commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
b27d2b3cd43db8f8b9251ff3fa370c4802770b44
modules/SofaGraphComponent/SofaGraphComponent_test/SceneChecker_test.cpp
modules/SofaGraphComponent/SofaGraphComponent_test/SceneChecker_test.cpp
#include <SofaTest/Sofa_test.h> using sofa::Sofa_test; #include <SofaGraphComponent/SceneCheckerVisitor.h> using sofa::simulation::SceneCheckerVisitor ; #include <SofaGraphComponent/SceneChecks.h> using namespace sofa::simulation::scenecheckers ; #include <sofa/helper/system/PluginManager.h> using sofa::helper::system::PluginManager ; #include <SofaSimulationCommon/SceneLoaderXML.h> using sofa::simulation::SceneLoaderXML ; using sofa::simulation::Node ; /////////////////////// COMPONENT DEFINITION & DECLARATION ///////////////////////////////////////// /// This component is only for testing the APIVersion system. //////////////////////////////////////////////////////////////////////////////////////////////////// #include <sofa/core/objectmodel/BaseObject.h> using sofa::core::objectmodel::BaseObject ; using sofa::core::objectmodel::Base ; #include <sofa/core/ObjectFactory.h> using sofa::core::ObjectFactory ; using sofa::core::ExecParams; class ComponentDeprecated : public BaseObject { public: SOFA_CLASS(ComponentDeprecated, BaseObject) ; public: }; SOFA_DECL_CLASS(ComponentDeprecated) int ComponentDeprecatedClassId = sofa::core::RegisterObject("") .add< ComponentDeprecated >() ; ////////////////////////////////////// TEST //////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// struct SceneChecker_test : public Sofa_test<> { void checkRequiredPlugin(bool missing) { EXPECT_MSG_EMIT(Error) ; EXPECT_MSG_NOEMIT(Warning); PluginManager::getInstance().loadPluginByName("SofaPython") ; std::string missStr = (missing)?"" : "<RequiredPlugin name='SofaPython'/> \n"; std::stringstream scene ; scene << "<?xml version='1.0'?>" << "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' > \n" << missStr << " <PythonScriptController classname='AClass' /> \n" << "</Node> \n" ; Node::SPtr root = SceneLoaderXML::loadFromMemory ("testscene", scene.str().c_str(), scene.str().size()) ; ASSERT_NE(root.get(), nullptr) ; root->init(ExecParams::defaultInstance()) ; SceneCheckerVisitor checker(ExecParams::defaultInstance()); checker.addCheck( SceneCheckMissingRequiredPlugin::newSPtr() ); if(missing) { EXPECT_MSG_EMIT(Warning); checker.validate(root.get()) ; }else{ EXPECT_MSG_NOEMIT(Warning); checker.validate(root.get()) ; } } void checkDuplicatedNames() { EXPECT_MSG_EMIT(Error) ; EXPECT_MSG_NOEMIT(Warning); std::stringstream scene ; scene << "<?xml version='1.0'?>" << "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' > \n" << " <Node name='nodeCheck'> \n" << " <Node name='nodeA' /> \n" << " <Node name='nodeA' /> \n" << " </Node> \n" << " <Node name='objectCheck'> \n" << " <OglModel name='objectA' /> \n" << " <OglModel name='objectA' /> \n" << " </Node> \n" << " <Node name='mixCheck'> \n" << " <Node name='mixA' /> \n" << " <OglModel name='mixA' /> \n" << " </Node> \n" << " <Node name='nothingCheck'> \n" << " <Node name='nodeA' /> \n" << " <OglModel name='objectA' /> \n" << " </Node> \n" << "</Node> \n" ; Node::SPtr root = SceneLoaderXML::loadFromMemory ("testscene", scene.str().c_str(), scene.str().size()) ; ASSERT_NE(root.get(), nullptr) ; root->init(ExecParams::defaultInstance()) ; SceneCheckerVisitor checker(ExecParams::defaultInstance()); checker.addCheck( SceneCheckDuplicatedName::newSPtr() ); std::vector<std::string> nodenames = {"nodeCheck", "objectCheck", "mixCheck"} ; for( auto& nodename : nodenames ) { EXPECT_MSG_EMIT(Warning); ASSERT_NE(root->getChild(nodename), nullptr) ; checker.validate(root->getChild(nodename)) ; } { EXPECT_MSG_NOEMIT(Warning); ASSERT_NE(root->getChild("nothingCheck"), nullptr) ; checker.validate(root->getChild("nothingCheck")) ; } } void checkAPIVersion(bool shouldWarn) { EXPECT_MSG_NOEMIT(Error) ; EXPECT_MSG_NOEMIT(Warning); std::string lvl = (shouldWarn)?"17.06":"17.12" ; std::stringstream scene ; scene << "<?xml version='1.0'?>" << "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' > \n" << " <APIVersion level='"<< lvl <<"'/> \n" << " <ComponentDeprecated /> \n" << "</Node> \n" ; Node::SPtr root = SceneLoaderXML::loadFromMemory ("testscene", scene.str().c_str(), scene.str().size()) ; ASSERT_NE(root.get(), nullptr) ; root->init(ExecParams::defaultInstance()) ; SceneCheckerVisitor checker(ExecParams::defaultInstance()); SceneCheckAPIChange::SPtr apichange = SceneCheckAPIChange::newSPtr() ; apichange->installDefaultChangeSets() ; apichange->addHookInChangeSet("17.06", [](Base* o){ if(o->getClassName() == "ComponentDeprecated") msg_warning(o) << "ComponentDeprecated have changed since 17.06." ; }) ; checker.addCheck(apichange) ; if(shouldWarn){ /// We check that running a scene set to 17.12 generate a warning on a 17.06 component EXPECT_MSG_EMIT(Warning) ; checker.validate(root.get()) ; } else { checker.validate(root.get()) ; } } }; TEST_F(SceneChecker_test, checkMissingRequiredPlugin ) { checkRequiredPlugin(true) ; } TEST_F(SceneChecker_test, checkPresentRequiredPlugin ) { checkRequiredPlugin(false) ; } TEST_F(SceneChecker_test, checkAPIVersion ) { checkAPIVersion(false) ; } TEST_F(SceneChecker_test, checkAPIVersionCurrent ) { checkAPIVersion(false) ; } TEST_F(SceneChecker_test, checkAPIVersionDeprecated ) { checkAPIVersion(true) ; } TEST_F(SceneChecker_test, checkDuplicatedNames ) { checkDuplicatedNames() ; }
#include <SofaTest/Sofa_test.h> using sofa::Sofa_test; #include <SofaGraphComponent/SceneCheckerVisitor.h> using sofa::simulation::SceneCheckerVisitor ; #include <SofaGraphComponent/SceneChecks.h> using namespace sofa::simulation::scenecheckers ; #include <sofa/helper/system/PluginManager.h> using sofa::helper::system::PluginManager ; #include <SofaSimulationCommon/SceneLoaderXML.h> using sofa::simulation::SceneLoaderXML ; using sofa::simulation::Node ; /////////////////////// COMPONENT DEFINITION & DECLARATION ///////////////////////////////////////// /// This component is only for testing the APIVersion system. //////////////////////////////////////////////////////////////////////////////////////////////////// #include <sofa/core/objectmodel/BaseObject.h> using sofa::core::objectmodel::BaseObject ; using sofa::core::objectmodel::Base ; #include <sofa/core/ObjectFactory.h> using sofa::core::ObjectFactory ; using sofa::core::ExecParams; class ComponentDeprecated : public BaseObject { public: SOFA_CLASS(ComponentDeprecated, BaseObject) ; public: }; SOFA_DECL_CLASS(ComponentDeprecated) int ComponentDeprecatedClassId = sofa::core::RegisterObject("") .add< ComponentDeprecated >() ; ////////////////////////////////////// TEST //////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// struct SceneChecker_test : public Sofa_test<> { void checkRequiredPlugin(bool missing) { EXPECT_MSG_EMIT(Error) ; EXPECT_MSG_NOEMIT(Warning); PluginManager::getInstance().loadPluginByName("SofaPython") ; std::string missStr = (missing)?"" : "<RequiredPlugin name='SofaPython'/> \n"; std::stringstream scene ; scene << "<?xml version='1.0'?>" << "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' > \n" << missStr << " <PythonScriptController classname='AClass' /> \n" << "</Node> \n" ; Node::SPtr root = SceneLoaderXML::loadFromMemory ("testscene", scene.str().c_str(), scene.str().size()) ; ASSERT_NE(root.get(), nullptr) ; root->init(ExecParams::defaultInstance()) ; SceneCheckerVisitor checker(ExecParams::defaultInstance()); checker.addCheck( SceneCheckMissingRequiredPlugin::newSPtr() ); if(missing) { EXPECT_MSG_EMIT(Warning); checker.validate(root.get()) ; }else{ EXPECT_MSG_NOEMIT(Warning); checker.validate(root.get()) ; } } void checkDuplicatedNames() { std::stringstream scene ; scene << "<?xml version='1.0'?>" << "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' > \n" << " <Node name='nodeCheck'> \n" << " <Node name='nodeA' /> \n" << " <Node name='nodeA' /> \n" << " </Node> \n" << " <Node name='objectCheck'> \n" << " <OglModel name='objectA' /> \n" << " <OglModel name='objectA' /> \n" << " </Node> \n" << " <Node name='mixCheck'> \n" << " <Node name='mixA' /> \n" << " <OglModel name='mixA' /> \n" << " </Node> \n" << " <Node name='nothingCheck'> \n" << " <Node name='nodeA' /> \n" << " <OglModel name='objectA' /> \n" << " </Node> \n" << "</Node> \n" ; Node::SPtr root = SceneLoaderXML::loadFromMemory ("testscene", scene.str().c_str(), scene.str().size()) ; ASSERT_NE(root.get(), nullptr) ; root->init(ExecParams::defaultInstance()) ; SceneCheckerVisitor checker(ExecParams::defaultInstance()); checker.addCheck( SceneCheckDuplicatedName::newSPtr() ); std::vector<std::string> nodenames = {"nodeCheck", "objectCheck", "mixCheck"} ; for( auto& nodename : nodenames ) { EXPECT_MSG_NOEMIT(Error) ; EXPECT_MSG_EMIT(Warning); ASSERT_NE(root->getChild(nodename), nullptr) ; checker.validate(root->getChild(nodename)) ; } { EXPECT_MSG_NOEMIT(Error); EXPECT_MSG_NOEMIT(Warning); ASSERT_NE(root->getChild("nothingCheck"), nullptr) ; checker.validate(root->getChild("nothingCheck")) ; } } void checkAPIVersion(bool shouldWarn) { EXPECT_MSG_NOEMIT(Error) ; EXPECT_MSG_NOEMIT(Warning); std::string lvl = (shouldWarn)?"17.06":"17.12" ; std::stringstream scene ; scene << "<?xml version='1.0'?>" << "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' > \n" << " <APIVersion level='"<< lvl <<"'/> \n" << " <ComponentDeprecated /> \n" << "</Node> \n" ; Node::SPtr root = SceneLoaderXML::loadFromMemory ("testscene", scene.str().c_str(), scene.str().size()) ; ASSERT_NE(root.get(), nullptr) ; root->init(ExecParams::defaultInstance()) ; SceneCheckerVisitor checker(ExecParams::defaultInstance()); SceneCheckAPIChange::SPtr apichange = SceneCheckAPIChange::newSPtr() ; apichange->installDefaultChangeSets() ; apichange->addHookInChangeSet("17.06", [](Base* o){ if(o->getClassName() == "ComponentDeprecated") msg_warning(o) << "ComponentDeprecated have changed since 17.06." ; }) ; checker.addCheck(apichange) ; if(shouldWarn){ /// We check that running a scene set to 17.12 generate a warning on a 17.06 component EXPECT_MSG_EMIT(Warning) ; checker.validate(root.get()) ; } else { checker.validate(root.get()) ; } } }; TEST_F(SceneChecker_test, checkMissingRequiredPlugin ) { checkRequiredPlugin(true) ; } TEST_F(SceneChecker_test, checkPresentRequiredPlugin ) { checkRequiredPlugin(false) ; } TEST_F(SceneChecker_test, checkAPIVersion ) { checkAPIVersion(false) ; } TEST_F(SceneChecker_test, checkAPIVersionCurrent ) { checkAPIVersion(false) ; } TEST_F(SceneChecker_test, checkAPIVersionDeprecated ) { checkAPIVersion(true) ; } TEST_F(SceneChecker_test, checkDuplicatedNames ) { checkDuplicatedNames() ; }
Fix the test that was wrong and thus failing.
[SceneChecker] Fix the test that was wrong and thus failing.
C++
lgpl-2.1
FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa
c0f070e4daba61a5eea67b8fe77fa958845cbc17
modules/planning/tasks/speed_optimizer.cc
modules/planning/tasks/speed_optimizer.cc
/****************************************************************************** * 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. *****************************************************************************/ /** * @file speed_optimizer.cc **/ #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/speed_limit.h" #include "modules/planning/tasks/speed_optimizer.h" namespace apollo { namespace planning { using apollo::planning_internal::StGraphBoundaryDebug; using apollo::planning_internal::STGraphDebug; SpeedOptimizer::SpeedOptimizer(const std::string& name) : Task(name) {} apollo::common::Status SpeedOptimizer::Execute( Frame* frame, ReferenceLineInfo* reference_line_info) { Task::Execute(frame, reference_line_info); auto ret = Process( reference_line_info->AdcSlBoundary(), reference_line_info->path_data(), frame->PlanningStartPoint(), reference_line_info->reference_line(), reference_line_info->path_decision(), reference_line_info->mutable_speed_data()); if (!ret.ok() && FLAGS_enable_slowdown_profile_generator && frame->PlanningStartPoint().v() > FLAGS_slowdown_speed_threshold) { *reference_line_info->mutable_speed_data() = GenerateStopProfile(frame->PlanningStartPoint().v()); } RecordDebugInfo(reference_line_info->speed_data()); return ret; } SpeedData SpeedOptimizer::GenerateStopProfile(const double init_speed) const { AERROR << "Slowing down the car."; SpeedData speed_data; const double min_acc = FLAGS_slowdown_profile_deceleration; const size_t max_t = 3.0; const double unit_t = 0.02; double pre_s = 0.0; double t = 0.0; while (t < max_t) { const double s = std::fmax(pre_s, init_speed * t + 0.5 * min_acc * t * t); const double v = std::fmax(0.0, init_speed + min_acc * t); speed_data.AppendSpeedPoint(s, t, v, min_acc, 0.0); pre_s = s; t += unit_t; } return speed_data; } void SpeedOptimizer::RecordDebugInfo(const SpeedData& speed_data) { auto debug = frame_->MutableADCTrajectory()->mutable_debug(); auto ptr_speed_plan = debug->mutable_planning_data()->add_speed_plan(); ptr_speed_plan->set_name(Name()); ptr_speed_plan->mutable_speed_point()->CopyFrom( {speed_data.speed_vector().begin(), speed_data.speed_vector().end()}); } void SpeedOptimizer::RecordSTGraphDebug( const std::vector<StBoundary>& boundaries, const SpeedLimit& speed_limits, const SpeedData& speed_data, STGraphDebug* st_graph_debug) { if (!FLAGS_enable_record_debug) { ADEBUG << "Skip record debug info"; return; } // auto debug = frame_->MutableADCTrajectory()->mutable_debug(); // auto st_graph_debug = debug->mutable_planning_data()->add_st_graph(); st_graph_debug->set_name(Name()); for (const auto boundary : boundaries) { auto boundary_debug = st_graph_debug->add_boundary(); boundary_debug->set_name(boundary.id()); switch (boundary.boundary_type()) { case StBoundary::BoundaryType::FOLLOW: boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_FOLLOW); break; case StBoundary::BoundaryType::OVERTAKE: boundary_debug->set_type( StGraphBoundaryDebug::ST_BOUNDARY_TYPE_OVERTAKE); break; case StBoundary::BoundaryType::STOP: boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_STOP); break; case StBoundary::BoundaryType::UNKNOWN: boundary_debug->set_type( StGraphBoundaryDebug::ST_BOUNDARY_TYPE_UNKNOWN); break; case StBoundary::BoundaryType::YIELD: boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_YIELD); break; } for (const auto point : boundary.points()) { auto point_debug = boundary_debug->add_point(); point_debug->set_t(point.x()); point_debug->set_s(point.y()); } } for (const auto point : speed_limits.speed_limit_points()) { common::SpeedPoint speed_point; speed_point.set_s(point.first); speed_point.set_v(point.second); st_graph_debug->add_speed_limit()->CopyFrom(speed_point); } st_graph_debug->mutable_speed_profile()->CopyFrom( {speed_data.speed_vector().begin(), speed_data.speed_vector().end()}); } } // namespace planning } // namespace apollo
/****************************************************************************** * 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. *****************************************************************************/ /** * @file speed_optimizer.cc **/ #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/speed_limit.h" #include "modules/planning/tasks/speed_optimizer.h" namespace apollo { namespace planning { using apollo::planning_internal::StGraphBoundaryDebug; using apollo::planning_internal::STGraphDebug; SpeedOptimizer::SpeedOptimizer(const std::string& name) : Task(name) {} apollo::common::Status SpeedOptimizer::Execute( Frame* frame, ReferenceLineInfo* reference_line_info) { Task::Execute(frame, reference_line_info); auto ret = Process( reference_line_info->AdcSlBoundary(), reference_line_info->path_data(), frame->PlanningStartPoint(), reference_line_info->reference_line(), reference_line_info->path_decision(), reference_line_info->mutable_speed_data()); if (!ret.ok() && FLAGS_enable_slowdown_profile_generator && frame->PlanningStartPoint().v() < FLAGS_slowdown_speed_threshold) { *reference_line_info->mutable_speed_data() = GenerateStopProfile(frame->PlanningStartPoint().v()); } RecordDebugInfo(reference_line_info->speed_data()); return ret; } SpeedData SpeedOptimizer::GenerateStopProfile(const double init_speed) const { AERROR << "Slowing down the car."; SpeedData speed_data; const double min_acc = FLAGS_slowdown_profile_deceleration; const size_t max_t = 3.0; const double unit_t = 0.02; double pre_s = 0.0; double t = 0.0; while (t < max_t) { const double s = std::fmax(pre_s, init_speed * t + 0.5 * min_acc * t * t); const double v = std::fmax(0.0, init_speed + min_acc * t); speed_data.AppendSpeedPoint(s, t, v, min_acc, 0.0); pre_s = s; t += unit_t; } return speed_data; } void SpeedOptimizer::RecordDebugInfo(const SpeedData& speed_data) { auto debug = frame_->MutableADCTrajectory()->mutable_debug(); auto ptr_speed_plan = debug->mutable_planning_data()->add_speed_plan(); ptr_speed_plan->set_name(Name()); ptr_speed_plan->mutable_speed_point()->CopyFrom( {speed_data.speed_vector().begin(), speed_data.speed_vector().end()}); } void SpeedOptimizer::RecordSTGraphDebug( const std::vector<StBoundary>& boundaries, const SpeedLimit& speed_limits, const SpeedData& speed_data, STGraphDebug* st_graph_debug) { if (!FLAGS_enable_record_debug) { ADEBUG << "Skip record debug info"; return; } // auto debug = frame_->MutableADCTrajectory()->mutable_debug(); // auto st_graph_debug = debug->mutable_planning_data()->add_st_graph(); st_graph_debug->set_name(Name()); for (const auto boundary : boundaries) { auto boundary_debug = st_graph_debug->add_boundary(); boundary_debug->set_name(boundary.id()); switch (boundary.boundary_type()) { case StBoundary::BoundaryType::FOLLOW: boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_FOLLOW); break; case StBoundary::BoundaryType::OVERTAKE: boundary_debug->set_type( StGraphBoundaryDebug::ST_BOUNDARY_TYPE_OVERTAKE); break; case StBoundary::BoundaryType::STOP: boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_STOP); break; case StBoundary::BoundaryType::UNKNOWN: boundary_debug->set_type( StGraphBoundaryDebug::ST_BOUNDARY_TYPE_UNKNOWN); break; case StBoundary::BoundaryType::YIELD: boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_YIELD); break; } for (const auto point : boundary.points()) { auto point_debug = boundary_debug->add_point(); point_debug->set_t(point.x()); point_debug->set_s(point.y()); } } for (const auto point : speed_limits.speed_limit_points()) { common::SpeedPoint speed_point; speed_point.set_s(point.first); speed_point.set_v(point.second); st_graph_debug->add_speed_limit()->CopyFrom(speed_point); } st_graph_debug->mutable_speed_profile()->CopyFrom( {speed_data.speed_vector().begin(), speed_data.speed_vector().end()}); } } // namespace planning } // namespace apollo
fix slowdown speed threshold condition bug.
planning: fix slowdown speed threshold condition bug.
C++
apache-2.0
msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo
741c098adaca051b29a5a441a2d51da402eb754a
libs/bayesian/src/bp.cpp
libs/bayesian/src/bp.cpp
#include <algorithm> #include <functional> #include "bayesian/graph.hpp" #include "bayesian/bp.hpp" #include "bayesian/cpt.hpp" // unordered_mapのネストの解決 namespace bn { bp::bp(graph_t const& graph) : graph_(graph) { } bp::return_type bp::operator()(std::unordered_map<vertex_type, matrix_type> const& precondition) { initialize(); lambda_ = precondition; // 最下流にall 1,最上流にevidenceを当てはめる for(auto const& node : graph_.vertex_list()) { if(graph_.in_edges(node).empty()) { auto& pi = pi_[node]; auto& data = node->cpt[condition_t()].second; pi.resize(1, node->selectable_num); pi.assign(data.cbegin(), data.cend()); } if(graph_.out_edges(node).empty()) { if(lambda_.find(node) == lambda_.cend()) { lambda_[node].resize(1, node->selectable_num, 1.0); } } } // すべてのpiとlambdaのうち,計算されていないものを計算する // ついでに返すための値を作っていく return_type result; for(auto const& node : graph_.vertex_list()) { if(pi_.find(node) == pi_.cend()) { calculate_pi(node); } if(lambda_.find(node) == lambda_.cend()) { calculate_lambda(node); } // 上からの確率と下からの確率を掛けあわせ,正規化する auto raw_bel = pi_[node] % lambda_[node]; result[node] = normalize(raw_bel); } return result; } void bp::initialize() { pi_.clear(); lambda_.clear(); pi_i_.clear(); lambda_k_.clear(); } matrix_type& bp::normalize(matrix_type& target) { double sum = 0; for(std::size_t i = 0; i < target.height(); ++i) for(std::size_t j = 0; j < target.width(); ++j) sum += target[i][j]; for(std::size_t i = 0; i < target.height(); ++i) for(std::size_t j = 0; j < target.width(); ++j) target[i][j] /= sum; return target; } void bp::calculate_pi(vertex_type const& target) { if(pi_.find(target) != pi_.cend()) return; auto const in_vertexs = graph_.in_vertexs(target); // 事前にpi_iを更新させる for(auto const& xi : in_vertexs) calculate_pi_i(target, xi); matrix_type matrix(1, target->selectable_num, 0.0); all_combination_pattern( in_vertexs, [&](condition_t const& condition) { auto const& cpt_data = target->cpt[condition].second; for(int i = 0; i < target->selectable_num; ++i) { double value = cpt_data[i]; for(auto const& xi : in_vertexs) { value *= pi_i_[target][xi][0][condition.at(xi)]; } matrix[0][i] += value; } }); // 計算された値でpiを更新させる pi_[target] = matrix; } void bp::calculate_pi_i(vertex_type const& from, vertex_type const& target) { if(pi_i_[from].find(target) != pi_i_[from].end()) return; auto out_vertexs = graph_.out_vertexs(target); out_vertexs.erase(std::find(out_vertexs.cbegin(), out_vertexs.cend(), from)); // 事前にpiやlambda_kを更新させる calculate_pi(target); for(auto const& xj : out_vertexs) calculate_lambda_k(xj, target); matrix_type matrix = pi_[target]; for(int i = 0; i < target->selectable_num; ++i) { for(auto const& xj : out_vertexs) { matrix[0][i] *= lambda_k_[xj][target][0][i]; } } // 計算された値でpi_iを更新させる pi_i_[from][target] = matrix; } void bp::calculate_lambda(vertex_type const& target) { if(lambda_.find(target) != lambda_.cend()) return; auto const out_vertexs = graph_.out_vertexs(target); // 事前にlambda_kを更新させる for(auto const& xi : out_vertexs) calculate_lambda_k(xi, target); matrix_type matrix(1, target->selectable_num, 1.0); for(int i = 0; i < target->selectable_num; ++i) { for(auto const& xi : out_vertexs) { matrix[0][i] *= lambda_k_[xi][target][0][i]; } } // 計算された値でlambdaを更新させる lambda_[target] = matrix; } void bp::calculate_lambda_k(vertex_type const& from, vertex_type const& target) { if(lambda_k_[from].find(target) != lambda_k_[from].end()) return; auto const in_vertexs = graph_.in_vertexs(from); // 事前にlambdaを更新させる calculate_lambda(from); for(auto const& xl : in_vertexs) if(xl != target) calculate_pi_i(from, xl); matrix_type matrix(1, target->selectable_num, 0.0); for(int i = 0; i < from->selectable_num; ++i) { auto const times = lambda_[from][0][i]; all_combination_pattern( in_vertexs, [&](condition_t const& cond) { double value = times * from->cpt[cond].second[i]; for(auto const& p : cond) { if(p.first != target) { value *= pi_i_[from][p.first][0][p.second]; } } matrix[0][cond.at(target)] += value; }); } // 計算された値でlambdaを更新させる lambda_k_[from][target] = matrix; } // 与えられた確率変数全ての組み合わせに対し,functionを実行するというインターフェースを提供する void bp::all_combination_pattern( std::vector<vertex_type> const& combination, std::function<void(condition_t const&)> const& function ) { typedef std::vector<vertex_type>::const_iterator iterator_type; std::function<void(iterator_type const, iterator_type const&)> recursive; condition_t condition; recursive = [&](iterator_type const it, iterator_type const& end) { if(it == end) { function(condition); } else { for(int i = 0; i < (*it)->selectable_num; ++i) { condition[*it] = i; recursive(it + 1, end); } } }; recursive(combination.cbegin(), combination.cend()); } } // namespace bn
#include <algorithm> #include <functional> #include "bayesian/graph.hpp" #include "bayesian/bp.hpp" #include "bayesian/cpt.hpp" // unordered_mapのネストの解決 namespace bn { bp::bp(graph_t const& graph) : graph_(graph) { } bp::return_type bp::operator()(std::unordered_map<vertex_type, matrix_type> const& precondition) { initialize(); lambda_ = precondition; pi_ = precondition; // 最下流にall 1,最上流にevidenceを当てはめる for(auto const& node : graph_.vertex_list()) { if(graph_.in_edges(node).empty() && pi_.find(node) == pi_.cend()) { auto& pi = pi_[node]; auto& data = node->cpt[condition_t()].second; pi.resize(1, node->selectable_num); pi.assign(data.cbegin(), data.cend()); } if(graph_.out_edges(node).empty() && lambda_.find(node) == lambda_.cend()) { lambda_[node].resize(1, node->selectable_num, 1.0); } } // すべてのpiとlambdaのうち,計算されていないものを計算する // ついでに返すための値を作っていく return_type result; for(auto const& node : graph_.vertex_list()) { if(pi_.find(node) == pi_.cend()) { calculate_pi(node); } if(lambda_.find(node) == lambda_.cend()) { calculate_lambda(node); } // 上からの確率と下からの確率を掛けあわせ,正規化する auto raw_bel = pi_[node] % lambda_[node]; result[node] = normalize(raw_bel); } return result; } void bp::initialize() { pi_.clear(); lambda_.clear(); pi_i_.clear(); lambda_k_.clear(); } matrix_type& bp::normalize(matrix_type& target) { double sum = 0; for(std::size_t i = 0; i < target.height(); ++i) for(std::size_t j = 0; j < target.width(); ++j) sum += target[i][j]; for(std::size_t i = 0; i < target.height(); ++i) for(std::size_t j = 0; j < target.width(); ++j) target[i][j] /= sum; return target; } void bp::calculate_pi(vertex_type const& target) { if(pi_.find(target) != pi_.cend()) return; auto const in_vertexs = graph_.in_vertexs(target); // 事前にpi_iを更新させる for(auto const& xi : in_vertexs) calculate_pi_i(target, xi); matrix_type matrix(1, target->selectable_num, 0.0); all_combination_pattern( in_vertexs, [&](condition_t const& condition) { auto const& cpt_data = target->cpt[condition].second; for(int i = 0; i < target->selectable_num; ++i) { double value = cpt_data[i]; for(auto const& xi : in_vertexs) { value *= pi_i_[target][xi][0][condition.at(xi)]; } matrix[0][i] += value; } }); // 計算された値でpiを更新させる pi_[target] = matrix; } void bp::calculate_pi_i(vertex_type const& from, vertex_type const& target) { if(pi_i_[from].find(target) != pi_i_[from].end()) return; auto out_vertexs = graph_.out_vertexs(target); out_vertexs.erase(std::find(out_vertexs.cbegin(), out_vertexs.cend(), from)); // 事前にpiやlambda_kを更新させる calculate_pi(target); for(auto const& xj : out_vertexs) calculate_lambda_k(xj, target); matrix_type matrix = pi_[target]; for(int i = 0; i < target->selectable_num; ++i) { for(auto const& xj : out_vertexs) { matrix[0][i] *= lambda_k_[xj][target][0][i]; } } // 計算された値でpi_iを更新させる pi_i_[from][target] = matrix; } void bp::calculate_lambda(vertex_type const& target) { if(lambda_.find(target) != lambda_.cend()) return; auto const out_vertexs = graph_.out_vertexs(target); // 事前にlambda_kを更新させる for(auto const& xi : out_vertexs) calculate_lambda_k(xi, target); matrix_type matrix(1, target->selectable_num, 1.0); for(int i = 0; i < target->selectable_num; ++i) { for(auto const& xi : out_vertexs) { matrix[0][i] *= lambda_k_[xi][target][0][i]; } } // 計算された値でlambdaを更新させる lambda_[target] = matrix; } void bp::calculate_lambda_k(vertex_type const& from, vertex_type const& target) { if(lambda_k_[from].find(target) != lambda_k_[from].end()) return; auto const in_vertexs = graph_.in_vertexs(from); // 事前にlambdaを更新させる calculate_lambda(from); for(auto const& xl : in_vertexs) if(xl != target) calculate_pi_i(from, xl); matrix_type matrix(1, target->selectable_num, 0.0); for(int i = 0; i < from->selectable_num; ++i) { auto const times = lambda_[from][0][i]; all_combination_pattern( in_vertexs, [&](condition_t const& cond) { double value = times * from->cpt[cond].second[i]; for(auto const& p : cond) { if(p.first != target) { value *= pi_i_[from][p.first][0][p.second]; } } matrix[0][cond.at(target)] += value; }); } // 計算された値でlambdaを更新させる lambda_k_[from][target] = matrix; } // 与えられた確率変数全ての組み合わせに対し,functionを実行するというインターフェースを提供する void bp::all_combination_pattern( std::vector<vertex_type> const& combination, std::function<void(condition_t const&)> const& function ) { typedef std::vector<vertex_type>::const_iterator iterator_type; std::function<void(iterator_type const, iterator_type const&)> recursive; condition_t condition; recursive = [&](iterator_type const it, iterator_type const& end) { if(it == end) { function(condition); } else { for(int i = 0; i < (*it)->selectable_num; ++i) { condition[*it] = i; recursive(it + 1, end); } } }; recursive(combination.cbegin(), combination.cend()); } } // namespace bn
Fix initialize by precondition. pi_ and lambda_ are init from the same argument.
Fix initialize by precondition. pi_ and lambda_ are init from the same argument. Signed-off-by: Godai Azuma <[email protected]>
C++
mit
godai0519/BayesianNetwork
2abeeb9bea090f2306a5f574ae0a660faaf793bb
source/process/common/RouterInitializer.cpp
source/process/common/RouterInitializer.cpp
/** * @file process/RouterInitializer.cpp * @date Created <2014-05-20 16:36:32> * * This file is generated by generators/router_initializer.rb from config file * generators/router_initializer.yml. Do not edit this file directly. Please read * the config file, update options there and re-run the ruby script to * update this file. */ #include "RouterInitializer.h" #include <util/driver/ActionHandler.h> #include <memory> // for std::auto_ptr #include "controllers/CommandsController.h" #include "controllers/DocumentsController.h" #include "controllers/StatusController.h" #include "controllers/CollectionController.h" #include "controllers/LaserController.h" #include "controllers/AdController.h" namespace sf1r { void initializeDriverRouter(::izenelib::driver::Router& router, IService* service, bool enableTest) { { CommandsController commands; const std::string controllerName("commands"); typedef ::izenelib::driver::ActionHandler<CommandsController> handler_type; typedef std::auto_ptr<handler_type> handler_ptr; handler_ptr indexHandler( new handler_type( commands, &CommandsController::index ) ); router.map( controllerName, "index", indexHandler.get() ); indexHandler.release(); handler_ptr load_laser_clusteringHandler( new handler_type( commands, &CommandsController::load_laser_clustering ) ); router.map( controllerName, "load_laser_clustering", load_laser_clusteringHandler.get() ); load_laser_clusteringHandler.release(); handler_ptr miningHandler( new handler_type( commands, &CommandsController::mining ) ); router.map( controllerName, "mining", miningHandler.get() ); miningHandler.release(); handler_ptr optimize_indexHandler( new handler_type( commands, &CommandsController::optimize_index ) ); router.map( controllerName, "optimize_index", optimize_indexHandler.get() ); optimize_indexHandler.release(); handler_ptr train_ctr_modelHandler( new handler_type( commands, &CommandsController::train_ctr_model ) ); router.map( controllerName, "train_ctr_model", train_ctr_modelHandler.get() ); train_ctr_modelHandler.release(); } { DocumentsController documents; const std::string controllerName("documents"); typedef ::izenelib::driver::ActionHandler<DocumentsController> handler_type; typedef std::auto_ptr<handler_type> handler_ptr; handler_ptr createHandler( new handler_type( documents, &DocumentsController::create ) ); router.map( controllerName, "create", createHandler.get() ); createHandler.release(); handler_ptr destroyHandler( new handler_type( documents, &DocumentsController::destroy ) ); router.map( controllerName, "destroy", destroyHandler.get() ); destroyHandler.release(); handler_ptr getHandler( new handler_type( documents, &DocumentsController::get ) ); router.map( controllerName, "get", getHandler.get() ); getHandler.release(); handler_ptr get_doc_countHandler( new handler_type( documents, &DocumentsController::get_doc_count ) ); router.map( controllerName, "get_doc_count", get_doc_countHandler.get() ); get_doc_countHandler.release(); handler_ptr get_freq_group_labelsHandler( new handler_type( documents, &DocumentsController::get_freq_group_labels ) ); router.map( controllerName, "get_freq_group_labels", get_freq_group_labelsHandler.get() ); get_freq_group_labelsHandler.release(); handler_ptr get_key_countHandler( new handler_type( documents, &DocumentsController::get_key_count ) ); router.map( controllerName, "get_key_count", get_key_countHandler.get() ); get_key_countHandler.release(); handler_ptr indexHandler( new handler_type( documents, &DocumentsController::index ) ); router.map( controllerName, "index", indexHandler.get() ); indexHandler.release(); handler_ptr log_group_labelHandler( new handler_type( documents, &DocumentsController::log_group_label ) ); router.map( controllerName, "log_group_label", log_group_labelHandler.get() ); log_group_labelHandler.release(); handler_ptr searchHandler( new handler_type( documents, &DocumentsController::search ) ); router.map( controllerName, "search", searchHandler.get() ); searchHandler.release(); handler_ptr set_top_group_labelHandler( new handler_type( documents, &DocumentsController::set_top_group_label ) ); router.map( controllerName, "set_top_group_label", set_top_group_labelHandler.get() ); set_top_group_labelHandler.release(); handler_ptr updateHandler( new handler_type( documents, &DocumentsController::update ) ); router.map( controllerName, "update", updateHandler.get() ); updateHandler.release(); handler_ptr update_inplaceHandler( new handler_type( documents, &DocumentsController::update_inplace ) ); router.map( controllerName, "update_inplace", update_inplaceHandler.get() ); update_inplaceHandler.release(); handler_ptr visitHandler( new handler_type( documents, &DocumentsController::visit ) ); router.map( controllerName, "visit", visitHandler.get() ); visitHandler.release(); } { StatusController status; const std::string controllerName("status"); typedef ::izenelib::driver::ActionHandler<StatusController> handler_type; typedef std::auto_ptr<handler_type> handler_ptr; handler_ptr get_distribute_statusHandler( new handler_type( status, &StatusController::get_distribute_status ) ); router.map( controllerName, "get_distribute_status", get_distribute_statusHandler.get() ); get_distribute_statusHandler.release(); handler_ptr indexHandler( new handler_type( status, &StatusController::index ) ); router.map( controllerName, "index", indexHandler.get() ); indexHandler.release(); } { CollectionController collection; const std::string controllerName("collection"); typedef ::izenelib::driver::ActionHandler<CollectionController> handler_type; typedef std::auto_ptr<handler_type> handler_ptr; handler_ptr add_sharding_nodesHandler( new handler_type( collection, &CollectionController::add_sharding_nodes ) ); router.map( controllerName, "add_sharding_nodes", add_sharding_nodesHandler.get() ); add_sharding_nodesHandler.release(); handler_ptr backup_allHandler( new handler_type( collection, &CollectionController::backup_all ) ); router.map( controllerName, "backup_all", backup_allHandler.get() ); backup_allHandler.release(); handler_ptr check_collectionHandler( new handler_type( collection, &CollectionController::check_collection ) ); router.map( controllerName, "check_collection", check_collectionHandler.get() ); check_collectionHandler.release(); handler_ptr create_collectionHandler( new handler_type( collection, &CollectionController::create_collection ) ); router.map( controllerName, "create_collection", create_collectionHandler.get() ); create_collectionHandler.release(); handler_ptr delete_collectionHandler( new handler_type( collection, &CollectionController::delete_collection ) ); router.map( controllerName, "delete_collection", delete_collectionHandler.get() ); delete_collectionHandler.release(); handler_ptr rebuild_collectionHandler( new handler_type( collection, &CollectionController::rebuild_collection ) ); router.map( controllerName, "rebuild_collection", rebuild_collectionHandler.get() ); rebuild_collectionHandler.release(); handler_ptr rebuild_from_scdHandler( new handler_type( collection, &CollectionController::rebuild_from_scd ) ); router.map( controllerName, "rebuild_from_scd", rebuild_from_scdHandler.get() ); rebuild_from_scdHandler.release(); handler_ptr start_collectionHandler( new handler_type( collection, &CollectionController::start_collection ) ); router.map( controllerName, "start_collection", start_collectionHandler.get() ); start_collectionHandler.release(); handler_ptr stop_collectionHandler( new handler_type( collection, &CollectionController::stop_collection ) ); router.map( controllerName, "stop_collection", stop_collectionHandler.get() ); stop_collectionHandler.release(); handler_ptr update_collection_confHandler( new handler_type( collection, &CollectionController::update_collection_conf ) ); router.map( controllerName, "update_collection_conf", update_collection_confHandler.get() ); update_collection_confHandler.release(); handler_ptr update_sharding_confHandler( new handler_type( collection, &CollectionController::update_sharding_conf ) ); router.map( controllerName, "update_sharding_conf", update_sharding_confHandler.get() ); update_sharding_confHandler.release(); } { LaserController laser; const std::string controllerName("laser"); typedef ::izenelib::driver::ActionHandler<LaserController> handler_type; typedef std::auto_ptr<handler_type> handler_ptr; handler_ptr recommendHandler( new handler_type( laser, &LaserController::recommend ) ); router.map( controllerName, "recommend", recommendHandler.get() ); recommendHandler.release(); } { /*AdController ad; const std::string controllerName("ad"); typedef ::izenelib::driver::ActionHandler<AdController> handler_type; typedef std::auto_ptr<handler_type> handler_ptr; handler_ptr set_ad_bid_phraseHandler( new handler_type( ad, &AdController::set_ad_bid_phrase ) ); router.map( controllerName, "set_ad_bid_phrase", set_ad_bid_phraseHandler.get() ); set_ad_bid_phraseHandler.release(); handler_ptr set_ad_campaign_budgetHandler( new handler_type( ad, &AdController::set_ad_campaign_budget ) ); router.map( controllerName, "set_ad_campaign_budget", set_ad_campaign_budgetHandler.get() ); set_ad_campaign_budgetHandler.release(); handler_ptr set_keyword_bidpriceHandler( new handler_type( ad, &AdController::set_keyword_bidprice ) ); router.map( controllerName, "set_keyword_bidprice", set_keyword_bidpriceHandler.get() ); set_keyword_bidpriceHandler.release();*/ } } } // namespace sf1r
/** * @file process/RouterInitializer.cpp * @date Created <2014-05-20 16:36:32> * * This file is generated by generators/router_initializer.rb from config file * generators/router_initializer.yml. Do not edit this file directly. Please read * the config file, update options there and re-run the ruby script to * update this file. */ #include "RouterInitializer.h" #include <util/driver/ActionHandler.h> #include <memory> // for std::auto_ptr #include "controllers/CommandsController.h" #include "controllers/DocumentsController.h" #include "controllers/StatusController.h" #include "controllers/CollectionController.h" #include "controllers/LaserController.h" #include "controllers/AdController.h" namespace sf1r { void initializeDriverRouter(::izenelib::driver::Router& router, IService* service, bool enableTest) { { CommandsController commands; const std::string controllerName("commands"); typedef ::izenelib::driver::ActionHandler<CommandsController> handler_type; typedef std::auto_ptr<handler_type> handler_ptr; handler_ptr indexHandler( new handler_type( commands, &CommandsController::index ) ); router.map( controllerName, "index", indexHandler.get() ); indexHandler.release(); handler_ptr load_laser_clusteringHandler( new handler_type( commands, &CommandsController::load_laser_clustering ) ); router.map( controllerName, "load_laser_clustering", load_laser_clusteringHandler.get() ); load_laser_clusteringHandler.release(); handler_ptr miningHandler( new handler_type( commands, &CommandsController::mining ) ); router.map( controllerName, "mining", miningHandler.get() ); miningHandler.release(); handler_ptr optimize_indexHandler( new handler_type( commands, &CommandsController::optimize_index ) ); router.map( controllerName, "optimize_index", optimize_indexHandler.get() ); optimize_indexHandler.release(); handler_ptr train_ctr_modelHandler( new handler_type( commands, &CommandsController::train_ctr_model ) ); router.map( controllerName, "train_ctr_model", train_ctr_modelHandler.get() ); train_ctr_modelHandler.release(); } { DocumentsController documents; const std::string controllerName("documents"); typedef ::izenelib::driver::ActionHandler<DocumentsController> handler_type; typedef std::auto_ptr<handler_type> handler_ptr; handler_ptr createHandler( new handler_type( documents, &DocumentsController::create ) ); router.map( controllerName, "create", createHandler.get() ); createHandler.release(); handler_ptr destroyHandler( new handler_type( documents, &DocumentsController::destroy ) ); router.map( controllerName, "destroy", destroyHandler.get() ); destroyHandler.release(); handler_ptr getHandler( new handler_type( documents, &DocumentsController::get ) ); router.map( controllerName, "get", getHandler.get() ); getHandler.release(); handler_ptr get_doc_countHandler( new handler_type( documents, &DocumentsController::get_doc_count ) ); router.map( controllerName, "get_doc_count", get_doc_countHandler.get() ); get_doc_countHandler.release(); handler_ptr get_freq_group_labelsHandler( new handler_type( documents, &DocumentsController::get_freq_group_labels ) ); router.map( controllerName, "get_freq_group_labels", get_freq_group_labelsHandler.get() ); get_freq_group_labelsHandler.release(); handler_ptr get_key_countHandler( new handler_type( documents, &DocumentsController::get_key_count ) ); router.map( controllerName, "get_key_count", get_key_countHandler.get() ); get_key_countHandler.release(); handler_ptr indexHandler( new handler_type( documents, &DocumentsController::index ) ); router.map( controllerName, "index", indexHandler.get() ); indexHandler.release(); handler_ptr log_group_labelHandler( new handler_type( documents, &DocumentsController::log_group_label ) ); router.map( controllerName, "log_group_label", log_group_labelHandler.get() ); log_group_labelHandler.release(); handler_ptr searchHandler( new handler_type( documents, &DocumentsController::search ) ); router.map( controllerName, "search", searchHandler.get() ); searchHandler.release(); handler_ptr set_top_group_labelHandler( new handler_type( documents, &DocumentsController::set_top_group_label ) ); router.map( controllerName, "set_top_group_label", set_top_group_labelHandler.get() ); set_top_group_labelHandler.release(); handler_ptr updateHandler( new handler_type( documents, &DocumentsController::update ) ); router.map( controllerName, "update", updateHandler.get() ); updateHandler.release(); handler_ptr update_inplaceHandler( new handler_type( documents, &DocumentsController::update_inplace ) ); router.map( controllerName, "update_inplace", update_inplaceHandler.get() ); update_inplaceHandler.release(); handler_ptr visitHandler( new handler_type( documents, &DocumentsController::visit ) ); router.map( controllerName, "visit", visitHandler.get() ); visitHandler.release(); } { StatusController status; const std::string controllerName("status"); typedef ::izenelib::driver::ActionHandler<StatusController> handler_type; typedef std::auto_ptr<handler_type> handler_ptr; handler_ptr get_distribute_statusHandler( new handler_type( status, &StatusController::get_distribute_status ) ); router.map( controllerName, "get_distribute_status", get_distribute_statusHandler.get() ); get_distribute_statusHandler.release(); handler_ptr indexHandler( new handler_type( status, &StatusController::index ) ); router.map( controllerName, "index", indexHandler.get() ); indexHandler.release(); } { CollectionController collection; const std::string controllerName("collection"); typedef ::izenelib::driver::ActionHandler<CollectionController> handler_type; typedef std::auto_ptr<handler_type> handler_ptr; handler_ptr add_sharding_nodesHandler( new handler_type( collection, &CollectionController::add_sharding_nodes ) ); router.map( controllerName, "add_sharding_nodes", add_sharding_nodesHandler.get() ); add_sharding_nodesHandler.release(); handler_ptr backup_allHandler( new handler_type( collection, &CollectionController::backup_all ) ); router.map( controllerName, "backup_all", backup_allHandler.get() ); backup_allHandler.release(); handler_ptr check_collectionHandler( new handler_type( collection, &CollectionController::check_collection ) ); router.map( controllerName, "check_collection", check_collectionHandler.get() ); check_collectionHandler.release(); handler_ptr create_collectionHandler( new handler_type( collection, &CollectionController::create_collection ) ); router.map( controllerName, "create_collection", create_collectionHandler.get() ); create_collectionHandler.release(); handler_ptr delete_collectionHandler( new handler_type( collection, &CollectionController::delete_collection ) ); router.map( controllerName, "delete_collection", delete_collectionHandler.get() ); delete_collectionHandler.release(); handler_ptr rebuild_collectionHandler( new handler_type( collection, &CollectionController::rebuild_collection ) ); router.map( controllerName, "rebuild_collection", rebuild_collectionHandler.get() ); rebuild_collectionHandler.release(); handler_ptr rebuild_from_scdHandler( new handler_type( collection, &CollectionController::rebuild_from_scd ) ); router.map( controllerName, "rebuild_from_scd", rebuild_from_scdHandler.get() ); rebuild_from_scdHandler.release(); handler_ptr start_collectionHandler( new handler_type( collection, &CollectionController::start_collection ) ); router.map( controllerName, "start_collection", start_collectionHandler.get() ); start_collectionHandler.release(); handler_ptr stop_collectionHandler( new handler_type( collection, &CollectionController::stop_collection ) ); router.map( controllerName, "stop_collection", stop_collectionHandler.get() ); stop_collectionHandler.release(); handler_ptr update_collection_confHandler( new handler_type( collection, &CollectionController::update_collection_conf ) ); router.map( controllerName, "update_collection_conf", update_collection_confHandler.get() ); update_collection_confHandler.release(); handler_ptr update_sharding_confHandler( new handler_type( collection, &CollectionController::update_sharding_conf ) ); router.map( controllerName, "update_sharding_conf", update_sharding_confHandler.get() ); update_sharding_confHandler.release(); } { LaserController laser; const std::string controllerName("laser"); typedef ::izenelib::driver::ActionHandler<LaserController> handler_type; typedef std::auto_ptr<handler_type> handler_ptr; handler_ptr recommendHandler( new handler_type( laser, &LaserController::recommend ) ); router.map( controllerName, "recommend", recommendHandler.get() ); recommendHandler.release(); } { AdController ad; const std::string controllerName("ad"); typedef ::izenelib::driver::ActionHandler<AdController> handler_type; typedef std::auto_ptr<handler_type> handler_ptr; handler_ptr set_ad_bid_phraseHandler( new handler_type( ad, &AdController::set_ad_bid_phrase ) ); router.map( controllerName, "set_ad_bid_phrase", set_ad_bid_phraseHandler.get() ); set_ad_bid_phraseHandler.release(); handler_ptr set_ad_campaign_budgetHandler( new handler_type( ad, &AdController::set_ad_campaign_budget ) ); router.map( controllerName, "set_ad_campaign_budget", set_ad_campaign_budgetHandler.get() ); set_ad_campaign_budgetHandler.release(); handler_ptr set_keyword_bidpriceHandler( new handler_type( ad, &AdController::set_keyword_bidprice ) ); router.map( controllerName, "set_keyword_bidprice", set_keyword_bidpriceHandler.get() ); set_keyword_bidpriceHandler.release(); } } } // namespace sf1r
Revert "comment code to package"
Revert "comment code to package" This reverts commit 837f66a5ee06d6f6226541b0632474925c3ef9d9.
C++
apache-2.0
izenecloud/sf1r-ad-delivery,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-ad-delivery
58cd63a6f1adf155c2b6ca97c0f0b9291431211e
src/thread/posixthread.cpp
src/thread/posixthread.cpp
/** * @file posix/wait.cpp * @brief POSIX event/timeout handling * * (c) 2013-2014 by Mega Limited, Wellsford, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include "mega.h" #include "mega/thread/posixthread.h" #ifdef USE_PTHREAD namespace mega { PosixThread::PosixThread() { thread = new pthread_t; } void PosixThread::start(void *(*start_routine)(void*), void *parameter) { pthread_create(thread, NULL, start_routine, parameter); } void PosixThread::join() { pthread_join(*thread, NULL); } PosixThread::~PosixThread() { delete thread; } //PosixMutex PosixMutex::PosixMutex() { mutex = NULL; attr = NULL; } void PosixMutex::init(bool recursive) { if(recursive) { mutex = new pthread_mutex_t; attr = new pthread_mutexattr_t; pthread_mutexattr_init(attr); pthread_mutexattr_settype(attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(mutex, attr); } else { mutex = new pthread_mutex_t; pthread_mutex_init(mutex, NULL); } } void PosixMutex::lock() { pthread_mutex_lock(mutex); } void PosixMutex::unlock() { pthread_mutex_unlock(mutex); } PosixMutex::~PosixMutex() { pthread_mutex_destroy(mutex); delete mutex; if (attr) { pthread_mutexattr_destroy(attr); delete attr; } } //PosixSemaphore PosixSemaphore::PosixSemaphore() { semaphore = new sem_t; if (sem_init(semaphore, 0, 0) == -1) { LOG_fatal << "Error creating semaphore: " << errno; } } void PosixSemaphore::wait() { while (sem_wait(&semaphore) == -1) { if (errno == EINTR) { continue; } LOG_fatal << "Error in sem_wait: " << errno; } } static inline void timespec_add_msec(struct timespec *tv, int milliseconds) { int seconds = milliseconds / 1000; int milliseconds_left = milliseconds % 1000; tv->tv_sec += seconds; tv->tv_nsec += milliseconds_left * 1000000; if (tv->tv_nsec >= 1000000000) { tv->tv_nsec -= 1000000000; tv->tv_sec++; } } int PosixSemaphore::timedwait(int milliseconds) { int ret; struct timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts) == -1) { LOG_err << "Error in clock_gettime"; return -2; } timespec_add_msec (&ts, milliseconds); while (true) { ret = sem_timedwait(semaphore, &ts); if (!ret) { return 0; } if (errno == ETIMEDOUT) { return -1; } if (errno == EINTR) { continue; } LOG_err << "Error in sem_timedwait: " << errno; return -2; } } void PosixSemaphore::release() { if (sem_post(semaphore) == -1) { LOG_fatal << "Error in sem_post: " << errno; } } PosixSemaphore::~PosixSemaphore() { sem_destroy(semaphore); delete semaphore; } }// namespace #endif
/** * @file posix/wait.cpp * @brief POSIX event/timeout handling * * (c) 2013-2014 by Mega Limited, Wellsford, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include "mega.h" #include "mega/thread/posixthread.h" #ifdef USE_PTHREAD namespace mega { PosixThread::PosixThread() { thread = new pthread_t; } void PosixThread::start(void *(*start_routine)(void*), void *parameter) { pthread_create(thread, NULL, start_routine, parameter); } void PosixThread::join() { pthread_join(*thread, NULL); } PosixThread::~PosixThread() { delete thread; } //PosixMutex PosixMutex::PosixMutex() { mutex = NULL; attr = NULL; } void PosixMutex::init(bool recursive) { if(recursive) { mutex = new pthread_mutex_t; attr = new pthread_mutexattr_t; pthread_mutexattr_init(attr); pthread_mutexattr_settype(attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(mutex, attr); } else { mutex = new pthread_mutex_t; pthread_mutex_init(mutex, NULL); } } void PosixMutex::lock() { pthread_mutex_lock(mutex); } void PosixMutex::unlock() { pthread_mutex_unlock(mutex); } PosixMutex::~PosixMutex() { if (mutex) { pthread_mutex_destroy(mutex); delete mutex; } if (attr) { pthread_mutexattr_destroy(attr); delete attr; } } //PosixSemaphore PosixSemaphore::PosixSemaphore() { semaphore = new sem_t; if (sem_init(semaphore, 0, 0) == -1) { LOG_fatal << "Error creating semaphore: " << errno; } } void PosixSemaphore::wait() { while (sem_wait(&semaphore) == -1) { if (errno == EINTR) { continue; } LOG_fatal << "Error in sem_wait: " << errno; } } static inline void timespec_add_msec(struct timespec *tv, int milliseconds) { int seconds = milliseconds / 1000; int milliseconds_left = milliseconds % 1000; tv->tv_sec += seconds; tv->tv_nsec += milliseconds_left * 1000000; if (tv->tv_nsec >= 1000000000) { tv->tv_nsec -= 1000000000; tv->tv_sec++; } } int PosixSemaphore::timedwait(int milliseconds) { int ret; struct timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts) == -1) { LOG_err << "Error in clock_gettime"; return -2; } timespec_add_msec (&ts, milliseconds); while (true) { ret = sem_timedwait(semaphore, &ts); if (!ret) { return 0; } if (errno == ETIMEDOUT) { return -1; } if (errno == EINTR) { continue; } LOG_err << "Error in sem_timedwait: " << errno; return -2; } } void PosixSemaphore::release() { if (sem_post(semaphore) == -1) { LOG_fatal << "Error in sem_post: " << errno; } } PosixSemaphore::~PosixSemaphore() { sem_destroy(semaphore); delete semaphore; } }// namespace #endif
Call pthread_mutex_destroy only if the mutex was initialized
Call pthread_mutex_destroy only if the mutex was initialized
C++
bsd-2-clause
meganz/sdk,meganz/sdk,Acidburn0zzz/sdk,meganz/sdk,Acidburn0zzz/sdk,Acidburn0zzz/sdk,Acidburn0zzz/sdk,Acidburn0zzz/sdk,meganz/sdk,meganz/sdk,Acidburn0zzz/sdk,Acidburn0zzz/sdk,meganz/sdk,meganz/sdk,Acidburn0zzz/sdk
01dffb89b9d7f9932fa46ab15edd9ec38c5a694c
src/menu/menu_animation.cpp
src/menu/menu_animation.cpp
#include "menu/menu_animation.h" #include <vector> #include "util/token.h" #include "util/bitmap.h" #include "globals.h" #include "util/funcs.h" MenuFrame::MenuFrame(Token *token, imageMap &images) throw (LoadException): bmp(0), time(0), horizontalFlip(false), verticalFlip(false), alpha(255){ offset.x = 0; offset.y = 0; window.x1 = 0; window.y1 = 0; window.x2 = 0; window.y2 = 0; if ( *token != "frame" ){ throw LoadException("Not an frame"); } Token tok(*token); /* The usual setup of an animation frame is // use image -1 to not draw anything, it can be used to get a blinking effect (frame (image NUM) (alpha NUM) (offset x y) (hflip 0|1) (vflip 0|1) (time NUM) (window x1 y1 x2 y2)) */ while ( tok.hasTokens() ){ try{ Token * token; tok >> token; if (*token == "image"){ // get the number int num; *token >> num; // now assign the bitmap bmp = images[num]; } else if (*token == "alpha"){ // get alpha *token >> alpha; } else if (*token == "offset"){ // Get the offset location it defaults to 0,0 *token >> offset.x >> offset.y; } else if (*token == "hflip"){ // horizontal flip *token >> horizontalFlip; } else if (*token == "vflip"){ // horizontal flip *token >> verticalFlip; } else if (*token == "time"){ // time to display *token >> time; } else if (*token == "window"){ // time to display *token >> window.x1 >> window.y1 >> window.x2 >> window.y2; } else { Global::debug( 3 ) << "Unhandled menu attribute: "<<endl; if (Global::getDebug() >= 3){ token->print(" "); } } } catch ( const TokenException & ex ) { string m( "Menu parse error: " ); m += ex.getReason(); throw LoadException( m ); } catch ( const LoadException & ex ) { throw ex; } } } MenuFrame::~MenuFrame(){ } void MenuFrame::draw(int xaxis, int yaxis, Bitmap *work){ if (!bmp)return; // Set clip from the axis default is 0,0,bitmap width, bitmap height work->setClipRect(window.x1,window.y1,work->getWidth() + window.x2,work->getHeight() + window.y2); Bitmap::transBlender( 0, 0, 0, alpha ); if (horizontalFlip && !verticalFlip){ bmp->drawTransHFlip(xaxis + offset.x, yaxis + offset.y, *work); } else if (!horizontalFlip && verticalFlip){ bmp->drawTransVFlip(xaxis + offset.x, yaxis + offset.y, *work); } else if (horizontalFlip && verticalFlip){ bmp->drawTransHVFlip(xaxis + offset.x, yaxis + offset.y, *work); } else if (!horizontalFlip && !verticalFlip){ bmp->drawTrans(xaxis + offset.x, yaxis + offset.y, *work); } work->setClipRect(0,0,work->getWidth(),work->getHeight()); } MenuAnimation::MenuAnimation(Token *token) throw (LoadException): id(0), location(0), ticks(0), currentFrame(0), loop(0), allowReset(true){ axis.x = 0; axis.y = 0; images[-1] = 0; if ( *token != "anim" ){ throw LoadException("Not an animation"); } /* The usual setup of an animation is The images must be listed prior to listing any frames loop will begin at the subsequent frame listed after loop axis is the location in which the drawing must be placed location - used to render in background or foreground (0 == background [default]| 1 == foreground) reset - used to allow resetting of animation (0 == no | 1 == yes [default]) (anim (id NUM) (location NUM) (image NUM FILE) (axis x y) (frame "Read comments above in constructor") (loop) (reset NUM)) */ Token tok(*token); while ( tok.hasTokens() ){ try{ Token * token; tok >> token; if (*token == "id"){ // get the id *token >> id; } else if (*token == "location"){ // get the location *token >> location; } else if (*token == "image"){ // add bitmaps by number to the map int number; std::string temp; *token >> number >> temp; Bitmap *bmp = new Bitmap(Util::getDataPath() + temp); if (bmp->getError()){ delete bmp; } else { images[number] = bmp; } } else if (*token == "axis"){ // Get the axis location it defaults to 0,0 *token >> axis.x >> axis.y; } else if (*token == "frame"){ // new frame MenuFrame *frame = new MenuFrame(token,images); frames.push_back(frame); } else if (*token == "loop"){ // start loop here loop = frames.size(); } else if (*token == "reset"){ // start loop here *token >> allowReset; } else { Global::debug( 3 ) << "Unhandled menu attribute: "<<endl; if (Global::getDebug() >= 3){ token->print(" "); } } } catch ( const TokenException & ex ) { string m( "Menu parse error: " ); m += ex.getReason(); throw LoadException( m ); } catch ( const LoadException & ex ) { throw ex; } } if (loop >= frames.size()){ throw LoadException( "Problem with the loop location, it is beyond the last frame.." ); } } MenuAnimation::~MenuAnimation(){ for (std::vector<MenuFrame *>::iterator i = frames.begin(); i != frames.end(); ++i){ if (*i){ delete *i; } } for (imageMap::iterator i = images.begin(); i != images.end(); ++i){ if (i->second){ delete i->second; } } } void MenuAnimation::act(){ if( frames[currentFrame]->time != -1 ){ ticks++; if(ticks >= frames[currentFrame]->time){ ticks = 0; forwardFrame(); } } } void MenuAnimation::draw(Bitmap *work){ frames[currentFrame]->draw(axis.x,axis.y,work); } void MenuAnimation::forwardFrame(){ if (currentFrame < frames.size() -1){ currentFrame++; } else { currentFrame = loop; } } void MenuAnimation::backFrame(){ if (currentFrame > loop){ currentFrame--; } else { currentFrame = frames.size() - 1; } }
#include "menu/menu_animation.h" #include <vector> #include "util/token.h" #include "util/bitmap.h" #include "globals.h" #include "util/funcs.h" MenuFrame::MenuFrame(Token *token, imageMap &images) throw (LoadException): bmp(0), time(0), horizontalFlip(false), verticalFlip(false), alpha(255){ offset.x = 0; offset.y = 0; window.x1 = 0; window.y1 = 0; window.x2 = 0; window.y2 = 0; if ( *token != "frame" ){ throw LoadException("Not an frame"); } Token tok(*token); /* The usual setup of an animation frame is // use image -1 to not draw anything, it can be used to get a blinking effect (frame (image NUM) (alpha NUM) (offset x y) (hflip 0|1) (vflip 0|1) (time NUM) (window x1 y1 x2 y2)) */ while ( tok.hasTokens() ){ try{ Token * token; tok >> token; if (*token == "image"){ // get the number int num; *token >> num; // now assign the bitmap bmp = images[num]; } else if (*token == "alpha"){ // get alpha *token >> alpha; } else if (*token == "offset"){ // Get the offset location it defaults to 0,0 *token >> offset.x >> offset.y; } else if (*token == "hflip"){ // horizontal flip *token >> horizontalFlip; } else if (*token == "vflip"){ // horizontal flip *token >> verticalFlip; } else if (*token == "time"){ // time to display *token >> time; } else if (*token == "window"){ // time to display *token >> window.x1 >> window.y1 >> window.x2 >> window.y2; } else { Global::debug( 3 ) << "Unhandled menu attribute: "<<endl; if (Global::getDebug() >= 3){ token->print(" "); } } } catch ( const TokenException & ex ) { string m( "Menu parse error: " ); m += ex.getReason(); throw LoadException( m ); } catch ( const LoadException & ex ) { throw ex; } } } MenuFrame::~MenuFrame(){ } void MenuFrame::draw(int xaxis, int yaxis, Bitmap *work){ if (!bmp)return; // Set clip from the axis default is 0,0,bitmap width, bitmap height work->setClipRect(window.x1,window.y1,work->getWidth() + window.x2,work->getHeight() + window.y2); if (alpha != 255){ Bitmap::transBlender( 0, 0, 0, alpha ); } if (horizontalFlip && !verticalFlip){ bmp->drawTransHFlip(xaxis + offset.x, yaxis + offset.y, *work); } else if (!horizontalFlip && verticalFlip){ bmp->drawTransVFlip(xaxis + offset.x, yaxis + offset.y, *work); } else if (horizontalFlip && verticalFlip){ bmp->drawTransHVFlip(xaxis + offset.x, yaxis + offset.y, *work); } else if (!horizontalFlip && !verticalFlip){ bmp->drawTrans(xaxis + offset.x, yaxis + offset.y, *work); } work->setClipRect(0,0,work->getWidth(),work->getHeight()); } MenuAnimation::MenuAnimation(Token *token) throw (LoadException): id(0), location(0), ticks(0), currentFrame(0), loop(0), allowReset(true){ axis.x = 0; axis.y = 0; images[-1] = 0; if ( *token != "anim" ){ throw LoadException("Not an animation"); } /* The usual setup of an animation is The images must be listed prior to listing any frames loop will begin at the subsequent frame listed after loop axis is the location in which the drawing must be placed location - used to render in background or foreground (0 == background [default]| 1 == foreground) reset - used to allow resetting of animation (0 == no | 1 == yes [default]) (anim (id NUM) (location NUM) (image NUM FILE) (axis x y) (frame "Read comments above in constructor") (loop) (reset NUM)) */ Token tok(*token); while ( tok.hasTokens() ){ try{ Token * token; tok >> token; if (*token == "id"){ // get the id *token >> id; } else if (*token == "location"){ // get the location *token >> location; } else if (*token == "image"){ // add bitmaps by number to the map int number; std::string temp; *token >> number >> temp; Bitmap *bmp = new Bitmap(Util::getDataPath() + temp); if (bmp->getError()){ delete bmp; } else { images[number] = bmp; } } else if (*token == "axis"){ // Get the axis location it defaults to 0,0 *token >> axis.x >> axis.y; } else if (*token == "frame"){ // new frame MenuFrame *frame = new MenuFrame(token,images); frames.push_back(frame); } else if (*token == "loop"){ // start loop here loop = frames.size(); } else if (*token == "reset"){ // start loop here *token >> allowReset; } else { Global::debug( 3 ) << "Unhandled menu attribute: "<<endl; if (Global::getDebug() >= 3){ token->print(" "); } } } catch ( const TokenException & ex ) { string m( "Menu parse error: " ); m += ex.getReason(); throw LoadException( m ); } catch ( const LoadException & ex ) { throw ex; } } if (loop >= frames.size()){ throw LoadException( "Problem with the loop location, it is beyond the last frame.." ); } } MenuAnimation::~MenuAnimation(){ for (std::vector<MenuFrame *>::iterator i = frames.begin(); i != frames.end(); ++i){ if (*i){ delete *i; } } for (imageMap::iterator i = images.begin(); i != images.end(); ++i){ if (i->second){ delete i->second; } } } void MenuAnimation::act(){ if( frames[currentFrame]->time != -1 ){ ticks++; if(ticks >= frames[currentFrame]->time){ ticks = 0; forwardFrame(); } } } void MenuAnimation::draw(Bitmap *work){ frames[currentFrame]->draw(axis.x,axis.y,work); } void MenuAnimation::forwardFrame(){ if (currentFrame < frames.size() -1){ currentFrame++; } else { currentFrame = loop; } } void MenuAnimation::backFrame(){ if (currentFrame > loop){ currentFrame--; } else { currentFrame = frames.size() - 1; } }
Check alpha if applicable set trans
Check alpha if applicable set trans
C++
bsd-3-clause
scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown
cb1fa0faafd6e534dde4ce9c912716608fe18ff7
db/yas_db_utils.cpp
db/yas_db_utils.cpp
// // yas_db_utils.cpp // #include "yas_db_attribute.h" #include "yas_db_database.h" #include "yas_db_manager.h" #include "yas_db_row_set.h" #include "yas_db_select_option.h" #include "yas_db_sql_utils.h" #include "yas_db_utils.h" #include "yas_unless.h" using namespace yas; db::update_result db::create_table(db::database &db, std::string const &table_name, std::vector<std::string> const &fields) { return db.execute_update(create_table_sql(table_name, fields)); } db::update_result db::alter_table(db::database &db, std::string const &table_name, std::string const &field) { return db.execute_update(alter_table_sql(table_name, field)); } db::update_result db::drop_table(db::database &db, std::string const &table_name) { return db.execute_update(drop_table_sql(table_name)); } db::update_result db::begin_transaction(db::database &db) { return db.execute_update("begin exclusive transaction"); } db::update_result db::begin_deferred_transaction(db::database &db) { return db.execute_update("begin deferred transaction"); } db::update_result db::commit(db::database &db) { return db.execute_update("commit transaction"); } db::update_result db::rollback(db::database &db) { return db.execute_update("rollback transaction"); } #if SQLITE_VERSION_NUMBER >= 3007000 namespace yas { namespace db { static std::string escape_save_point_name(std::string const &name) { return replaced(name, "'", "''"); } } } db::update_result db::start_save_point(db::database &db, std::string const &name) { if (name.size() == 0) { return update_result{error{error_type::invalid_argument}}; } return db.execute_update("savepoint '" + escape_save_point_name(name) + "';"); } db::update_result db::release_save_point(db::database &db, std::string const &name) { if (name.size() == 0) { return update_result{error{error_type::invalid_argument}}; } return db.execute_update("release savepoint '" + escape_save_point_name(name) + "';"); } db::update_result db::rollback_save_point(db::database &db, std::string const &name) { if (name.size() == 0) { return update_result{error{error_type::invalid_argument}}; } return db.execute_update("rollback transaction to savepoint '" + escape_save_point_name(name) + "';"); } db::update_result db::in_save_point(db::database &db, std::function<void(bool &rollback)> const function) { static unsigned long save_point_idx = 0; std::string const name = "db_save_point_" + std::to_string(save_point_idx++); if (auto ul = unless(start_save_point(db, name))) { return std::move(ul.value); } bool should_rollback = false; function(should_rollback); if (should_rollback) { rollback_save_point(db, name); } return release_save_point(db, name); } #endif bool db::table_exists(database const &db, std::string const &table_name) { if (auto row_set = get_table_schema(db, table_name)) { if (row_set.next()) { return true; } } return false; } db::row_set db::get_schema(database const &db) { if (auto query_result = db.execute_query( "select type, name, tbl_name, rootpage, sql from (select * from sqlite_master union all select * from " "sqlite_temp_master) where type != 'meta' and name not like 'sqlite_%' order by tbl_name, type desc, " "name")) { return query_result.value(); } return nullptr; } db::row_set db::get_table_schema(database const &db, std::string const &table_name) { if (auto query_result = db.execute_query("pragma table_info('" + table_name + "')")) { return query_result.value(); } return nullptr; } bool db::column_exists(database const &db, std::string column_name, std::string table_name) { std::string lower_table_name = to_lower(std::move(table_name)); std::string lower_column_name = to_lower(std::move(column_name)); if (auto row_set = get_table_schema(db, lower_table_name)) { while (row_set.next()) { auto value = row_set.column_value("name"); if (to_lower(value.get<db::text>()) == lower_column_name) { return true; } } } return false; } db::select_result db::select(db::database const &db, std::string const &table_name, select_option const &option) { auto const sql = select_sql(table_name, option.fields, option.where_exprs, option.field_orders, option.limit_range); db::value_map_vector value_map_vector; if (auto query_result = db.execute_query(sql, option.arguments)) { auto row_set = query_result.value(); while (row_set.next()) { value_map_vector.emplace_back(row_set.value_map()); } } else { return select_result{std::move(query_result.error())}; } return select_result{value_map_vector}; } db::select_result db::select_last(database const &db, std::string const &table_name, db::value const &save_id, select_option option) { std::vector<std::string> components; if (save_id) { components.emplace_back(expr(save_id_field, "<=", to_string(save_id))); } if (option.where_exprs.size() > 0) { components.emplace_back(option.where_exprs); } std::string sub_where = components.size() > 0 ? " where " + joined(components, " and ") : ""; option.where_exprs = "rowid in (select max(rowid) from " + table_name + sub_where + " group by " + db::object_id_field + ")"; return select(db, table_name, option); } db::select_result db::select_undo(database const &db, std::string const &table_name, integer::type const revert_save_id, integer::type const current_save_id) { if (current_save_id <= revert_save_id) { throw "revert_save_id greater than or equal to current_save_id"; } std::vector<std::string> components; components.emplace_back(object_id_field + " in (select distinct " + object_id_field + " from " + table_name + " where " + joined({expr(save_id_field, "<=", std::to_string(current_save_id)), expr(save_id_field, ">", std::to_string(revert_save_id))}, " and ") + ")"); components.emplace_back(expr(save_id_field, "<=", std::to_string(revert_save_id))); select_option option{.where_exprs = "rowid in (select max(rowid) from " + table_name + " where " + joined(components, " and ") + " group by " + object_id_field + ")", .field_orders = {{object_id_field, order::ascending}}}; auto result = select(db, table_name, option); if (!result) { return select_result{std::move(result.error())}; } select_option empty_option{.fields = {object_id_field}, .where_exprs = joined({expr(save_id_field, "<=", std::to_string(current_save_id)), expr(save_id_field, ">", std::to_string(revert_save_id)), equal_field_expr(action_field)}, " and "), .arguments = {{action_field, db::value{insert_action}}}, .field_orders = {{object_id_field, order::ascending}}}; auto empty_result = select(db, table_name, empty_option); if (!empty_result) { return select_result{std::move(empty_result.error())}; } return select_result{connect(std::move(result.value()), std::move(empty_result.value()))}; } db::select_result db::select_redo(database const &db, std::string const &table_name, integer::type const revert_save_id, integer::type const current_save_id) { if (revert_save_id <= current_save_id) { throw "current_save_id greater than or equal to revert_save_id"; } std::vector<std::string> components; components.emplace_back(expr(save_id_field, ">", std::to_string(current_save_id))); db::select_option option{.where_exprs = joined(components, " and "), .field_orders = {{object_id_field, db::order::ascending}}}; return select_last(db, table_name, db::value{revert_save_id}, std::move(option)); } db::select_result db::select_revert(database const &db, std::string const &table_name, integer::type const revert_save_id, integer::type const current_save_id) { if (revert_save_id < current_save_id) { return select_undo(db, table_name, revert_save_id, current_save_id); } else if (current_save_id < revert_save_id) { return select_redo(db, table_name, revert_save_id, current_save_id); } return select_result{value_map_vector{}}; } db::select_single_result db::select_db_info(database const &db) { if (auto const &select_result = select(db, db::info_table)) { if (select_result.value().size() > 0) { return select_single_result{std::move(select_result.value().at(0))}; } } return select_single_result{nullptr}; } db::value db::max(database const &db, std::string const &table_name, std::string const &field) { if (auto query_result = db.execute_query("select max(" + field + ") from " + table_name + ";")) { auto &row_set = query_result.value(); if (row_set.next()) { return row_set.column_value(0); } } return nullptr; }
// // yas_db_utils.cpp // #include "yas_db_attribute.h" #include "yas_db_database.h" #include "yas_db_manager.h" #include "yas_db_row_set.h" #include "yas_db_select_option.h" #include "yas_db_sql_utils.h" #include "yas_db_utils.h" #include "yas_unless.h" using namespace yas; db::update_result db::create_table(db::database &db, std::string const &table_name, std::vector<std::string> const &fields) { return db.execute_update(create_table_sql(table_name, fields)); } db::update_result db::alter_table(db::database &db, std::string const &table_name, std::string const &field) { return db.execute_update(alter_table_sql(table_name, field)); } db::update_result db::drop_table(db::database &db, std::string const &table_name) { return db.execute_update(drop_table_sql(table_name)); } db::update_result db::begin_transaction(db::database &db) { return db.execute_update("begin exclusive transaction"); } db::update_result db::begin_deferred_transaction(db::database &db) { return db.execute_update("begin deferred transaction"); } db::update_result db::commit(db::database &db) { return db.execute_update("commit transaction"); } db::update_result db::rollback(db::database &db) { return db.execute_update("rollback transaction"); } #if SQLITE_VERSION_NUMBER >= 3007000 namespace yas { namespace db { static std::string escape_save_point_name(std::string const &name) { return replaced(name, "'", "''"); } } } db::update_result db::start_save_point(db::database &db, std::string const &name) { if (name.size() == 0) { return update_result{error{error_type::invalid_argument}}; } return db.execute_update("savepoint '" + escape_save_point_name(name) + "';"); } db::update_result db::release_save_point(db::database &db, std::string const &name) { if (name.size() == 0) { return update_result{error{error_type::invalid_argument}}; } return db.execute_update("release savepoint '" + escape_save_point_name(name) + "';"); } db::update_result db::rollback_save_point(db::database &db, std::string const &name) { if (name.size() == 0) { return update_result{error{error_type::invalid_argument}}; } return db.execute_update("rollback transaction to savepoint '" + escape_save_point_name(name) + "';"); } db::update_result db::in_save_point(db::database &db, std::function<void(bool &rollback)> const function) { static unsigned long save_point_idx = 0; std::string const name = "db_save_point_" + std::to_string(save_point_idx++); if (auto ul = unless(start_save_point(db, name))) { return std::move(ul.value); } bool should_rollback = false; function(should_rollback); if (should_rollback) { rollback_save_point(db, name); } return release_save_point(db, name); } #endif bool db::table_exists(database const &db, std::string const &table_name) { if (auto row_set = get_table_schema(db, table_name)) { if (row_set.next()) { return true; } } return false; } db::row_set db::get_schema(database const &db) { if (auto query_result = db.execute_query( "select type, name, tbl_name, rootpage, sql from (select * from sqlite_master union all select * from " "sqlite_temp_master) where type != 'meta' and name not like 'sqlite_%' order by tbl_name, type desc, " "name")) { return query_result.value(); } return nullptr; } db::row_set db::get_table_schema(database const &db, std::string const &table_name) { if (auto query_result = db.execute_query("pragma table_info('" + table_name + "')")) { return query_result.value(); } return nullptr; } bool db::column_exists(database const &db, std::string column_name, std::string table_name) { std::string lower_table_name = to_lower(std::move(table_name)); std::string lower_column_name = to_lower(std::move(column_name)); if (auto row_set = get_table_schema(db, lower_table_name)) { while (row_set.next()) { auto value = row_set.column_value("name"); if (to_lower(value.get<db::text>()) == lower_column_name) { return true; } } } return false; } db::select_result db::select(db::database const &db, std::string const &table_name, select_option const &option) { auto const sql = select_sql(table_name, option.fields, option.where_exprs, option.field_orders, option.limit_range); db::value_map_vector value_map_vector; if (auto query_result = db.execute_query(sql, option.arguments)) { auto row_set = query_result.value(); while (row_set.next()) { value_map_vector.emplace_back(row_set.value_map()); } } else { return select_result{std::move(query_result.error())}; } return select_result{value_map_vector}; } db::select_result db::select_last(database const &db, std::string const &table_name, db::value const &save_id, select_option option) { std::vector<std::string> components; if (save_id) { components.emplace_back(expr(save_id_field, "<=", to_string(save_id))); } if (option.where_exprs.size() > 0) { components.emplace_back(option.where_exprs); } std::string sub_where = components.size() > 0 ? " where " + joined(components, " and ") : ""; option.where_exprs = "rowid in (select max(rowid) from " + table_name + sub_where + " group by " + db::object_id_field + ")"; return select(db, table_name, option); } db::select_result db::select_undo(database const &db, std::string const &table_name, integer::type const revert_save_id, integer::type const current_save_id) { if (current_save_id <= revert_save_id) { throw "revert_save_id greater than or equal to current_save_id"; } std::vector<std::string> components; components.emplace_back(object_id_field + " in (select distinct " + object_id_field + " from " + table_name + " where " + joined({expr(save_id_field, "<=", std::to_string(current_save_id)), expr(save_id_field, ">", std::to_string(revert_save_id))}, " and ") + ")"); components.emplace_back(expr(save_id_field, "<=", std::to_string(revert_save_id))); select_option option{.where_exprs = "rowid in (select max(rowid) from " + table_name + " where " + joined(components, " and ") + " group by " + object_id_field + ")", .field_orders = {{object_id_field, order::ascending}}}; auto result = select(db, table_name, option); if (!result) { return select_result{std::move(result.error())}; } select_option empty_option{.fields = {object_id_field}, .where_exprs = joined({expr(save_id_field, "<=", std::to_string(current_save_id)), expr(save_id_field, ">", std::to_string(revert_save_id)), equal_field_expr(action_field)}, " and "), .arguments = {{action_field, db::value{insert_action}}}, .field_orders = {{object_id_field, order::ascending}}}; auto empty_result = select(db, table_name, empty_option); if (!empty_result) { return select_result{std::move(empty_result.error())}; } return select_result{connect(std::move(result.value()), std::move(empty_result.value()))}; } db::select_result db::select_redo(database const &db, std::string const &table_name, integer::type const revert_save_id, integer::type const current_save_id) { if (revert_save_id <= current_save_id) { throw "current_save_id greater than or equal to revert_save_id"; } std::vector<std::string> components; components.emplace_back(expr(save_id_field, ">", std::to_string(current_save_id))); db::select_option option{.where_exprs = joined(components, " and "), .field_orders = {{object_id_field, db::order::ascending}}}; return select_last(db, table_name, db::value{revert_save_id}, std::move(option)); } db::select_result db::select_revert(database const &db, std::string const &table_name, integer::type const revert_save_id, integer::type const current_save_id) { if (revert_save_id < current_save_id) { return select_undo(db, table_name, revert_save_id, current_save_id); } else if (current_save_id < revert_save_id) { return select_redo(db, table_name, revert_save_id, current_save_id); } return select_result{value_map_vector{}}; } db::select_single_result db::select_db_info(database const &db) { select_option option{.limit_range = {.location = 0, .length = 1}}; if (auto const &select_result = select(db, db::info_table, option)) { if (select_result.value().size() > 0) { return select_single_result{std::move(select_result.value().at(0))}; } } return select_single_result{nullptr}; } db::value db::max(database const &db, std::string const &table_name, std::string const &field) { if (auto query_result = db.execute_query("select max(" + field + ") from " + table_name + ";")) { auto &row_set = query_result.value(); if (row_set.next()) { return row_set.column_value(0); } } return nullptr; }
update db_utils
update db_utils
C++
mit
objective-audio/db,objective-audio/db,objective-audio/db
5bb467684cec8f230f5582cea2ea45dcc77153d7
cpp/full_text_cache_expirer.cc
cpp/full_text_cache_expirer.cc
/** \brief Utility for expunging old records from our full-text database. * \author Dr. Johannes Ruscheinski ([email protected]) * * \copyright 2017 Universitätsbiblothek Tübingen. All rights reserved. * * 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/>. */ #include <iostream> #include <cstdlib> #include "DbConnection.h" #include "SqlUtil.h" #include "StringUtil.h" #include "util.h" #include "VuFind.h" static void Usage() __attribute__((noreturn)); static void Usage() { std::cerr << "Usage: " << ::progname << " no_of_months_db\n" << " Removes all records from the full-text database whose last_used dates are older than\n" << " \"no_of_months_db\" months.\n\n"; std::exit(EXIT_FAILURE); } void ExpungeOldRecords(const unsigned no_of_months) { std::string mysql_url; VuFind::GetMysqlURL(&mysql_url); DbConnection db_connection(mysql_url); const time_t now(std::time(nullptr)); const std::string cutoff_datetime(SqlUtil::TimeTToDatetime(now - no_of_months * 30 * 86400)); const std::string DELETE_STMT("DELETE FROM full_text_cache SET WHERE last_used < \"" + cutoff_datetime + "\""); if (not db_connection.query(DELETE_STMT)) throw std::runtime_error("Query \"" + DELETE_STMT + "\" failed because: " + db_connection.getLastErrorMessage()); } int main(int argc, char *argv[]) { ::progname = argv[0]; if (argc != 2) Usage(); unsigned no_of_months; if (not StringUtil::ToUnsigned(argv[1], &no_of_months)) Error("no_of_months must be a number!"); try { ExpungeOldRecords(no_of_months); } catch (const std::exception &e) { Error("caught exception: " + std::string(e.what())); } }
/** \brief Utility for expunging old records from our full-text database. * \author Dr. Johannes Ruscheinski ([email protected]) * * \copyright 2017 Universitätsbiblothek Tübingen. All rights reserved. * * 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/>. */ #include <iostream> #include <cstdlib> #include "DbConnection.h" #include "SqlUtil.h" #include "StringUtil.h" #include "util.h" #include "VuFind.h" static void Usage() __attribute__((noreturn)); static void Usage() { std::cerr << "Usage: " << ::progname << " no_of_months_db\n" << " Removes all records from the full-text database whose last_used dates are older than\n" << " \"no_of_months_db\" months.\n\n"; std::exit(EXIT_FAILURE); } void ExpungeOldRecords(const unsigned no_of_months) { std::string mysql_url; VuFind::GetMysqlURL(&mysql_url); DbConnection db_connection(mysql_url); const time_t now(std::time(nullptr)); const std::string cutoff_datetime(SqlUtil::TimeTToDatetime(now - no_of_months * 30 * 86400)); const std::string DELETE_STMT("DELETE FROM full_text_cache WHERE last_used < \"" + cutoff_datetime + "\""); if (not db_connection.query(DELETE_STMT)) throw std::runtime_error("Query \"" + DELETE_STMT + "\" failed because: " + db_connection.getLastErrorMessage()); } int main(int argc, char *argv[]) { ::progname = argv[0]; if (argc != 2) Usage(); unsigned no_of_months; if (not StringUtil::ToUnsigned(argv[1], &no_of_months)) Error("no_of_months must be a number!"); try { ExpungeOldRecords(no_of_months); } catch (const std::exception &e) { Error("caught exception: " + std::string(e.what())); } }
Update full_text_cache_expirer.cc
Update full_text_cache_expirer.cc
C++
agpl-3.0
ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools
88de8e419c4154457f0bf13aa67923b437462a72
nuitka/build/include/nuitka/threading.hpp
nuitka/build/include/nuitka/threading.hpp
// Copyright 2013, Kay Hayen, mailto:[email protected] // // Part of "Nuitka", an optimizing Python compiler that is compatible and // integrates with CPython, but also works on its own. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef __NUITKA_THREADING_H__ #define __NUITKA_THREADING_H__ #if PYTHON_VERSION < 300 // We share this with CPython bytecode main loop. PyAPI_DATA(volatile int) _Py_Ticker; #else extern volatile int _Py_Ticker; #define _Py_CheckInterval 20 #endif NUITKA_MAY_BE_UNUSED static void CONSIDER_THREADING( void ) { // Decrease ticker if ( --_Py_Ticker < 0 ) { _Py_Ticker = _Py_CheckInterval; int res = Py_MakePendingCalls(); if (unlikely( res < 0 )) { throw PythonException(); } PyThreadState *tstate = PyThreadState_GET(); assert( tstate ); #ifdef _NUITKA_EXPERIMENTAL if ( PyEval_ThreadsInitialized() ) { // Release and acquire the GIL, it's very inefficient, because we // don't even know if it makes sense to do it. A controlling thread // should be used to determine if it's needed at all. PyEval_SaveThread(); PyEval_AcquireThread( tstate ); } #endif if (unlikely( tstate->async_exc != NULL )) { PyObjectTemporary tmp_async_exc( tstate->async_exc ); tstate->async_exc = NULL; throw PythonException( tmp_async_exc.asObject() ); } } } #endif
// Copyright 2013, Kay Hayen, mailto:[email protected] // // Part of "Nuitka", an optimizing Python compiler that is compatible and // integrates with CPython, but also works on its own. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef __NUITKA_THREADING_H__ #define __NUITKA_THREADING_H__ #if PYTHON_VERSION < 300 // We share this with CPython bytecode main loop. PyAPI_DATA(volatile int) _Py_Ticker; #else extern volatile int _Py_Ticker; #define _Py_CheckInterval 20 #endif NUITKA_MAY_BE_UNUSED static void CONSIDER_THREADING( void ) { // Decrease ticker if ( --_Py_Ticker < 0 ) { _Py_Ticker = _Py_CheckInterval; int res = Py_MakePendingCalls(); if (unlikely( res < 0 )) { throw PythonException(); } PyThreadState *tstate = PyThreadState_GET(); assert( tstate ); if ( PyEval_ThreadsInitialized() ) { // Release and acquire the GIL, it's very inefficient, because we // don't even know if it makes sense to do it. A controlling thread // should be used to determine if it's needed at all. PyEval_SaveThread(); PyEval_AcquireThread( tstate ); } if (unlikely( tstate->async_exc != NULL )) { PyObjectTemporary tmp_async_exc( tstate->async_exc ); tstate->async_exc = NULL; throw PythonException( tmp_async_exc.asObject() ); } } } #endif
Enable threading support by default.
Enable threading support by default.
C++
apache-2.0
kayhayen/Nuitka,kayhayen/Nuitka,tempbottle/Nuitka,wfxiang08/Nuitka,wfxiang08/Nuitka,tempbottle/Nuitka,tempbottle/Nuitka,kayhayen/Nuitka,wfxiang08/Nuitka,kayhayen/Nuitka,wfxiang08/Nuitka,tempbottle/Nuitka
47a2032bd01304cd8c5cfd96f2600d4bf9ff1201
opencog/atoms/execution/EvaluationLink.cc
opencog/atoms/execution/EvaluationLink.cc
/* * opencog/atoms/execution/EvaluationLink.cc * * Copyright (C) 2009, 2013, 2014, 2015 Linas Vepstas * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/atomspace/atom_types.h> #include <opencog/atomspace/AtomSpace.h> #include <opencog/atomspace/SimpleTruthValue.h> #include <opencog/atoms/NumberNode.h> #include <opencog/atoms/core/DefineLink.h> #include <opencog/atoms/execution/Instantiator.h> #include <opencog/atoms/reduct/FoldLink.h> #include <opencog/cython/PythonEval.h> #include <opencog/guile/SchemeEval.h> #include <opencog/query/BindLinkAPI.h> #include "EvaluationLink.h" using namespace opencog; EvaluationLink::EvaluationLink(const HandleSeq& oset, TruthValuePtr tv, AttentionValuePtr av) : FreeLink(EVALUATION_LINK, oset, tv, av) { if ((2 != oset.size()) or (LIST_LINK != oset[1]->getType())) { throw RuntimeException(TRACE_INFO, "EvaluationLink must have predicate and args!"); } } EvaluationLink::EvaluationLink(const Handle& schema, const Handle& args, TruthValuePtr tv, AttentionValuePtr av) : FreeLink(EVALUATION_LINK, schema, args, tv, av) { if (LIST_LINK != args->getType()) { throw RuntimeException(TRACE_INFO, "EvaluationLink must have args in a ListLink!"); } } EvaluationLink::EvaluationLink(Link& l) : FreeLink(l) { Type tscope = l.getType(); if (EVALUATION_LINK != tscope) { throw RuntimeException(TRACE_INFO, "Expecting an EvaluationLink"); } } static Handle fold_execute(AtomSpace* as, const Handle& h) { FoldLinkPtr flp(FoldLinkCast(FoldLink::factory(LinkCast(h)))); if (NULL == flp) throw RuntimeException(TRACE_INFO, "Not executable!"); return flp->execute(as); } // Perform a GreaterThan check static TruthValuePtr greater(AtomSpace* as, const LinkPtr& ll) { if (2 != ll->getArity()) throw RuntimeException(TRACE_INFO, "GreaterThankLink expects two arguments"); Handle h1(ll->getOutgoingAtom(0)); Handle h2(ll->getOutgoingAtom(1)); // If they are not numbers, then we expect them to be something that // can be executed, yeilding a number. if (NUMBER_NODE != h1->getType()) h1 = fold_execute(as, h1); if (NUMBER_NODE != h2->getType()) h2 = fold_execute(as, h2); NumberNodePtr n1(NumberNodeCast(h1)); NumberNodePtr n2(NumberNodeCast(h2)); if (NULL == n1 or NULL == n2) throw RuntimeException(TRACE_INFO, "Expecting c++:greater arguments to be NumberNode's! Got:\n%s\n", (h1==NULL)? "(invalid handle)" : h1->toShortString().c_str(), (h2==NULL)? "(invalid handle)" : h2->toShortString().c_str()); if (n1->get_value() > n2->get_value()) return TruthValue::TRUE_TV(); else return TruthValue::FALSE_TV(); } static TruthValuePtr equal(AtomSpace* as, const LinkPtr& ll) { const HandleSeq& oset = ll->getOutgoingSet(); if (2 != oset.size()) throw RuntimeException(TRACE_INFO, "EqualLink expects two arguments"); Instantiator inst(as); Handle h0(inst.execute(oset[0])); Handle h1(inst.execute(oset[1])); if (h0 == h1) return TruthValue::TRUE_TV(); else return TruthValue::FALSE_TV(); } /// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink /// /// Expects the argument to be an EvaluationLink, which should have the /// following structure: /// /// EvaluationLink /// GroundedPredicateNode "lang: func_name" /// ListLink /// SomeAtom /// OtherAtom /// /// The "lang:" should be either "scm:" for scheme, or "py:" for python. /// This method will then invoke "func_name" on the provided ListLink /// of arguments to the function. /// /// This function takes TWO atomspace arguments! The first is the /// "main" atomspace, the second is a "scratch" or "temporary" /// atomspace. The scratch space is used to instantiate any arguments /// that need to be passed to evaluatable links (i.e. to predicates); /// the idea is that such temproraries don't add garbage to the main /// atomspace. The first argument, though, the "main" space, is used /// to instantiate any executable atoms: specifically, any PutLinks /// that were wrapped up by TrueLink, FalseLink. This is needed to get /// SequentialAndLink to work correctly, when moving down the sequence. /// TruthValuePtr EvaluationLink::do_eval_scratch(AtomSpace* as, const Handle& evelnk, AtomSpace* scratch) { Type t = evelnk->getType(); if (EVALUATION_LINK == t) { const LinkPtr l(LinkCast(evelnk)); const HandleSeq& sna(l->getOutgoingSet()); // The arguments may need to be executed... Instantiator inst(scratch); Handle args(inst.execute(sna.at(1))); return do_evaluate(scratch, sna.at(0), args); } else if (EQUAL_LINK == t) { return equal(scratch, LinkCast(evelnk)); } else if (GREATER_THAN_LINK == t) { return greater(scratch, LinkCast(evelnk)); } else if (NOT_LINK == t) { LinkPtr l(LinkCast(evelnk)); TruthValuePtr tv(do_eval_scratch(as, l->getOutgoingAtom(0), scratch)); return SimpleTruthValue::createTV( 1.0 - tv->getMean(), tv->getCount()); } else if (TRUE_LINK == t or FALSE_LINK == t) { // Assume that the link is wrapping something executable, // which we execute, but then ignore the result. const LinkPtr ll(LinkCast(evelnk)); Instantiator inst(as); Handle result(inst.execute(ll->getOutgoingAtom(0))); as->add_atom(result); if (TRUE_LINK == t) return TruthValue::TRUE_TV(); return TruthValue::FALSE_TV(); } else if (SATISFACTION_LINK == t) { return satisfaction_link(as, evelnk); } else if (DEFINED_PREDICATE_NODE == t) { return do_eval_scratch(as, DefineLink::get_definition(evelnk), scratch); } // We do not want to waste CPU time printing an exception message; // this is supposed to be handled automatically. Hmmm... unless // its a user Syntax error .... throw NotEvaluatableException(); // throw SyntaxException(TRACE_INFO, // "Expecting to get an EvaluationLink, got %s", // evelnk->toString().c_str()); } TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, const Handle& evelnk) { return do_eval_scratch(as, evelnk, as); } /// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink /// /// Expects the sequence to be exactly two atoms long. /// Expects the first handle of the sequence to be a GroundedPredicateNode /// Expects the second handle of the sequence to be a ListLink /// Executes the GroundedPredicateNode, supplying the second handle as argument /// TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, const HandleSeq& sna) { if (2 != sna.size()) { throw RuntimeException(TRACE_INFO, "Incorrect arity for an EvaluationLink!"); } return do_evaluate(as, sna[0], sna[1]); } /// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink /// /// Expects "gsn" to be a GroundedPredicateNode /// Expects "args" to be a ListLink /// Executes the GroundedPredicateNode, supplying the args as argument /// TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, const Handle& gsn, const Handle& args) { if (GROUNDED_PREDICATE_NODE != gsn->getType()) { throw RuntimeException(TRACE_INFO, "Expecting GroundedPredicateNode!"); } if (LIST_LINK != args->getType()) { throw RuntimeException(TRACE_INFO, "Expecting arguments to EvaluationLink!"); } // Get the schema name. const std::string& schema = NodeCast(gsn)->getName(); // printf ("Grounded schema name: %s\n", schema.c_str()); // A very special-case C++ comparison. // This compares two NumberNodes, by their numeric value. // Hard-coded in C++ for speed. (well, and for convenience ...) if (0 == schema.compare("c++:greater")) { return greater(as, LinkCast(args)); } // A very special-case C++ comparison. // This compares a set of atoms, verifying that they are all different. // Hard-coded in C++ for speed. (well, and for convenience ...) if (0 == schema.compare("c++:exclusive")) { LinkPtr ll(LinkCast(args)); Arity sz = ll->getArity(); for (Arity i=0; i<sz-1; i++) { Handle h1(ll->getOutgoingAtom(i)); for (Arity j=i+1; j<sz; j++) { Handle h2(ll->getOutgoingAtom(j)); if (h1 == h2) return TruthValue::FALSE_TV(); } } return TruthValue::TRUE_TV(); } // At this point, we only run scheme and python schemas. if (0 == schema.compare(0,4,"scm:", 4)) { #ifdef HAVE_GUILE // Be friendly, and strip leading white-space, if any. size_t pos = 4; while (' ' == schema[pos]) pos++; SchemeEval* applier = SchemeEval::get_evaluator(as); return applier->apply_tv(schema.substr(pos), args); #else throw RuntimeException(TRACE_INFO, "Cannot evaluate scheme GroundedPredicateNode!"); #endif /* HAVE_GUILE */ } if (0 == schema.compare(0, 3,"py:", 3)) { #ifdef HAVE_CYTHON // Be friendly, and strip leading white-space, if any. size_t pos = 3; while (' ' == schema[pos]) pos++; // Be sure to specify the atomspace in which to work! PythonEval &applier = PythonEval::instance(); return applier.apply_tv(as, schema.substr(pos), args); #else throw RuntimeException(TRACE_INFO, "Cannot evaluate python GroundedPredicateNode!"); #endif /* HAVE_CYTHON */ } // Unkown proceedure type. throw RuntimeException(TRACE_INFO, "Cannot evaluate unknown GroundedPredicateNode: %s", schema.c_str()); }
/* * opencog/atoms/execution/EvaluationLink.cc * * Copyright (C) 2009, 2013, 2014, 2015 Linas Vepstas * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/atomspace/atom_types.h> #include <opencog/atomspace/AtomSpace.h> #include <opencog/atomspace/SimpleTruthValue.h> #include <opencog/atoms/NumberNode.h> #include <opencog/atoms/core/DefineLink.h> #include <opencog/atoms/execution/Instantiator.h> #include <opencog/atoms/reduct/FoldLink.h> #include <opencog/cython/PythonEval.h> #include <opencog/guile/SchemeEval.h> #include <opencog/query/BindLinkAPI.h> #include "EvaluationLink.h" using namespace opencog; EvaluationLink::EvaluationLink(const HandleSeq& oset, TruthValuePtr tv, AttentionValuePtr av) : FreeLink(EVALUATION_LINK, oset, tv, av) { if ((2 != oset.size()) or (LIST_LINK != oset[1]->getType())) { throw RuntimeException(TRACE_INFO, "EvaluationLink must have predicate and args!"); } } EvaluationLink::EvaluationLink(const Handle& schema, const Handle& args, TruthValuePtr tv, AttentionValuePtr av) : FreeLink(EVALUATION_LINK, schema, args, tv, av) { if (LIST_LINK != args->getType()) { throw RuntimeException(TRACE_INFO, "EvaluationLink must have args in a ListLink!"); } } EvaluationLink::EvaluationLink(Link& l) : FreeLink(l) { Type tscope = l.getType(); if (EVALUATION_LINK != tscope) { throw RuntimeException(TRACE_INFO, "Expecting an EvaluationLink"); } } static Handle fold_execute(AtomSpace* as, const Handle& h) { FoldLinkPtr flp(FoldLinkCast(FoldLink::factory(LinkCast(h)))); if (NULL == flp) throw RuntimeException(TRACE_INFO, "Not executable!"); return flp->execute(as); } // Perform a GreaterThan check static TruthValuePtr greater(AtomSpace* as, const LinkPtr& ll) { if (2 != ll->getArity()) throw RuntimeException(TRACE_INFO, "GreaterThankLink expects two arguments"); Handle h1(ll->getOutgoingAtom(0)); Handle h2(ll->getOutgoingAtom(1)); // If they are not numbers, then we expect them to be something that // can be executed, yeilding a number. if (NUMBER_NODE != h1->getType()) h1 = fold_execute(as, h1); if (NUMBER_NODE != h2->getType()) h2 = fold_execute(as, h2); NumberNodePtr n1(NumberNodeCast(h1)); NumberNodePtr n2(NumberNodeCast(h2)); if (NULL == n1 or NULL == n2) throw RuntimeException(TRACE_INFO, "Expecting c++:greater arguments to be NumberNode's! Got:\n%s\n", (h1==NULL)? "(invalid handle)" : h1->toShortString().c_str(), (h2==NULL)? "(invalid handle)" : h2->toShortString().c_str()); if (n1->get_value() > n2->get_value()) return TruthValue::TRUE_TV(); else return TruthValue::FALSE_TV(); } static TruthValuePtr equal(AtomSpace* as, const LinkPtr& ll) { const HandleSeq& oset = ll->getOutgoingSet(); if (2 != oset.size()) throw RuntimeException(TRACE_INFO, "EqualLink expects two arguments"); Instantiator inst(as); Handle h0(inst.execute(oset[0])); Handle h1(inst.execute(oset[1])); if (h0 == h1) return TruthValue::TRUE_TV(); else return TruthValue::FALSE_TV(); } /// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink /// /// Expects the argument to be an EvaluationLink, which should have the /// following structure: /// /// EvaluationLink /// GroundedPredicateNode "lang: func_name" /// ListLink /// SomeAtom /// OtherAtom /// /// The "lang:" should be either "scm:" for scheme, or "py:" for python. /// This method will then invoke "func_name" on the provided ListLink /// of arguments to the function. /// /// This function takes TWO atomspace arguments! The first is the /// "main" atomspace, the second is a "scratch" or "temporary" /// atomspace. The scratch space is used to instantiate any arguments /// that need to be passed to evaluatable links (i.e. to predicates); /// the idea is that such temproraries don't add garbage to the main /// atomspace. The first argument, though, the "main" space, is used /// to instantiate any executable atoms: specifically, any PutLinks /// that were wrapped up by TrueLink, FalseLink. This is needed to get /// SequentialAndLink to work correctly, when moving down the sequence. /// TruthValuePtr EvaluationLink::do_eval_scratch(AtomSpace* as, const Handle& evelnk, AtomSpace* scratch) { Type t = evelnk->getType(); if (EVALUATION_LINK == t) { const LinkPtr l(LinkCast(evelnk)); const HandleSeq& sna(l->getOutgoingSet()); // The arguments may need to be executed... Instantiator inst(scratch); Handle args(inst.execute(sna.at(1))); return do_evaluate(scratch, sna.at(0), args); } else if (EQUAL_LINK == t) { return equal(scratch, LinkCast(evelnk)); } else if (GREATER_THAN_LINK == t) { return greater(scratch, LinkCast(evelnk)); } else if (NOT_LINK == t) { LinkPtr l(LinkCast(evelnk)); TruthValuePtr tv(do_eval_scratch(as, l->getOutgoingAtom(0), scratch)); return SimpleTruthValue::createTV( 1.0 - tv->getMean(), tv->getCount()); } else if (TRUE_LINK == t or FALSE_LINK == t) { // Assume that the link is wrapping something executable, // which we execute, but then ignore the result. const LinkPtr ll(LinkCast(evelnk)); Instantiator inst(as); Handle result(inst.execute(ll->getOutgoingAtom(0))); as->add_atom(result); if (TRUE_LINK == t) return TruthValue::TRUE_TV(); return TruthValue::FALSE_TV(); } else if (SATISFACTION_LINK == t) { return satisfaction_link(as, evelnk); } else if (DEFINED_PREDICATE_NODE == t) { return do_eval_scratch(as, DefineLink::get_definition(evelnk), scratch); } // We do not want to waste CPU time printing an exception message; // this is supposed to be handled automatically. Hmmm... unless // its a user Syntax error .... throw NotEvaluatableException(); // throw SyntaxException(TRACE_INFO, // "Expecting to get an EvaluationLink, got %s", // evelnk->toString().c_str()); } TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, const Handle& evelnk) { return do_eval_scratch(as, evelnk, as); } /// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink /// /// Expects the sequence to be exactly two atoms long. /// Expects the first handle of the sequence to be a GroundedPredicateNode /// Expects the second handle of the sequence to be a ListLink /// Executes the GroundedPredicateNode, supplying the second handle as argument /// TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, const HandleSeq& sna) { if (2 != sna.size()) { throw RuntimeException(TRACE_INFO, "Incorrect arity for an EvaluationLink!"); } return do_evaluate(as, sna[0], sna[1]); } /// do_evaluate -- evaluate the GroundedPredicateNode of the EvaluationLink /// /// Expects "gsn" to be a GroundedPredicateNode /// Expects "args" to be a ListLink /// Executes the GroundedPredicateNode, supplying the args as argument /// TruthValuePtr EvaluationLink::do_evaluate(AtomSpace* as, const Handle& gsn, const Handle& args) { if (GROUNDED_PREDICATE_NODE != gsn->getType()) { // Throw a silent exception; this is called in some try..catch blocks. throw NotEvaluatableException(); } if (LIST_LINK != args->getType()) { throw RuntimeException(TRACE_INFO, "Expecting arguments to EvaluationLink!"); } // Get the schema name. const std::string& schema = NodeCast(gsn)->getName(); // printf ("Grounded schema name: %s\n", schema.c_str()); // A very special-case C++ comparison. // This compares two NumberNodes, by their numeric value. // Hard-coded in C++ for speed. (well, and for convenience ...) if (0 == schema.compare("c++:greater")) { return greater(as, LinkCast(args)); } // A very special-case C++ comparison. // This compares a set of atoms, verifying that they are all different. // Hard-coded in C++ for speed. (well, and for convenience ...) if (0 == schema.compare("c++:exclusive")) { LinkPtr ll(LinkCast(args)); Arity sz = ll->getArity(); for (Arity i=0; i<sz-1; i++) { Handle h1(ll->getOutgoingAtom(i)); for (Arity j=i+1; j<sz; j++) { Handle h2(ll->getOutgoingAtom(j)); if (h1 == h2) return TruthValue::FALSE_TV(); } } return TruthValue::TRUE_TV(); } // At this point, we only run scheme and python schemas. if (0 == schema.compare(0,4,"scm:", 4)) { #ifdef HAVE_GUILE // Be friendly, and strip leading white-space, if any. size_t pos = 4; while (' ' == schema[pos]) pos++; SchemeEval* applier = SchemeEval::get_evaluator(as); return applier->apply_tv(schema.substr(pos), args); #else throw RuntimeException(TRACE_INFO, "Cannot evaluate scheme GroundedPredicateNode!"); #endif /* HAVE_GUILE */ } if (0 == schema.compare(0, 3,"py:", 3)) { #ifdef HAVE_CYTHON // Be friendly, and strip leading white-space, if any. size_t pos = 3; while (' ' == schema[pos]) pos++; // Be sure to specify the atomspace in which to work! PythonEval &applier = PythonEval::instance(); return applier.apply_tv(as, schema.substr(pos), args); #else throw RuntimeException(TRACE_INFO, "Cannot evaluate python GroundedPredicateNode!"); #endif /* HAVE_CYTHON */ } // Unkown proceedure type. throw RuntimeException(TRACE_INFO, "Cannot evaluate unknown GroundedPredicateNode: %s", schema.c_str()); }
Throw a silent exception
Throw a silent exception
C++
agpl-3.0
misgeatgit/atomspace,ceefour/atomspace,ceefour/atomspace,misgeatgit/atomspace,ceefour/atomspace,rodsol/atomspace,rTreutlein/atomspace,yantrabuddhi/atomspace,williampma/atomspace,rTreutlein/atomspace,yantrabuddhi/atomspace,yantrabuddhi/atomspace,yantrabuddhi/atomspace,ArvinPan/atomspace,ceefour/atomspace,ArvinPan/atomspace,misgeatgit/atomspace,cosmoharrigan/atomspace,williampma/atomspace,rTreutlein/atomspace,ArvinPan/atomspace,williampma/atomspace,misgeatgit/atomspace,misgeatgit/atomspace,AmeBel/atomspace,AmeBel/atomspace,inflector/atomspace,inflector/atomspace,ArvinPan/atomspace,AmeBel/atomspace,cosmoharrigan/atomspace,cosmoharrigan/atomspace,rodsol/atomspace,cosmoharrigan/atomspace,williampma/atomspace,inflector/atomspace,AmeBel/atomspace,inflector/atomspace,rodsol/atomspace,rodsol/atomspace,yantrabuddhi/atomspace,rTreutlein/atomspace,rTreutlein/atomspace,inflector/atomspace,AmeBel/atomspace
63b704f799d9ebf48db56d53940748a387037e9f
src/kernel/appupappsmodel.cpp
src/kernel/appupappsmodel.cpp
/* * Copyright 2011 Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 */ #include "appupappsmodel.h" #include <QHash> #include <QDir> #include <QDebug> #include <QStringList> #include <QFileSystemWatcher> #include <QtDeclarative/qdeclarative.h> #include <mdesktopentry.h> AppUpAppsModel::AppUpAppsModel(AppUpType type, QObject *parent) : QAbstractListModel(parent), mLimit(6), mType(type) { QHash<int, QByteArray> roles; roles.insert(AppUpAppsModel::Type, "type"); roles.insert(AppUpAppsModel::Title, "title"); roles.insert(AppUpAppsModel::Comment, "comment"); roles.insert(AppUpAppsModel::Icon, "icon"); roles.insert(AppUpAppsModel::Exec, "exec"); roles.insert(AppUpAppsModel::Filename, "filename"); setRoleNames(roles); mWatcher = new QFileSystemWatcher(this); qDebug() << "Type: " << type << "Adding path: " << APPUP_DESKTOP_PATH.arg(APPUP_DIRECTORIES.at(mType)); mWatcher->addPath(APPUP_DESKTOP_PATH.arg(QDir::homePath(), APPUP_DIRECTORIES.at(mType))); connect(mWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(loadDesktops())); loadDesktops(); } AppUpAppsModel::~AppUpAppsModel() { } int AppUpAppsModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); if (mLimit == 0) return mDesktops.count(); else return std::min(mDesktops.count(), mLimit); } QVariant AppUpAppsModel::data(const QModelIndex &index, int role) const { int row; if (!index.isValid() || index.row() >= mDesktops.count()) return QVariant(); row = index.row(); switch (role) { case AppUpAppsModel::Type: return mDesktops[row]->type(); break; case AppUpAppsModel::Title: return mDesktops[row]->name(); break; case AppUpAppsModel::Comment: return mDesktops[row]->comment(); break; case AppUpAppsModel::Exec: return mDesktops[row]->exec(); break; case AppUpAppsModel::Icon: return mDesktops[row]->icon(); break; case AppUpAppsModel::Filename: return mDesktops[row]->fileName(); break; default: qDebug("Unhandled data role requested in AppUpAppsModel::data(): %i", role); return QVariant(); break; } } //Private slots: void AppUpAppsModel::loadDesktops() { // qDebug("**** Beginning loadDesktops"); this->beginRemoveRows(QModelIndex(), 0, mDesktops.count()-1); mDesktops.clear(); this->endRemoveRows(); qDebug() << mWatcher->directories(); if (mWatcher->directories().count() < 1) { qDebug("No directories loaded into mWatcher!"); return; } QString curDir = mWatcher->directories().at(0); QDir dir(curDir); dir.setFilter(QDir::Files | QDir::NoSymLinks); QStringList filters; filters << "*.desktop"; foreach (QFileInfo fileInfo, dir.entryInfoList(filters)) { // qDebug("Inside foreach loop"); MDesktopEntry *newDesktop = new MDesktopEntry(fileInfo.absoluteFilePath()); // qDebug("After MDesktopEntry creation"); if (newDesktop->isValid()) { // qDebug("MDesktopEntry valid!"); this->beginInsertRows(QModelIndex(), mDesktops.count(), mDesktops.count()); mDesktops.append(new MDesktopEntry(fileInfo.absoluteFilePath())); this->endInsertRows(); // qDebug("After endInsertRows"); } } // qDebug("End of loadDesktops"); } //Private functions void AppUpAppsModel::setType(AppUpType type) { mType = type; emit this->typeChanged(); mWatcher->removePath(mWatcher->directories()[0]); mWatcher->addPath(APPUP_DESKTOP_PATH.arg(QDir::homePath(), APPUP_DIRECTORIES.at(mType))); loadDesktops(); } QML_DECLARE_TYPE(AppUpAppsModel);
/* * Copyright 2011 Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 */ #include "appupappsmodel.h" #include <QHash> #include <QDir> #include <QDebug> #include <QStringList> #include <QFileSystemWatcher> #include <QtDeclarative/qdeclarative.h> #include <mdesktopentry.h> AppUpAppsModel::AppUpAppsModel(AppUpType type, QObject *parent) : QAbstractListModel(parent), mLimit(6), mType(type) { QHash<int, QByteArray> roles; roles.insert(AppUpAppsModel::Type, "type"); roles.insert(AppUpAppsModel::Title, "title"); roles.insert(AppUpAppsModel::Comment, "comment"); roles.insert(AppUpAppsModel::Icon, "icon"); roles.insert(AppUpAppsModel::Exec, "exec"); roles.insert(AppUpAppsModel::Filename, "filename"); setRoleNames(roles); mWatcher = new QFileSystemWatcher(this); qDebug() << "Type: " << type << "Adding path: " << APPUP_DESKTOP_PATH.arg(APPUP_DIRECTORIES.at(mType)); mWatcher->addPath(APPUP_DESKTOP_PATH.arg(QDir::homePath(), APPUP_DIRECTORIES.at(mType))); connect(mWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(loadDesktops())); loadDesktops(); } AppUpAppsModel::~AppUpAppsModel() { } int AppUpAppsModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); if (mLimit == 0) return mDesktops.count(); else return std::min(mDesktops.count(), mLimit); } QVariant AppUpAppsModel::data(const QModelIndex &index, int role) const { int row; if (!index.isValid() || index.row() >= mDesktops.count()) return QVariant(); row = index.row(); switch (role) { case AppUpAppsModel::Type: return mDesktops[row]->type(); break; case AppUpAppsModel::Title: return mDesktops[row]->name(); break; case AppUpAppsModel::Comment: return mDesktops[row]->comment(); break; case AppUpAppsModel::Exec: return mDesktops[row]->exec(); break; case AppUpAppsModel::Icon: return mDesktops[row]->icon(); break; case AppUpAppsModel::Filename: return mDesktops[row]->fileName(); break; default: qDebug("Unhandled data role requested in AppUpAppsModel::data(): %i", role); return QVariant(); break; } } //Private slots: void AppUpAppsModel::loadDesktops() { // qDebug("**** Beginning loadDesktops"); if (mDesktops.count()) { this->beginRemoveRows(QModelIndex(), 0, mDesktops.count()-1); mDesktops.clear(); this->endRemoveRows(); } qDebug() << mWatcher->directories(); if (mWatcher->directories().count() < 1) { qDebug("No directories loaded into mWatcher!"); return; } QString curDir = mWatcher->directories().at(0); QDir dir(curDir); dir.setFilter(QDir::Files | QDir::NoSymLinks); QStringList filters; filters << "*.desktop"; foreach (QFileInfo fileInfo, dir.entryInfoList(filters)) { // qDebug("Inside foreach loop"); MDesktopEntry *newDesktop = new MDesktopEntry(fileInfo.absoluteFilePath()); // qDebug("After MDesktopEntry creation"); if (newDesktop->isValid()) { // qDebug("MDesktopEntry valid!"); this->beginInsertRows(QModelIndex(), mDesktops.count(), mDesktops.count()); mDesktops.append(new MDesktopEntry(fileInfo.absoluteFilePath())); this->endInsertRows(); // qDebug("After endInsertRows"); } } // qDebug("End of loadDesktops"); } //Private functions void AppUpAppsModel::setType(AppUpType type) { mType = type; emit this->typeChanged(); mWatcher->removePath(mWatcher->directories()[0]); mWatcher->addPath(APPUP_DESKTOP_PATH.arg(QDir::homePath(), APPUP_DIRECTORIES.at(mType))); loadDesktops(); } QML_DECLARE_TYPE(AppUpAppsModel);
Fix bug where a segfault could happen on transition from 0 desktops to > 0 desktops
Fix bug where a segfault could happen on transition from 0 desktops to > 0 desktops Signed-off-by: James Ausmus <[email protected]>
C++
apache-2.0
meego-tablet-ux/meegolabs-ux-components,meego-tablet-ux/meegolabs-ux-components
d3dd55a965fc5dba4ba02461853141cbaf5c0206
WickedEngine/RenderPath3D_TiledDeferred.cpp
WickedEngine/RenderPath3D_TiledDeferred.cpp
#include "RenderPath3D_TiledDeferred.h" #include "wiRenderer.h" #include "wiImage.h" #include "wiHelper.h" #include "wiTextureHelper.h" #include "wiSprite.h" #include "ResourceMapping.h" #include "wiProfiler.h" #include "wiBackLog.h" using namespace wiGraphics; void RenderPath3D_TiledDeferred::ResizeBuffers() { RenderPath3D_Deferred::ResizeBuffers(); GraphicsDevice* device = wiRenderer::GetDevice(); // Workaround textures if R11G11B10 UAV loads are not supported by the GPU: if(!device->CheckCapability(GraphicsDevice::GRAPHICSDEVICE_CAPABILITY_UAV_LOAD_FORMAT_R11G11B10_FLOAT)) { wiBackLog::post("\nWARNING: GRAPHICSDEVICE_CAPABILITY_UAV_LOAD_FORMAT_R11G11B10_FLOAT not supported, Tiled deferred will be using workaround slow path!\n"); TextureDesc desc; desc = lightbuffer_diffuse.GetDesc(); desc.Format = FORMAT_R16G16B16A16_FLOAT; device->CreateTexture(&desc, nullptr, &lightbuffer_diffuse_noR11G11B10supportavailable); device->SetName(&lightbuffer_diffuse_noR11G11B10supportavailable, "lightbuffer_diffuse_noR11G11B10supportavailable"); desc = lightbuffer_specular.GetDesc(); desc.Format = FORMAT_R16G16B16A16_FLOAT; device->CreateTexture(&desc, nullptr, &lightbuffer_specular_noR11G11B10supportavailable); device->SetName(&lightbuffer_specular_noR11G11B10supportavailable, "lightbuffer_specular_noR11G11B10supportavailable"); } } void RenderPath3D_TiledDeferred::Render() const { GraphicsDevice* device = wiRenderer::GetDevice(); wiJobSystem::context ctx; CommandList cmd; cmd = device->BeginCommandList(); wiJobSystem::Execute(ctx, [this, cmd] { RenderFrameSetUp(cmd); }); cmd = device->BeginCommandList(); wiJobSystem::Execute(ctx, [this, cmd] { RenderShadows(cmd); }); cmd = device->BeginCommandList(); wiJobSystem::Execute(ctx, [this, cmd] { RenderReflections(cmd); }); // Main scene: cmd = device->BeginCommandList(); wiJobSystem::Execute(ctx, [this, device, cmd] { wiRenderer::UpdateCameraCB(wiRenderer::GetCamera(), cmd); device->Barrier(&GPUBarrier::Image(&depthBuffer, IMAGE_LAYOUT_DEPTHSTENCIL_READONLY, IMAGE_LAYOUT_DEPTHSTENCIL), 1, cmd); { auto range = wiProfiler::BeginRangeGPU("Opaque Scene", cmd); device->RenderPassBegin(&renderpass_gbuffer, cmd); Viewport vp; vp.Width = (float)depthBuffer.GetDesc().Width; vp.Height = (float)depthBuffer.GetDesc().Height; device->BindViewports(1, &vp, cmd); device->BindResource(PS, getReflectionsEnabled() ? &rtReflection : wiTextureHelper::getTransparent(), TEXSLOT_RENDERPATH_REFLECTION, cmd); wiRenderer::DrawScene(wiRenderer::GetCamera(), getTessellationEnabled(), cmd, RENDERPASS_DEFERRED, true, true); device->RenderPassEnd(cmd); wiProfiler::EndRange(range); // Opaque Scene } { GPUBarrier barriers[] = { GPUBarrier::Image(&depthBuffer, IMAGE_LAYOUT_DEPTHSTENCIL, IMAGE_LAYOUT_COPY_SRC), GPUBarrier::Image(&depthBuffer_Copy, IMAGE_LAYOUT_SHADER_RESOURCE, IMAGE_LAYOUT_COPY_DST) }; device->Barrier(barriers, arraysize(barriers), cmd); } device->CopyResource(&depthBuffer_Copy, &depthBuffer, cmd); { GPUBarrier barriers[] = { GPUBarrier::Image(&depthBuffer, IMAGE_LAYOUT_COPY_SRC, IMAGE_LAYOUT_DEPTHSTENCIL_READONLY), GPUBarrier::Image(&depthBuffer_Copy, IMAGE_LAYOUT_COPY_DST, IMAGE_LAYOUT_SHADER_RESOURCE) }; device->Barrier(barriers, arraysize(barriers), cmd); } RenderLinearDepth(cmd); RenderSSAO(cmd); }); cmd = device->BeginCommandList(); wiJobSystem::Execute(ctx, [this, device, cmd] { wiRenderer::UpdateCameraCB(wiRenderer::GetCamera(), cmd); wiRenderer::BindCommonResources(cmd); RenderDecals(cmd); device->BindResource(CS, getSSAOEnabled() ? &rtSSAO[0] : wiTextureHelper::getWhite(), TEXSLOT_RENDERPATH_SSAO, cmd); device->BindResource(CS, getSSREnabled() ? &rtSSR : wiTextureHelper::getTransparent(), TEXSLOT_RENDERPATH_SSR, cmd); if (device->CheckCapability(GraphicsDevice::GRAPHICSDEVICE_CAPABILITY_UAV_LOAD_FORMAT_R11G11B10_FLOAT)) { wiRenderer::ComputeTiledLightCulling( depthBuffer_Copy, cmd, &rtGBuffer[0], &rtGBuffer[1], &rtGBuffer[2], &lightbuffer_diffuse, &lightbuffer_specular ); } else { // This workaround if R11G11B10_FLOAT can't be used with UAV loads copies into R16G16B16A16_FLOAT, does the tiled deferred then copies back: device->EventBegin("WARNING: GRAPHICSDEVICE_CAPABILITY_UAV_LOAD_FORMAT_R11G11B10_FLOAT not supported workaround!", cmd); wiRenderer::CopyTexture2D(lightbuffer_diffuse_noR11G11B10supportavailable, 0, 0, 0, lightbuffer_diffuse, 0, cmd); wiRenderer::CopyTexture2D(lightbuffer_specular_noR11G11B10supportavailable, 0, 0, 0, lightbuffer_specular, 0, cmd); wiRenderer::ComputeTiledLightCulling( depthBuffer_Copy, cmd, &rtGBuffer[0], &rtGBuffer[1], &rtGBuffer[2], &lightbuffer_diffuse_noR11G11B10supportavailable, &lightbuffer_specular_noR11G11B10supportavailable ); wiRenderer::CopyTexture2D(lightbuffer_diffuse, 0, 0, 0, lightbuffer_diffuse_noR11G11B10supportavailable, 0, cmd); wiRenderer::CopyTexture2D(lightbuffer_specular, 0, 0, 0, lightbuffer_specular_noR11G11B10supportavailable, 0, cmd); device->EventEnd(cmd); } }); cmd = device->BeginCommandList(); wiJobSystem::Execute(ctx, [this, device, cmd] { wiRenderer::UpdateCameraCB(wiRenderer::GetCamera(), cmd); wiRenderer::BindCommonResources(cmd); RenderSSS(cmd); RenderDeferredComposition(cmd); RenderSSR(rtDeferred, rtGBuffer[1], cmd); DownsampleDepthBuffer(cmd); RenderLightShafts(cmd); RenderVolumetrics(cmd); RenderRefractionSource(rtDeferred, cmd); RenderTransparents(renderpass_transparent, RENDERPASS_TILEDFORWARD, cmd); RenderOutline(rtDeferred, cmd); RenderPostprocessChain(rtDeferred, rtGBuffer[1], cmd); }); RenderPath2D::Render(); wiJobSystem::Wait(ctx); }
#include "RenderPath3D_TiledDeferred.h" #include "wiRenderer.h" #include "wiImage.h" #include "wiHelper.h" #include "wiTextureHelper.h" #include "wiSprite.h" #include "ResourceMapping.h" #include "wiProfiler.h" #include "wiBackLog.h" using namespace wiGraphics; void RenderPath3D_TiledDeferred::ResizeBuffers() { RenderPath3D_Deferred::ResizeBuffers(); GraphicsDevice* device = wiRenderer::GetDevice(); // Workaround textures if R11G11B10 UAV loads are not supported by the GPU: if(!device->CheckCapability(GraphicsDevice::GRAPHICSDEVICE_CAPABILITY_UAV_LOAD_FORMAT_R11G11B10_FLOAT)) { wiBackLog::post("\nWARNING: GRAPHICSDEVICE_CAPABILITY_UAV_LOAD_FORMAT_R11G11B10_FLOAT not supported, Tiled deferred will be using workaround slow path!\n"); TextureDesc desc; desc = lightbuffer_diffuse.GetDesc(); desc.Format = FORMAT_R16G16B16A16_FLOAT; device->CreateTexture(&desc, nullptr, &lightbuffer_diffuse_noR11G11B10supportavailable); device->SetName(&lightbuffer_diffuse_noR11G11B10supportavailable, "lightbuffer_diffuse_noR11G11B10supportavailable"); desc = lightbuffer_specular.GetDesc(); desc.Format = FORMAT_R16G16B16A16_FLOAT; device->CreateTexture(&desc, nullptr, &lightbuffer_specular_noR11G11B10supportavailable); device->SetName(&lightbuffer_specular_noR11G11B10supportavailable, "lightbuffer_specular_noR11G11B10supportavailable"); } } void RenderPath3D_TiledDeferred::Render() const { GraphicsDevice* device = wiRenderer::GetDevice(); wiJobSystem::context ctx; CommandList cmd; cmd = device->BeginCommandList(); wiJobSystem::Execute(ctx, [this, cmd] { RenderFrameSetUp(cmd); }); cmd = device->BeginCommandList(); wiJobSystem::Execute(ctx, [this, cmd] { RenderShadows(cmd); }); cmd = device->BeginCommandList(); wiJobSystem::Execute(ctx, [this, cmd] { RenderReflections(cmd); }); // Main scene: cmd = device->BeginCommandList(); wiJobSystem::Execute(ctx, [this, device, cmd] { wiRenderer::UpdateCameraCB(wiRenderer::GetCamera(), cmd); device->Barrier(&GPUBarrier::Image(&depthBuffer, IMAGE_LAYOUT_DEPTHSTENCIL_READONLY, IMAGE_LAYOUT_DEPTHSTENCIL), 1, cmd); { auto range = wiProfiler::BeginRangeGPU("Opaque Scene", cmd); device->RenderPassBegin(&renderpass_gbuffer, cmd); Viewport vp; vp.Width = (float)depthBuffer.GetDesc().Width; vp.Height = (float)depthBuffer.GetDesc().Height; device->BindViewports(1, &vp, cmd); device->BindResource(PS, getReflectionsEnabled() ? &rtReflection : wiTextureHelper::getTransparent(), TEXSLOT_RENDERPATH_REFLECTION, cmd); wiRenderer::DrawScene(wiRenderer::GetCamera(), getTessellationEnabled(), cmd, RENDERPASS_DEFERRED, true, true); device->RenderPassEnd(cmd); wiProfiler::EndRange(range); // Opaque Scene } { GPUBarrier barriers[] = { GPUBarrier::Image(&depthBuffer, IMAGE_LAYOUT_DEPTHSTENCIL, IMAGE_LAYOUT_COPY_SRC), GPUBarrier::Image(&depthBuffer_Copy, IMAGE_LAYOUT_SHADER_RESOURCE, IMAGE_LAYOUT_COPY_DST) }; device->Barrier(barriers, arraysize(barriers), cmd); } device->CopyResource(&depthBuffer_Copy, &depthBuffer, cmd); { GPUBarrier barriers[] = { GPUBarrier::Image(&depthBuffer, IMAGE_LAYOUT_COPY_SRC, IMAGE_LAYOUT_DEPTHSTENCIL_READONLY), GPUBarrier::Image(&depthBuffer_Copy, IMAGE_LAYOUT_COPY_DST, IMAGE_LAYOUT_SHADER_RESOURCE) }; device->Barrier(barriers, arraysize(barriers), cmd); } RenderLinearDepth(cmd); RenderSSAO(cmd); }); cmd = device->BeginCommandList(); wiJobSystem::Execute(ctx, [this, device, cmd] { wiRenderer::UpdateCameraCB(wiRenderer::GetCamera(), cmd); wiRenderer::BindCommonResources(cmd); RenderDecals(cmd); device->BindResource(CS, getSSAOEnabled() ? &rtSSAO[0] : wiTextureHelper::getWhite(), TEXSLOT_RENDERPATH_SSAO, cmd); device->BindResource(CS, getSSREnabled() ? &rtStochasticSSR : wiTextureHelper::getTransparent(), TEXSLOT_RENDERPATH_SSR, cmd); if (device->CheckCapability(GraphicsDevice::GRAPHICSDEVICE_CAPABILITY_UAV_LOAD_FORMAT_R11G11B10_FLOAT)) { wiRenderer::ComputeTiledLightCulling( depthBuffer_Copy, cmd, &rtGBuffer[0], &rtGBuffer[1], &rtGBuffer[2], &lightbuffer_diffuse, &lightbuffer_specular ); } else { // This workaround if R11G11B10_FLOAT can't be used with UAV loads copies into R16G16B16A16_FLOAT, does the tiled deferred then copies back: device->EventBegin("WARNING: GRAPHICSDEVICE_CAPABILITY_UAV_LOAD_FORMAT_R11G11B10_FLOAT not supported workaround!", cmd); wiRenderer::CopyTexture2D(lightbuffer_diffuse_noR11G11B10supportavailable, 0, 0, 0, lightbuffer_diffuse, 0, cmd); wiRenderer::CopyTexture2D(lightbuffer_specular_noR11G11B10supportavailable, 0, 0, 0, lightbuffer_specular, 0, cmd); wiRenderer::ComputeTiledLightCulling( depthBuffer_Copy, cmd, &rtGBuffer[0], &rtGBuffer[1], &rtGBuffer[2], &lightbuffer_diffuse_noR11G11B10supportavailable, &lightbuffer_specular_noR11G11B10supportavailable ); wiRenderer::CopyTexture2D(lightbuffer_diffuse, 0, 0, 0, lightbuffer_diffuse_noR11G11B10supportavailable, 0, cmd); wiRenderer::CopyTexture2D(lightbuffer_specular, 0, 0, 0, lightbuffer_specular_noR11G11B10supportavailable, 0, cmd); device->EventEnd(cmd); } }); cmd = device->BeginCommandList(); wiJobSystem::Execute(ctx, [this, device, cmd] { wiRenderer::UpdateCameraCB(wiRenderer::GetCamera(), cmd); wiRenderer::BindCommonResources(cmd); RenderSSS(cmd); RenderDeferredComposition(cmd); RenderStochasticSSR(rtDeferred, rtGBuffer[0], rtGBuffer[1], rtGBuffer[2], cmd); DownsampleDepthBuffer(cmd); RenderLightShafts(cmd); RenderVolumetrics(cmd); RenderRefractionSource(rtDeferred, cmd); RenderTransparents(renderpass_transparent, RENDERPASS_TILEDFORWARD, cmd); RenderOutline(rtDeferred, cmd); RenderPostprocessChain(rtDeferred, rtGBuffer[1], cmd); }); RenderPath2D::Render(); wiJobSystem::Wait(ctx); }
Update RenderPath3D_TiledDeferred.cpp
Update RenderPath3D_TiledDeferred.cpp
C++
mit
turanszkij/WickedEngine,turanszkij/WickedEngine,turanszkij/WickedEngine,turanszkij/WickedEngine
0e52cc4ec5287efd7cd039aac946e2c19c485b5b
src-qt5/desktop-utils/lumina-fm/Browser.cpp
src-qt5/desktop-utils/lumina-fm/Browser.cpp
//=========================================== // Lumina-DE source code // Copyright (c) 2016, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "Browser.h" #include <QStringList> #include <QTimer> #include <QtConcurrent> #include <QDebug> #include <LUtils.h> Browser::Browser(QObject *parent) : QObject(parent){ watcher = new QFileSystemWatcher(this); connect(watcher, SIGNAL(fileChanged(const QString&)), this, SLOT(fileChanged(QString)) ); connect(watcher, SIGNAL(directoryChanged(const QString&)), this, SLOT(dirChanged(QString)) ); showHidden = false; showThumbs = false; imageFormats = LUtils::imageExtensions(false); //lowercase suffixes connect(this, SIGNAL(threadDone(QString, QImage)), this, SLOT(futureFinished(QString, QImage))); //will always be between different threads } Browser::~Browser(){ //watcher->deleteLater(); } QString Browser::currentDirectory(){ return currentDir; } void Browser::showHiddenFiles(bool show){ if(show !=showHidden){ showHidden = show; if(!currentDir.isEmpty()){ QTimer::singleShot(0, this, SLOT(loadDirectory()) ); } } } bool Browser::showingHiddenFiles(){ return showHidden; } void Browser::showThumbnails(bool show){ if(show != showThumbs){ showThumbs = show; if(!currentDir.isEmpty()){ QTimer::singleShot(0, this, SLOT(loadDirectory()) ); } } } bool Browser::showingThumbnails(){ return showThumbs; } // PRIVATE void Browser::loadItem(QString info, Browser *obj){ QImage pix; if(imageFormats.contains(info.section(".",-1).toLower()) ){ QFile file(info); if(file.open(QIODevice::ReadOnly)){ QByteArray bytes = file.readAll(); file.close(); pix.loadFromData(bytes); if(pix.width() > 256 || pix.height() > 256 ){ pix = pix.scaled(256,256, Qt::KeepAspectRatio, Qt::SmoothTransformation); } } } //qDebug() << " - done with item:" << info; obj->emit threadDone(info, pix); } QIcon Browser::loadIcon(QString icon){ if(!mimeIcons.contains(icon)){ mimeIcons.insert(icon, LXDG::findIcon(icon, "unknown")); } return mimeIcons[icon]; } // PRIVATE SLOTS void Browser::fileChanged(QString file){ if(file.startsWith(currentDir+"/") ){ if(QFile::exists(file) ){ QtConcurrent::run(this, &Browser::loadItem, file, this); } //file modified but not removed else{ QTimer::singleShot(0, this, SLOT(loadDirectory()) ); } //file removed - need to update entire dir }else if(file==currentDir){ QTimer::singleShot(0, this, SLOT(loadDirectory()) ); } } void Browser::dirChanged(QString dir){ if(dir==currentDir){ QTimer::singleShot(500, this, SLOT(loadDirectory()) ); } else if(dir.startsWith(currentDir)){ QtConcurrent::run(this, &Browser::loadItem, dir, this ); } } void Browser::futureFinished(QString name, QImage icon){ //Note: this will be called once for every item that loads QIcon ico; //LFileInfo info(name); LFileInfo *info = new LFileInfo(name); if(!icon.isNull()){ //qDebug() << " -- Data:"; QPixmap pix = QPixmap::fromImage(icon); ico.addPixmap(pix); }else if(info->isDir()){ //qDebug() << " -- Folder:"; ico = loadIcon("folder"); } if(ico.isNull()){ //qDebug() << " -- MimeType:" << info.fileName() << info.mimetype(); ico = loadIcon(info->iconfile()); } this->emit itemDataAvailable( ico, info); //qDebug() << " -- done:" << name; } // PUBLIC SLOTS void Browser::loadDirectory(QString dir){ if(dir.isEmpty()){ dir = currentDir; } //reload current directory if(dir.isEmpty()){ return; } //nothing to do - nothing previously loaded //qDebug() << "Load Directory" << dir; if(currentDir != dir){ //let the main widget know to clear all current items (completely different dir) oldFiles.clear(); emit clearItems(); } currentDir = dir; //save this for later //clean up the watcher first QStringList watched; watched << watcher->files() << watcher->directories(); if(!watched.isEmpty()){ watcher->removePaths(watched); } QStringList old = oldFiles; //copy this over for the moment (both lists will change in a moment) oldFiles.clear(); //get ready for re-creating this list // read the given directory QDir directory(dir); if(directory.exists()){ QStringList files; if(showHidden){ files = directory.entryList( QDir::Dirs | QDir::Files | QDir::Hidden | QDir::NoDotAndDotDot, QDir::NoSort); } else{ files = directory.entryList( QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot, QDir::NoSort); } emit itemsLoading(files.length()); for(int i=0; i<files.length(); i++){ watcher->addPath(directory.absoluteFilePath(files[i])); //qDebug() << "Future Starting:" << files[i]; QString path = directory.absoluteFilePath(files[i]); if(old.contains(path)){ old.removeAll(path); } oldFiles << path; //add to list for next time if(showThumbs && imageFormats.contains(path.section(".",-1).toLower())){ QtConcurrent::run(this, &Browser::loadItem, path, this); }else{ //No special icon loading - just skip the file read step futureFinished(path, QImage()); //loadItem(path, this); } } watcher->addPath(directory.absolutePath()); if(!old.isEmpty()){ old.removeAll(directory.absolutePath()); for(int i=0; i<old.length(); i++){ emit itemRemoved(old[i]); } } }else{ emit itemsLoading(0); //nothing to load } }
//=========================================== // Lumina-DE source code // Copyright (c) 2016, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "Browser.h" #include <QStringList> #include <QTimer> #include <QtConcurrent> #include <QDebug> #include <LUtils.h> Browser::Browser(QObject *parent) : QObject(parent){ watcher = new QFileSystemWatcher(this); connect(watcher, SIGNAL(fileChanged(const QString&)), this, SLOT(fileChanged(QString)) ); connect(watcher, SIGNAL(directoryChanged(const QString&)), this, SLOT(dirChanged(QString)) ); showHidden = false; showThumbs = false; imageFormats = LUtils::imageExtensions(false); //lowercase suffixes connect(this, SIGNAL(threadDone(QString, QImage)), this, SLOT(futureFinished(QString, QImage))); //will always be between different threads } Browser::~Browser(){ //watcher->deleteLater(); } QString Browser::currentDirectory(){ return currentDir; } void Browser::showHiddenFiles(bool show){ if(show !=showHidden){ showHidden = show; if(!currentDir.isEmpty()){ QTimer::singleShot(0, this, SLOT(loadDirectory()) ); } } } bool Browser::showingHiddenFiles(){ return showHidden; } void Browser::showThumbnails(bool show){ if(show != showThumbs){ showThumbs = show; if(!currentDir.isEmpty()){ QTimer::singleShot(0, this, SLOT(loadDirectory()) ); } } } bool Browser::showingThumbnails(){ return showThumbs; } // PRIVATE void Browser::loadItem(QString info, Browser *obj){ QImage pix; if(imageFormats.contains(info.section(".",-1).toLower()) ){ QFile file(info); if(file.open(QIODevice::ReadOnly)){ QByteArray bytes = file.readAll(); file.close(); pix.loadFromData(bytes); if(pix.width() > 256 || pix.height() > 256 ){ pix = pix.scaled(256,256, Qt::KeepAspectRatio, Qt::SmoothTransformation); } } } //qDebug() << " - done with item:" << info; obj->emit threadDone(info, pix); } QIcon Browser::loadIcon(QString icon){ if(!mimeIcons.contains(icon)){ mimeIcons.insert(icon, LXDG::findIcon(icon, "unknown")); } return mimeIcons[icon]; } // PRIVATE SLOTS void Browser::fileChanged(QString file){ if(file.startsWith(currentDir+"/") ){ if(QFile::exists(file) ){ QtConcurrent::run(this, &Browser::loadItem, file, this); } //file modified but not removed else{ QTimer::singleShot(0, this, SLOT(loadDirectory()) ); } //file removed - need to update entire dir }else if(file==currentDir){ QTimer::singleShot(0, this, SLOT(loadDirectory()) ); } } void Browser::dirChanged(QString dir){ if(dir==currentDir){ QTimer::singleShot(500, this, SLOT(loadDirectory()) ); } else if(dir.startsWith(currentDir)){ QtConcurrent::run(this, &Browser::loadItem, dir, this ); } } void Browser::futureFinished(QString name, QImage icon){ //Note: this will be called once for every item that loads QIcon ico; //LFileInfo info(name); LFileInfo *info = new LFileInfo(name); if(!icon.isNull() && showThumbs){ //qDebug() << " -- Data:"; QPixmap pix = QPixmap::fromImage(icon); ico.addPixmap(pix); //}else if(info->isDir()){ //qDebug() << " -- Folder:"; //ico = loadIcon("folder"); } if(ico.isNull()){ //qDebug() << " -- MimeType:" << info.fileName() << info.mimetype(); ico = loadIcon(info->iconfile()); } this->emit itemDataAvailable( ico, info); //qDebug() << " -- done:" << name; } // PUBLIC SLOTS void Browser::loadDirectory(QString dir){ if(dir.isEmpty()){ dir = currentDir; } //reload current directory if(dir.isEmpty()){ return; } //nothing to do - nothing previously loaded //qDebug() << "Load Directory" << dir; if(currentDir != dir){ //let the main widget know to clear all current items (completely different dir) oldFiles.clear(); emit clearItems(); } currentDir = dir; //save this for later //clean up the watcher first QStringList watched; watched << watcher->files() << watcher->directories(); if(!watched.isEmpty()){ watcher->removePaths(watched); } QStringList old = oldFiles; //copy this over for the moment (both lists will change in a moment) oldFiles.clear(); //get ready for re-creating this list // read the given directory QDir directory(dir); if(directory.exists()){ QStringList files; if(showHidden){ files = directory.entryList( QDir::Dirs | QDir::Files | QDir::Hidden | QDir::NoDotAndDotDot, QDir::NoSort); } else{ files = directory.entryList( QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot, QDir::NoSort); } emit itemsLoading(files.length()); for(int i=0; i<files.length(); i++){ watcher->addPath(directory.absoluteFilePath(files[i])); //qDebug() << "Future Starting:" << files[i]; QString path = directory.absoluteFilePath(files[i]); if(old.contains(path)){ old.removeAll(path); } oldFiles << path; //add to list for next time //if(showThumbs && imageFormats.contains(path.section(".",-1).toLower())){ QtConcurrent::run(this, &Browser::loadItem, path, this); /*}else{ //No special icon loading - just skip the file read step futureFinished(path, QImage()); //loadItem(path, this); }*/ } watcher->addPath(directory.absolutePath()); if(!old.isEmpty()){ old.removeAll(directory.absolutePath()); for(int i=0; i<old.length(); i++){ emit itemRemoved(old[i]); } } }else{ emit itemsLoading(0); //nothing to load } }
Update the browser to multi-thread *all* file loading, not just thumbnails.
Update the browser to multi-thread *all* file loading, not just thumbnails.
C++
bsd-3-clause
sasongko26/lumina,sasongko26/lumina,sasongko26/lumina,sasongko26/lumina,sasongko26/lumina,cpforbes/lumina,trueos/lumina,trueos/lumina,trueos/lumina,cpforbes/lumina,sasongko26/lumina,cpforbes/lumina,trueos/lumina,trueos/lumina,sasongko26/lumina,pcbsd/lumina,pcbsd/lumina,trueos/lumina,cpforbes/lumina,trueos/lumina,sasongko26/lumina,cpforbes/lumina,cpforbes/lumina,trueos/lumina,pcbsd/lumina,cpforbes/lumina,cpforbes/lumina
0ecbfdc45c679b1044dec5221e670a01b84545d4
unitTests/src/ofApp.cpp
unitTests/src/ofApp.cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofTrueTypeFont::setGlobalDpi(72); ofSetBackgroundColor(0, 0, 0); verdana14.load("verdana.ttf", 14, true, true); verdana14.setLineHeight(18.0f); verdana14.setLetterSpacing(1.037); // A simple DOL System, as describe at the beginning of the book vector<string> expectedSimpleDOL{ "B", "A", "AB", "ABA", "ABAAB", "ABAABABA", }; auto SimpleDOL = RuleTest( "A simple DOL System", "B", vector<string> {"A->AB", "B->A"}, 5, expectedSimpleDOL ); SimpleDOL.executeTest(); tests.push_back(SimpleDOL); // parametric test rule with constants vector<string> expectedParametricWithConstantsResult{ "A(12)", "F(12)[+A(6)][-A(6)]", "F(12)[+F(6)[+A(3)][-A(3)]][-F(6)[+A(3)][-A(3)]]" }; map<string, float> constants; constants.insert(make_pair("R", 2.0)); auto parametricWithConstants = RuleTest( "Parametric Grammar test with Constants", "A(12)", vector<string> {"A(s)->F(s)[+A(s/R)][-A(s/R)]"}, 2, expectedParametricWithConstantsResult, constants ); parametricWithConstants.executeTest(); tests.push_back(parametricWithConstants); //parametric test. Rules also in page 43 of "The Algorithmic Beauty of Plants" vector<string> parametricRules; parametricRules.push_back("A(x,y): y<=3 -> A(x*2,x+y)"); parametricRules.push_back("A(x,y): y>3 -> B(x)A(x/y,0)"); parametricRules.push_back("B(x) :x<1 -> C"); parametricRules.push_back("B(x) : x>=1 -> B(x-1)"); vector<string> expectedParametricResult { "B(2)A(4,4)", "B(1)B(4)A(1,0)", "B(0)B(3)A(2,1)", "CB(2)A(4,3)" }; auto parametricTest = RuleTest("Parametric Grammar test", "B(2)A(4,4)", parametricRules, 3, expectedParametricResult ); parametricTest.executeTest(); tests.push_back(parametricTest); } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ int x = 20; int y = 20; for(auto test : tests){ string text; if(test.isPassed()){ ofSetColor(0,255,0); text = test.getTitle() += ": OK"; }else{ ofSetColor(255,0,0); text = test.getTitle() += ": ERROR, expected:\n"; for(auto r :test.getExpectedResult()){ text+= r + "\n"; } text += "\ngot: \n"; for(auto r :test.getResult()){ text+= r + "\n"; } } ofRectangle bounds = verdana14.getStringBoundingBox(text, 100, y); auto passed = test.isPassed() ? "OK" : "ERROR"; verdana14.drawString(text , x, y ); y += bounds.height+5; } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofTrueTypeFont::setGlobalDpi(72); ofSetBackgroundColor(0, 0, 0); verdana14.load("verdana.ttf", 14, true, true); verdana14.setLineHeight(18.0f); verdana14.setLetterSpacing(1.037); // A simple DOL System, as describe at the beginning of the book vector<string> expectedSimpleDOL{ "B", "A", "AB", "ABA", "ABAAB", "ABAABABA", }; auto SimpleDOL = RuleTest( "A simple DOL System", "B", vector<string> {"A->AB", "B->A"}, 5, expectedSimpleDOL ); SimpleDOL.executeTest(); tests.push_back(SimpleDOL); // Bracketed edge rewriting system, second example page 25 vector<string> expectedBracketedEdge{ "F", "F[+F]F[-F][F]", "F[+F]F[-F][F][+F[+F]F[-F][F]]F[+F]F[-F][F][-F[+F]F[-F][F]][F[+F]F[-F][F]]", "F[+F]F[-F][F][+F[+F]F[-F][F]]F[+F]F[-F][F][-F[+F]F[-F][F]][F[+F]F[-F][F]][+F[+F]F[-F][F][+F[+F]F[-F][F]]F[+F]F[-F][F][-F[+F]F[-F][F]][F[+F]F[-F][F]]]F[+F]F[-F][F][+F[+F]F[-F][F]]F[+F]F[-F][F][-F[+F]F[-F][F]][F[+F]F[-F][F]][-F[+F]F[-F][F][+F[+F]F[-F][F]]F[+F]F[-F][F][-F[+F]F[-F][F]][F[+F]F[-F][F]]][F[+F]F[-F][F][+F[+F]F[-F][F]]F[+F]F[-F][F][-F[+F]F[-F][F]][F[+F]F[-F][F]]]" }; auto bracketedEdge = RuleTest( "A bracketed edge rewriting system", "F", vector<string> {"F->F[+F]F[-F][F]"}, 3, expectedBracketedEdge ); bracketedEdge.executeTest(); tests.push_back(bracketedEdge); // parametric test rule with constants vector<string> expectedParametricWithConstantsResult{ "A(12)", "F(12)[+A(6)][-A(6)]", "F(12)[+F(6)[+A(3)][-A(3)]][-F(6)[+A(3)][-A(3)]]" }; map<string, float> constants; constants.insert(make_pair("R", 2.0)); auto parametricWithConstants = RuleTest( "Parametric Grammar test with Constants", "A(12)", vector<string> {"A(s)->F(s)[+A(s/R)][-A(s/R)]"}, 2, expectedParametricWithConstantsResult, constants ); parametricWithConstants.executeTest(); tests.push_back(parametricWithConstants); //parametric test. Rules also in page 43 of "The Algorithmic Beauty of Plants" vector<string> parametricRules; parametricRules.push_back("A(x,y): y<=3 -> A(x*2,x+y)"); parametricRules.push_back("A(x,y): y>3 -> B(x)A(x/y,0)"); parametricRules.push_back("B(x) :x<1 -> C"); parametricRules.push_back("B(x) : x>=1 -> B(x-1)"); vector<string> expectedParametricResult { "B(2)A(4,4)", "B(1)B(4)A(1,0)", "B(0)B(3)A(2,1)", "CB(2)A(4,3)" }; auto parametricTest = RuleTest("Parametric Grammar test", "B(2)A(4,4)", parametricRules, 3, expectedParametricResult ); parametricTest.executeTest(); tests.push_back(parametricTest); } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ int x = 20; int y = 20; for(auto test : tests){ string text; if(test.isPassed()){ ofSetColor(0,255,0); text = test.getTitle() += ": OK"; }else{ ofSetColor(255,0,0); text = test.getTitle() += ": ERROR, expected:\n"; for(auto r :test.getExpectedResult()){ text+= r + "\n"; } text += "\ngot: \n"; for(auto r :test.getResult()){ cout << r + "\n\n"<< endl; text+= r + "\n"; } } ofRectangle bounds = verdana14.getStringBoundingBox(text, 100, y); auto passed = test.isPassed() ? "OK" : "ERROR"; verdana14.drawString(text , x, y ); y += bounds.height+5; } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
add unit test for bracketed edge rewriting L-System
add unit test for bracketed edge rewriting L-System
C++
mit
edap/ofxLSystemGrammar
0788454513ced7e075071e4deb97d05411bebad1
unit_test/color_test.cc
unit_test/color_test.cc
/* * Copyright 2015 The LibYuv 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 <stdlib.h> #include "libyuv/convert.h" #include "libyuv/convert_argb.h" #include "libyuv/convert_from.h" #include "libyuv/convert_from_argb.h" #include "libyuv/cpu_id.h" #include "libyuv/row.h" // For Sobel #include "../unit_test/unit_test.h" namespace libyuv { #define TESTCS(TESTNAME, YUVTOARGB, ARGBTOYUV, HS1, HS, HN, DIFF) \ TEST_F(libyuvTest, TESTNAME) { \ const int kPixels = benchmark_width_ * benchmark_height_; \ const int kHalfPixels = ((benchmark_width_ + 1) / 2) * \ ((benchmark_height_ + HS1) / HS); \ align_buffer_64(orig_y, kPixels); \ align_buffer_64(orig_u, kHalfPixels); \ align_buffer_64(orig_v, kHalfPixels); \ align_buffer_64(orig_pixels, kPixels * 4); \ align_buffer_64(temp_y, kPixels); \ align_buffer_64(temp_u, kHalfPixels); \ align_buffer_64(temp_v, kHalfPixels); \ align_buffer_64(dst_pixels_opt, kPixels * 4); \ align_buffer_64(dst_pixels_c, kPixels * 4); \ \ MemRandomize(orig_pixels, kPixels * 4); \ MemRandomize(orig_y, kPixels); \ MemRandomize(orig_u, kHalfPixels); \ MemRandomize(orig_v, kHalfPixels); \ MemRandomize(temp_y, kPixels); \ MemRandomize(temp_u, kHalfPixels); \ MemRandomize(temp_v, kHalfPixels); \ MemRandomize(dst_pixels_opt, kPixels * 4); \ MemRandomize(dst_pixels_c, kPixels * 4); \ \ /* The test is overall for color conversion matrix being reversible, so */ \ /* this initializes the pixel with 2x2 blocks to eliminate subsampling. */ \ uint8* p = orig_y; \ for (int y = 0; y < benchmark_height_ - HS1; y += HS) { \ for (int x = 0; x < benchmark_width_ - 1; x += 2) { \ uint8 r = static_cast<uint8>(random()); \ p[0] = r; \ p[1] = r; \ p[HN] = r; \ p[HN + 1] = r; \ p += 2; \ } \ p += HN; \ } \ \ /* Start with YUV converted to ARGB. */ \ YUVTOARGB(orig_y, benchmark_width_, \ orig_u, (benchmark_width_ + 1) / 2, \ orig_v, (benchmark_width_ + 1) / 2, \ orig_pixels, benchmark_width_ * 4, \ benchmark_width_, benchmark_height_); \ \ ARGBTOYUV(orig_pixels, benchmark_width_ * 4, \ temp_y, benchmark_width_, \ temp_u, (benchmark_width_ + 1) / 2, \ temp_v, (benchmark_width_ + 1) / 2, \ benchmark_width_, benchmark_height_); \ \ MaskCpuFlags(0); \ YUVTOARGB(temp_y, benchmark_width_, \ temp_u, (benchmark_width_ + 1) / 2, \ temp_v, (benchmark_width_ + 1) / 2, \ dst_pixels_c, benchmark_width_ * 4, \ benchmark_width_, benchmark_height_); \ MaskCpuFlags(-1); \ \ for (int i = 0; i < benchmark_iterations_; ++i) { \ YUVTOARGB(temp_y, benchmark_width_, \ temp_u, (benchmark_width_ + 1) / 2, \ temp_v, (benchmark_width_ + 1) / 2, \ dst_pixels_opt, benchmark_width_ * 4, \ benchmark_width_, benchmark_height_); \ } \ /* Test C and SIMD match. */ \ for (int i = 0; i < kPixels * 4; ++i) { \ EXPECT_EQ(dst_pixels_c[i], dst_pixels_opt[i]); \ } \ /* Test SIMD is close to original. */ \ for (int i = 0; i < kPixels * 4; ++i) { \ EXPECT_NEAR(static_cast<int>(orig_pixels[i]), \ static_cast<int>(dst_pixels_opt[i]), DIFF); \ } \ \ free_aligned_buffer_64(orig_pixels); \ free_aligned_buffer_64(orig_y); \ free_aligned_buffer_64(orig_u); \ free_aligned_buffer_64(orig_v); \ free_aligned_buffer_64(temp_y); \ free_aligned_buffer_64(temp_u); \ free_aligned_buffer_64(temp_v); \ free_aligned_buffer_64(dst_pixels_opt); \ free_aligned_buffer_64(dst_pixels_c); \ } \ TESTCS(TestI420, I420ToARGB, ARGBToI420, 1, 2, benchmark_width_, 7) TESTCS(TestI422, I422ToARGB, ARGBToI422, 0, 1, 0, 7) TESTCS(TestJ420, J420ToARGB, ARGBToJ420, 1, 2, benchmark_width_, 3) TESTCS(TestJ422, J422ToARGB, ARGBToJ422, 0, 1, 0, 3) } // namespace libyuv
/* * Copyright 2015 The LibYuv 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 <stdlib.h> #include "libyuv/convert.h" #include "libyuv/convert_argb.h" #include "libyuv/convert_from.h" #include "libyuv/convert_from_argb.h" #include "libyuv/cpu_id.h" #include "libyuv/row.h" // For Sobel #include "../unit_test/unit_test.h" namespace libyuv { #define TESTCS(TESTNAME, YUVTOARGB, ARGBTOYUV, HS1, HS, HN, DIFF) \ TEST_F(libyuvTest, TESTNAME) { \ const int kPixels = benchmark_width_ * benchmark_height_; \ const int kHalfPixels = ((benchmark_width_ + 1) / 2) * \ ((benchmark_height_ + HS1) / HS); \ align_buffer_64(orig_y, kPixels); \ align_buffer_64(orig_u, kHalfPixels); \ align_buffer_64(orig_v, kHalfPixels); \ align_buffer_64(orig_pixels, kPixels * 4); \ align_buffer_64(temp_y, kPixels); \ align_buffer_64(temp_u, kHalfPixels); \ align_buffer_64(temp_v, kHalfPixels); \ align_buffer_64(dst_pixels_opt, kPixels * 4); \ align_buffer_64(dst_pixels_c, kPixels * 4); \ \ MemRandomize(orig_pixels, kPixels * 4); \ MemRandomize(orig_y, kPixels); \ MemRandomize(orig_u, kHalfPixels); \ MemRandomize(orig_v, kHalfPixels); \ MemRandomize(temp_y, kPixels); \ MemRandomize(temp_u, kHalfPixels); \ MemRandomize(temp_v, kHalfPixels); \ MemRandomize(dst_pixels_opt, kPixels * 4); \ MemRandomize(dst_pixels_c, kPixels * 4); \ \ /* The test is overall for color conversion matrix being reversible, so */ \ /* this initializes the pixel with 2x2 blocks to eliminate subsampling. */ \ uint8* p = orig_y; \ for (int y = 0; y < benchmark_height_ - HS1; y += HS) { \ for (int x = 0; x < benchmark_width_ - 1; x += 2) { \ uint8 r = static_cast<uint8>(random()); \ p[0] = r; \ p[1] = r; \ p[HN] = r; \ p[HN + 1] = r; \ p += 2; \ } \ p += HN; \ } \ \ /* Start with YUV converted to ARGB. */ \ YUVTOARGB(orig_y, benchmark_width_, \ orig_u, (benchmark_width_ + 1) / 2, \ orig_v, (benchmark_width_ + 1) / 2, \ orig_pixels, benchmark_width_ * 4, \ benchmark_width_, benchmark_height_); \ \ ARGBTOYUV(orig_pixels, benchmark_width_ * 4, \ temp_y, benchmark_width_, \ temp_u, (benchmark_width_ + 1) / 2, \ temp_v, (benchmark_width_ + 1) / 2, \ benchmark_width_, benchmark_height_); \ \ MaskCpuFlags(0); \ YUVTOARGB(temp_y, benchmark_width_, \ temp_u, (benchmark_width_ + 1) / 2, \ temp_v, (benchmark_width_ + 1) / 2, \ dst_pixels_c, benchmark_width_ * 4, \ benchmark_width_, benchmark_height_); \ MaskCpuFlags(-1); \ \ for (int i = 0; i < benchmark_iterations_; ++i) { \ YUVTOARGB(temp_y, benchmark_width_, \ temp_u, (benchmark_width_ + 1) / 2, \ temp_v, (benchmark_width_ + 1) / 2, \ dst_pixels_opt, benchmark_width_ * 4, \ benchmark_width_, benchmark_height_); \ } \ /* Test C and SIMD match. */ \ for (int i = 0; i < kPixels * 4; ++i) { \ EXPECT_EQ(dst_pixels_c[i], dst_pixels_opt[i]); \ } \ /* Test SIMD is close to original. */ \ for (int i = 0; i < kPixels * 4; ++i) { \ EXPECT_NEAR(static_cast<int>(orig_pixels[i]), \ static_cast<int>(dst_pixels_opt[i]), DIFF); \ } \ \ free_aligned_buffer_64(orig_pixels); \ free_aligned_buffer_64(orig_y); \ free_aligned_buffer_64(orig_u); \ free_aligned_buffer_64(orig_v); \ free_aligned_buffer_64(temp_y); \ free_aligned_buffer_64(temp_u); \ free_aligned_buffer_64(temp_v); \ free_aligned_buffer_64(dst_pixels_opt); \ free_aligned_buffer_64(dst_pixels_c); \ } \ TESTCS(TestI420, I420ToARGB, ARGBToI420, 1, 2, benchmark_width_, 7) TESTCS(TestI422, I422ToARGB, ARGBToI422, 0, 1, 0, 7) TESTCS(TestJ420, J420ToARGB, ARGBToJ420, 1, 2, benchmark_width_, 3) TESTCS(TestJ422, J422ToARGB, ARGBToJ422, 0, 1, 0, 3) int Clamp(double f) { int i = static_cast<int>(round(f)); if (i < 0) { i = 0; } if (i > 255) { i = 255; } return i; } void TestYUVToRGBReference(int y, int u, int v, int &r, int &g, int &b) { r = Clamp((y - 16) * 1.164 + (v - 128) * 1.596); g = Clamp((y - 16) * 1.164 + (u - 128) * -0.391 + (v - 128) * -0.813); b = Clamp((y - 16) * 1.164 + (u - 128) * 2.018); } void TestYUVToRGB(int y, int u, int v, int &r, int &g, int &b, int benchmark_width_, int benchmark_height_) { const int kPixels = benchmark_width_ * benchmark_height_; const int kHalfPixels = ((benchmark_width_ + 1) / 2) * ((benchmark_height_ + 1) / 2); align_buffer_64(orig_y, kPixels); align_buffer_64(orig_u, kHalfPixels); align_buffer_64(orig_v, kHalfPixels); align_buffer_64(orig_pixels, kPixels * 4); memset(orig_y, y, kPixels); memset(orig_u, u, kHalfPixels); memset(orig_v, v, kHalfPixels); MemRandomize(orig_pixels, kPixels * 4); /* YUV converted to ARGB. */ I420ToARGB(orig_y, benchmark_width_, orig_u, (benchmark_width_ + 1) / 2, orig_v, (benchmark_width_ + 1) / 2, orig_pixels, benchmark_width_ * 4, benchmark_width_, benchmark_height_); b = orig_pixels[0]; g = orig_pixels[1]; r = orig_pixels[2]; free_aligned_buffer_64(orig_pixels); free_aligned_buffer_64(orig_y); free_aligned_buffer_64(orig_u); free_aligned_buffer_64(orig_v); } TEST_F(libyuvTest, TestYUV) { int r0, g0, b0; TestYUVToRGBReference(16, 128, 128, r0, g0, b0); EXPECT_EQ(0, r0); EXPECT_EQ(0, g0); EXPECT_EQ(0, b0); int r1, g1, b1; TestYUVToRGB(16, 128, 128, r1, g1, b1, benchmark_width_, benchmark_height_); EXPECT_EQ(0, r1); EXPECT_EQ(0, g1); EXPECT_EQ(0, b1); TestYUVToRGBReference(240, 128, 128, r0, g0, b0); EXPECT_EQ(255, r0); EXPECT_EQ(255, g0); EXPECT_EQ(255, b0); TestYUVToRGB(240, 128, 128, r1, g1, b1, benchmark_width_, benchmark_height_); EXPECT_EQ(255, r1); EXPECT_EQ(254, g1); EXPECT_EQ(255, b1); } } // namespace libyuv
Test color space against a reference function. BUG=none TESTED=TestYUV [email protected]
Test color space against a reference function. BUG=none TESTED=TestYUV [email protected] Review URL: https://webrtc-codereview.appspot.com/35789004 git-svn-id: a51711482b6ba0e1d1ab095578a045eeae45ac9a@1229 16f28f9a-4ce2-e073-06de-1de4eb20be90
C++
bsd-3-clause
rig-project/libyuv,archos-sa/libyuv-avp,granalberto/libyuv,archos-sa/libyuv-avp,granalberto/libyuv,archos-sa/libyuv-avp,granalberto/libyuv,rig-project/libyuv,granalberto/libyuv,rig-project/libyuv
2317481852cb5c1003f79677ac189bb32c0c2c44
application_sandbox/pipeline_executable_properties/main.cpp
application_sandbox/pipeline_executable_properties/main.cpp
// Copyright 2019 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "application_sandbox/sample_application_framework/sample_application.h" #include "support/entry/entry.h" #include "vulkan_helpers/buffer_frame_data.h" #include "vulkan_helpers/vulkan_application.h" #include "vulkan_helpers/vulkan_model.h" namespace cube_model { #include "cube.obj.h" } const auto& cube_data = cube_model::model; uint32_t cube_vertex_shader[] = #include "cube.vert.spv" ; uint32_t cube_fragment_shader[] = #include "cube.frag.spv" ; int main_entry(const entry::EntryData* data) { logging::Logger* log = data->logger(); log->LogInfo("Application Startup"); VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pipeline_executable_info_features{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR, nullptr, true}; vulkan::VulkanApplication app( data->allocator(), data->logger(), data, {}, {VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME}, {0}, 1024 * 128, 1024 * 128, 1024 * 128, 1024 * 128, false, false, false, 0, false, &pipeline_executable_info_features); vulkan::VkDevice& device = app.device(); vulkan::VulkanModel cube(data->allocator(), data->logger(), cube_data); VkDescriptorSetLayoutBinding cube_descriptor_set_layouts_[2] = { { 0, // binding VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType 1, // descriptorCount VK_SHADER_STAGE_VERTEX_BIT, // stageFlags nullptr // pImmutableSamplers }, { 1, // binding VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType 1, // descriptorCount VK_SHADER_STAGE_VERTEX_BIT, // stageFlags nullptr // pImmutableSamplers }}; containers::unique_ptr<vulkan::PipelineLayout> pipeline_layout = containers::make_unique<vulkan::PipelineLayout>( data->allocator(), app.CreatePipelineLayout({{cube_descriptor_set_layouts_[0], cube_descriptor_set_layouts_[1]}})); VkAttachmentReference color_attachment = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; uint32_t image_resolution = 1024; VkSampleCountFlagBits num_samples = VK_SAMPLE_COUNT_1_BIT; VkViewport viewport = {0.0f, 0.0f, static_cast<float>(image_resolution), static_cast<float>(image_resolution), 0.0f, 1.0f}; VkRect2D scissor = {{0, 0}, {image_resolution, image_resolution}}; containers::unique_ptr<vulkan::VkRenderPass> render_pass = containers::make_unique<vulkan::VkRenderPass>( data->allocator(), app.CreateRenderPass( {{ 0, // flags app.swapchain().format(), // format num_samples, // samples VK_ATTACHMENT_LOAD_OP_CLEAR, // loadOp VK_ATTACHMENT_STORE_OP_STORE, // storeOp VK_ATTACHMENT_LOAD_OP_DONT_CARE, // stenilLoadOp VK_ATTACHMENT_STORE_OP_DONT_CARE, // stenilStoreOp VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // initialLayout VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // finalLayout }}, // AttachmentDescriptions {{ 0, // flags VK_PIPELINE_BIND_POINT_GRAPHICS, // pipelineBindPoint 0, // inputAttachmentCount nullptr, // pInputAttachments 1, // colorAttachmentCount &color_attachment, // colorAttachment nullptr, // pResolveAttachments nullptr, // pDepthStencilAttachment 0, // preserveAttachmentCount nullptr // pPreserveAttachments }}, // SubpassDescriptions {} // SubpassDependencies )); containers::unique_ptr<vulkan::VulkanGraphicsPipeline> cube_pipeline = containers::make_unique<vulkan::VulkanGraphicsPipeline>( data->allocator(), app.CreateGraphicsPipeline(pipeline_layout.get(), render_pass.get(), 0)); cube_pipeline->AddShader(VK_SHADER_STAGE_VERTEX_BIT, "main", cube_vertex_shader); cube_pipeline->AddShader(VK_SHADER_STAGE_FRAGMENT_BIT, "main", cube_fragment_shader); cube_pipeline->SetTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST); cube_pipeline->SetInputStreams(&cube); cube_pipeline->SetViewport(viewport); cube_pipeline->SetScissor(scissor); cube_pipeline->SetSamples(num_samples); cube_pipeline->AddAttachment(); cube_pipeline->flags() = VK_PIPELINE_CREATE_CAPTURE_STATISTICS_BIT_KHR | VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR; cube_pipeline->Commit(); VkPipelineInfoKHR pipeline_info{VK_STRUCTURE_TYPE_PIPELINE_INFO_KHR, nullptr, *cube_pipeline}; uint32_t executable_count; device->vkGetPipelineExecutablePropertiesKHR(device, &pipeline_info, &executable_count, nullptr); containers::vector<VkPipelineExecutablePropertiesKHR> executable_properties( executable_count, {VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_PROPERTIES_KHR, nullptr}, data->allocator()); device->vkGetPipelineExecutablePropertiesKHR( device, &pipeline_info, &executable_count, executable_properties.data()); for (uint32_t i = 0; i < executable_count; i++) { VkPipelineExecutableInfoKHR executable_info{ VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_INFO_KHR, nullptr, *cube_pipeline, i}; uint32_t statistic_count; device->vkGetPipelineExecutableStatisticsKHR(device, &executable_info, &statistic_count, nullptr); containers::vector<VkPipelineExecutableStatisticKHR> statistic( statistic_count, {VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_STATISTIC_KHR, nullptr}, data->allocator()); device->vkGetPipelineExecutableStatisticsKHR( device, &executable_info, &statistic_count, statistic.data()); uint32_t internal_representation_count; device->vkGetPipelineExecutableInternalRepresentationsKHR( device, &executable_info, &internal_representation_count, nullptr); containers::vector<VkPipelineExecutableInternalRepresentationKHR> internal_representation(internal_representation_count, {}, data->allocator()); device->vkGetPipelineExecutableInternalRepresentationsKHR( device, &executable_info, &internal_representation_count, internal_representation.data()); log->LogInfo( "============= Shader executable ==================================="); log->LogInfo("Name : ", executable_properties[i].name); log->LogInfo("Description : ", executable_properties[i].description); log->LogInfo("Subgroup size : ", executable_properties[i].subgroupSize); log->LogInfo( "============= Shader executable statistic ========================="); for (const auto& s : statistic) { log->LogInfo("Name : ", s.name); log->LogInfo("Description : ", s.description); switch (s.format) { case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_BOOL32_KHR: log->LogInfo("Value : ", s.value.b32); break; case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_INT64_KHR: log->LogInfo("Value : ", s.value.i64); break; case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR: log->LogInfo("Value : ", s.value.u64); break; case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_FLOAT64_KHR: log->LogInfo("Value : ", s.value.f64); break; default: LOG_CRASH(log, "Unexpected format"); } log->LogInfo(""); } log->LogInfo( "============= Shader executable internal representation ==========="); for (const auto& ir : internal_representation) { log->LogInfo("Name : ", ir.name); log->LogInfo("Description : ", ir.description); if (ir.isText) { log->LogInfo("Text : ", ir.pData); } } } log->LogInfo("Application Shutdown"); return 0; }
// Copyright 2019 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "application_sandbox/sample_application_framework/sample_application.h" #include "support/entry/entry.h" #include "vulkan_helpers/buffer_frame_data.h" #include "vulkan_helpers/vulkan_application.h" #include "vulkan_helpers/vulkan_model.h" namespace cube_model { #include "cube.obj.h" } const auto& cube_data = cube_model::model; uint32_t cube_vertex_shader[] = #include "cube.vert.spv" ; uint32_t cube_fragment_shader[] = #include "cube.frag.spv" ; int main_entry(const entry::EntryData* data) { logging::Logger* log = data->logger(); log->LogInfo("Application Startup"); VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pipeline_executable_info_features{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR, nullptr, true}; vulkan::VulkanApplication app( data->allocator(), data->logger(), data, {}, {VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME}, {0}, 1024 * 128, 1024 * 128, 1024 * 128, 1024 * 128, false, false, false, 0, false, false, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, false, false, nullptr, false, false, &pipeline_executable_info_features); vulkan::VkDevice& device = app.device(); vulkan::VulkanModel cube(data->allocator(), data->logger(), cube_data); VkDescriptorSetLayoutBinding cube_descriptor_set_layouts_[2] = { { 0, // binding VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType 1, // descriptorCount VK_SHADER_STAGE_VERTEX_BIT, // stageFlags nullptr // pImmutableSamplers }, { 1, // binding VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType 1, // descriptorCount VK_SHADER_STAGE_VERTEX_BIT, // stageFlags nullptr // pImmutableSamplers }}; containers::unique_ptr<vulkan::PipelineLayout> pipeline_layout = containers::make_unique<vulkan::PipelineLayout>( data->allocator(), app.CreatePipelineLayout({{cube_descriptor_set_layouts_[0], cube_descriptor_set_layouts_[1]}})); VkAttachmentReference color_attachment = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; uint32_t image_resolution = 1024; VkSampleCountFlagBits num_samples = VK_SAMPLE_COUNT_1_BIT; VkViewport viewport = {0.0f, 0.0f, static_cast<float>(image_resolution), static_cast<float>(image_resolution), 0.0f, 1.0f}; VkRect2D scissor = {{0, 0}, {image_resolution, image_resolution}}; containers::unique_ptr<vulkan::VkRenderPass> render_pass = containers::make_unique<vulkan::VkRenderPass>( data->allocator(), app.CreateRenderPass( {{ 0, // flags app.swapchain().format(), // format num_samples, // samples VK_ATTACHMENT_LOAD_OP_CLEAR, // loadOp VK_ATTACHMENT_STORE_OP_STORE, // storeOp VK_ATTACHMENT_LOAD_OP_DONT_CARE, // stenilLoadOp VK_ATTACHMENT_STORE_OP_DONT_CARE, // stenilStoreOp VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // initialLayout VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // finalLayout }}, // AttachmentDescriptions {{ 0, // flags VK_PIPELINE_BIND_POINT_GRAPHICS, // pipelineBindPoint 0, // inputAttachmentCount nullptr, // pInputAttachments 1, // colorAttachmentCount &color_attachment, // colorAttachment nullptr, // pResolveAttachments nullptr, // pDepthStencilAttachment 0, // preserveAttachmentCount nullptr // pPreserveAttachments }}, // SubpassDescriptions {} // SubpassDependencies )); containers::unique_ptr<vulkan::VulkanGraphicsPipeline> cube_pipeline = containers::make_unique<vulkan::VulkanGraphicsPipeline>( data->allocator(), app.CreateGraphicsPipeline(pipeline_layout.get(), render_pass.get(), 0)); cube_pipeline->AddShader(VK_SHADER_STAGE_VERTEX_BIT, "main", cube_vertex_shader); cube_pipeline->AddShader(VK_SHADER_STAGE_FRAGMENT_BIT, "main", cube_fragment_shader); cube_pipeline->SetTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST); cube_pipeline->SetInputStreams(&cube); cube_pipeline->SetViewport(viewport); cube_pipeline->SetScissor(scissor); cube_pipeline->SetSamples(num_samples); cube_pipeline->AddAttachment(); cube_pipeline->flags() = VK_PIPELINE_CREATE_CAPTURE_STATISTICS_BIT_KHR | VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR; cube_pipeline->Commit(); VkPipelineInfoKHR pipeline_info{VK_STRUCTURE_TYPE_PIPELINE_INFO_KHR, nullptr, *cube_pipeline}; uint32_t executable_count; device->vkGetPipelineExecutablePropertiesKHR(device, &pipeline_info, &executable_count, nullptr); containers::vector<VkPipelineExecutablePropertiesKHR> executable_properties( executable_count, {VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_PROPERTIES_KHR, nullptr}, data->allocator()); device->vkGetPipelineExecutablePropertiesKHR( device, &pipeline_info, &executable_count, executable_properties.data()); for (uint32_t i = 0; i < executable_count; i++) { VkPipelineExecutableInfoKHR executable_info{ VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_INFO_KHR, nullptr, *cube_pipeline, i}; uint32_t statistic_count; device->vkGetPipelineExecutableStatisticsKHR(device, &executable_info, &statistic_count, nullptr); containers::vector<VkPipelineExecutableStatisticKHR> statistic( statistic_count, {VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_STATISTIC_KHR, nullptr}, data->allocator()); device->vkGetPipelineExecutableStatisticsKHR( device, &executable_info, &statistic_count, statistic.data()); uint32_t internal_representation_count; device->vkGetPipelineExecutableInternalRepresentationsKHR( device, &executable_info, &internal_representation_count, nullptr); containers::vector<VkPipelineExecutableInternalRepresentationKHR> internal_representation(internal_representation_count, {}, data->allocator()); device->vkGetPipelineExecutableInternalRepresentationsKHR( device, &executable_info, &internal_representation_count, internal_representation.data()); log->LogInfo( "============= Shader executable ==================================="); log->LogInfo("Name : ", executable_properties[i].name); log->LogInfo("Description : ", executable_properties[i].description); log->LogInfo("Subgroup size : ", executable_properties[i].subgroupSize); log->LogInfo( "============= Shader executable statistic ========================="); for (const auto& s : statistic) { log->LogInfo("Name : ", s.name); log->LogInfo("Description : ", s.description); switch (s.format) { case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_BOOL32_KHR: log->LogInfo("Value : ", s.value.b32); break; case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_INT64_KHR: log->LogInfo("Value : ", s.value.i64); break; case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR: log->LogInfo("Value : ", s.value.u64); break; case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_FLOAT64_KHR: log->LogInfo("Value : ", s.value.f64); break; default: LOG_CRASH(log, "Unexpected format"); } log->LogInfo(""); } log->LogInfo( "============= Shader executable internal representation ==========="); for (const auto& ir : internal_representation) { log->LogInfo("Name : ", ir.name); log->LogInfo("Description : ", ir.description); if (ir.isText) { log->LogInfo("Text : ", ir.pData); } } } log->LogInfo("Application Shutdown"); return 0; }
Fix build issue with pipeline_executable_properties.
Fix build issue with pipeline_executable_properties.
C++
apache-2.0
google/vulkan_test_applications,google/vulkan_test_applications,google/vulkan_test_applications,google/vulkan_test_applications
92a8b8f7d6e2568d58b810a6535af8f3d0d0d754
user/tools/iporinad.cpp
user/tools/iporinad.cpp
#include <cstdlib> #include <cstring> #include <iostream> #include <fstream> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <fcntl.h> #include <linux/if.h> #include <linux/if_tun.h> using namespace std; /* Arguments taken by the function: * * char *dev: the name of an interface (or '\0'). MUST have enough * space to hold the interface name if '\0' is passed * int flags: interface flags (eg, IFF_TUN, IFF_NO_PI, IFF_TAP etc.) */ static int tun_alloc(char *dev, int flags) { struct ifreq ifr; int fd, err; if ((fd = open("/dev/net/tun", O_RDWR)) < 0) { perror("open(/dev/net/tun)"); return fd; } memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = flags; /* IFF_TUN or IFF_TAP, plus maybe IFF_NO_PI */ if (*dev) { /* If a device name was specified, put it in the structure; otherwise, * the kernel will try to allocate the "next" device of the * specified type */ strncpy(ifr.ifr_name, dev, IFNAMSIZ); } /* Try to create the device */ if ((err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0) { perror("ioctl(TUNSETIFF)"); close(fd); return err; } /* Ff the operation was successful, write back the name of the * interface to the variable "dev", so the caller can know * it. Note that the caller MUST reserve space in *dev (see calling * code below) */ strcpy(dev, ifr.ifr_name); /* this is the special file descriptor that the caller will use to talk * with the virtual interface */ return fd; } void alloc_tun() { char tun_name[IFNAMSIZ]; int tunfd; strcpy(tun_name, "tun1"); tunfd = tun_alloc(tun_name, IFF_TUN | IFF_NO_PI); close(tunfd); } static int parse_conf(const char *path) { ifstream fin(path); if (fin.fail()) { cerr << "Cannot open configuration file " << path << endl; return -1; } fin.close(); return 0; } static void usage(void) { cout << "iporinad [OPTIONS]" << endl << " -h : show this help" << endl << " -c CONF_FILE: path to configuration file" << endl; } int main(int argc, char **argv) { const char *confpath = "/etc/iporinad.conf"; int opt; while ((opt = getopt(argc, argv, "hc:")) != -1) { switch (opt) { case 'h': usage(); return 0; case 'c': confpath = optarg; break; default: printf(" Unrecognized option %c\n", opt); usage(); return -1; } } if (parse_conf(confpath)) { return -1; } return 0; }
#include <cstdlib> #include <cstring> #include <iostream> #include <fstream> #include <string> #include <list> #include <vector> #include <sstream> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <fcntl.h> #include <linux/if.h> #include <linux/if_tun.h> using namespace std; struct IPSubnet { string prefix; unsigned netbits; }; struct Local { string app_name; string dif_name; Local(const string &a, const string &d) : app_name(a), dif_name(d) { } }; struct Remote { string app_name; string dif_name; IPSubnet tun_subnet; Remote(const string &a, const string &d, const IPSubnet &i) : app_name(a), dif_name(d), tun_subnet(i) { } }; struct Route { IPSubnet subnet; }; struct IPoRINA { list<Local> locals; list<Remote> remotes; list<Route> routes; }; /* Arguments taken by the function: * * char *dev: the name of an interface (or '\0'). MUST have enough * space to hold the interface name if '\0' is passed * int flags: interface flags (eg, IFF_TUN, IFF_NO_PI, IFF_TAP etc.) */ static int tun_alloc(char *dev, int flags) { struct ifreq ifr; int fd, err; if ((fd = open("/dev/net/tun", O_RDWR)) < 0) { perror("open(/dev/net/tun)"); return fd; } memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = flags; /* IFF_TUN or IFF_TAP, plus maybe IFF_NO_PI */ if (*dev) { /* If a device name was specified, put it in the structure; otherwise, * the kernel will try to allocate the "next" device of the * specified type */ strncpy(ifr.ifr_name, dev, IFNAMSIZ); } /* Try to create the device */ if ((err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0) { perror("ioctl(TUNSETIFF)"); close(fd); return err; } /* Ff the operation was successful, write back the name of the * interface to the variable "dev", so the caller can know * it. Note that the caller MUST reserve space in *dev (see calling * code below) */ strcpy(dev, ifr.ifr_name); /* this is the special file descriptor that the caller will use to talk * with the virtual interface */ return fd; } void alloc_tun() { char tun_name[IFNAMSIZ]; int tunfd; strcpy(tun_name, "tun1"); tunfd = tun_alloc(tun_name, IFF_TUN | IFF_NO_PI); close(tunfd); } static int parse_conf(const char *path) { ifstream fin(path); if (fin.fail()) { cerr << "Cannot open configuration file " << path << endl; return -1; } for (unsigned int lines_cnt = 1; !fin.eof(); lines_cnt++) { string line; getline(fin, line); istringstream iss(line); vector<string> tokens; string token; while (iss >> token) { tokens.push_back(token); } if (tokens.size() <= 0 || tokens[0][0] == '#') { /* Ignore comments and white spaces. */ continue; } } fin.close(); return 0; } static void usage(void) { cout << "iporinad [OPTIONS]" << endl << " -h : show this help" << endl << " -c CONF_FILE: path to configuration file" << endl; } int main(int argc, char **argv) { const char *confpath = "/etc/iporinad.conf"; int opt; while ((opt = getopt(argc, argv, "hc:")) != -1) { switch (opt) { case 'h': usage(); return 0; case 'c': confpath = optarg; break; default: printf(" Unrecognized option %c\n", opt); usage(); return -1; } } if (parse_conf(confpath)) { return -1; } return 0; }
add definitions for data structures
iporinad: add definitions for data structures
C++
lgpl-2.1
autrimpo/rlite,autrimpo/rlite,vmaffione/rlite,vmaffione/rlite,autrimpo/rlite,vmaffione/rlite,autrimpo/rlite,vmaffione/rlite
97efa262466d1dad84ec4ab14a4c2cac6261c92a
planning/lib/node.hpp
planning/lib/node.hpp
#pragma once #include <string> #include <map> #include <functional> #include <vector> namespace search { class Node { public: using Size = std::size_t; using Path = std::string; using Chidlren = std::vector<Node>; struct Coordinate { Coordinate(Size x, Size y) : x{ x }, y{ y } {} Coordinate& operator = (Coordinate const& other) { x = other.x; y = other.y; return *this; } Size x, y; }; using Functions = std::map< char, std::function< Coordinate(Coordinate) >>; // // ctor // Node(Path const& path) : _path{ path } { } auto path() -> Path const& { return _path; } auto coordinate(Coordinate start) const -> Coordinate { Coordinate c = start; for (auto direction : _path) c = Node::goes.at(direction)(c); return c; } template<typename ValidateFunc> auto children(ValidateFunc validate) const -> Children { Chidlren result; auto curr = coordinate(); for (auto go_from : goes) { auto child = go_from(curr); if (validate(child)) result.push_back(child); } return children; } const static Functions goes; private: Path const _path; }; Node::Functions const Node::goes { { '1', [](Coordinate c) -> Coordinate{ return{ c.x - 1, c.y - 1 }; } }, { '2', [](Coordinate c) -> Coordinate{ return{ c.x - 0, c.y - 1 }; } }, { '3', [](Coordinate c) -> Coordinate{ return{ c.x + 1, c.y + 1 }; } }, { '4', [](Coordinate c) -> Coordinate{ return{ c.x - 1, c.y + 0 }; } }, { '5', [](Coordinate c) -> Coordinate{ return{ c.x + 1, c.y + 0 }; } }, { '6', [](Coordinate c) -> Coordinate{ return{ c.x - 1, c.y - 1 }; } }, { '7', [](Coordinate c) -> Coordinate{ return{ c.x - 0, c.y - 1 }; } }, { '8', [](Coordinate c) -> Coordinate{ return{ c.x + 1, c.y - 1 }; } } }; }
#pragma once #include <string> #include <map> #include <functional> #include <vector> namespace search { class Node { public: using Size = std::size_t; using Path = std::string; using Chidlren = std::vector<Node>; struct Coordinate { Coordinate(Size x, Size y) : x{ x }, y{ y } {} Coordinate& operator = (Coordinate const& other) { x = other.x; y = other.y; return *this; } Size x, y; }; using Functions = std::map< char, std::function< Coordinate(Coordinate) >>; // // ctor // Node(Path const& path) : _path{ path } { } auto path() const -> Path const& { return _path; } auto coordinate(Coordinate start) const -> Coordinate { Coordinate c = start; for (auto direction : _path) c = Node::goes.at(direction)(c); return c; } template<typename ValidateFunc> auto children(ValidateFunc validate) const -> Children { Chidlren result; auto curr = coordinate(); for (auto go_from : goes) { auto child = go_from(curr); if (validate(child)) result.push_back(child); } return children; } const static Functions goes; private: Path const _path; }; Node::Functions const Node::goes { { '1', [](Coordinate c) -> Coordinate{ return{ c.x - 1, c.y - 1 }; } }, { '2', [](Coordinate c) -> Coordinate{ return{ c.x - 0, c.y - 1 }; } }, { '3', [](Coordinate c) -> Coordinate{ return{ c.x + 1, c.y + 1 }; } }, { '4', [](Coordinate c) -> Coordinate{ return{ c.x - 1, c.y + 0 }; } }, { '5', [](Coordinate c) -> Coordinate{ return{ c.x + 1, c.y + 0 }; } }, { '6', [](Coordinate c) -> Coordinate{ return{ c.x - 1, c.y - 1 }; } }, { '7', [](Coordinate c) -> Coordinate{ return{ c.x - 0, c.y - 1 }; } }, { '8', [](Coordinate c) -> Coordinate{ return{ c.x + 1, c.y - 1 }; } } }; }
add const for path()
add const for path()
C++
mit
Mooophy/Path-Planning,Mooophy/Path-Planning
e75d717eec3f3f25d001e52204f7489b2c76431d
chrome/browser/extensions/theme_preview_infobar_delegate.cc
chrome/browser/extensions/theme_preview_infobar_delegate.cc
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/extensions/theme_preview_infobar_delegate.h" #include "app/l10n_util.h" #include "base/string_util.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "grit/generated_resources.h" ThemePreviewInfobarDelegate::ThemePreviewInfobarDelegate( TabContents* tab_contents, const std::string& name) : ConfirmInfoBarDelegate(tab_contents), profile_(tab_contents->profile()), name_(name), selection_made_(false) { } void ThemePreviewInfobarDelegate::InfoBarClosed() { if (!selection_made_) profile_->ClearTheme(); delete this; } std::wstring ThemePreviewInfobarDelegate::GetMessageText() const { return l10n_util::GetStringF(IDS_THEME_PREVIEW_INFOBAR_LABEL, UTF8ToWide(name_)); } SkBitmap* ThemePreviewInfobarDelegate::GetIcon() const { // TODO(aa): Reply with the theme's icon, but this requires reading it // asynchronously from disk. return NULL; } int ThemePreviewInfobarDelegate::GetButtons() const { return BUTTON_OK | BUTTON_CANCEL; } std::wstring ThemePreviewInfobarDelegate::GetButtonLabel( ConfirmInfoBarDelegate::InfoBarButton button) const { switch (button) { case BUTTON_OK: return l10n_util::GetString(IDS_THEME_PREVIEW_INFOBAR_OK_BUTTON); case BUTTON_CANCEL: return l10n_util::GetString(IDS_THEME_PREVIEW_INFOBAR_CANCEL_BUTTON); default: NOTREACHED(); return L""; } } bool ThemePreviewInfobarDelegate::Accept() { selection_made_ = true; return true; } bool ThemePreviewInfobarDelegate::Cancel() { selection_made_ = true; // Blech, this is a total hack. // // a) We should be uninstalling via ExtensionsService, not // Profile::ClearTheme(). // b) We should be able to view the theme without installing it. This would // help in edge cases like the user closing the window or tab before making // a decision. profile_->ClearTheme(); return true; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/theme_preview_infobar_delegate.h" #include "app/l10n_util.h" #include "base/string_util.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "grit/generated_resources.h" ThemePreviewInfobarDelegate::ThemePreviewInfobarDelegate( TabContents* tab_contents, const std::string& name) : ConfirmInfoBarDelegate(tab_contents), profile_(tab_contents->profile()), name_(name), selection_made_(false) { } void ThemePreviewInfobarDelegate::InfoBarClosed() { if (!selection_made_) profile_->ClearTheme(); delete this; } std::wstring ThemePreviewInfobarDelegate::GetMessageText() const { return l10n_util::GetStringF(IDS_THEME_PREVIEW_INFOBAR_LABEL, UTF8ToWide(name_)); } SkBitmap* ThemePreviewInfobarDelegate::GetIcon() const { // TODO(aa): Reply with the theme's icon, but this requires reading it // asynchronously from disk. return NULL; } int ThemePreviewInfobarDelegate::GetButtons() const { return BUTTON_OK | BUTTON_CANCEL; } std::wstring ThemePreviewInfobarDelegate::GetButtonLabel( ConfirmInfoBarDelegate::InfoBarButton button) const { switch (button) { case BUTTON_OK: return l10n_util::GetString(IDS_THEME_PREVIEW_INFOBAR_OK_BUTTON); case BUTTON_CANCEL: return l10n_util::GetString(IDS_THEME_PREVIEW_INFOBAR_CANCEL_BUTTON); default: NOTREACHED(); return L""; } } bool ThemePreviewInfobarDelegate::Accept() { selection_made_ = true; return true; } bool ThemePreviewInfobarDelegate::Cancel() { selection_made_ = true; // Blech, this is a total hack. // // a) We should be uninstalling via ExtensionsService, not // Profile::ClearTheme(). // b) We should be able to view the theme without installing it. This would // help in edge cases like the user closing the window or tab before making // a decision. profile_->ClearTheme(); return true; }
Fix broken tree.
Fix broken tree. git-svn-id: http://src.chromium.org/svn/trunk/src@21624 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 47f959cb504664dc499584e604f27799d14baaed
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
c3ba3d76edbc0ce28f3bf801239d5995e69ddae2
examples/qt/qwt_spectrogram/qwt_spectrogram.cpp
examples/qt/qwt_spectrogram/qwt_spectrogram.cpp
#include "aquila/global.h" #include "aquila/functions.h" #include "aquila/source/generator/SineGenerator.h" #include "aquila/source/FramesCollection.h" #include "aquila/transform/Spectrogram.h" #include <QApplication> #include <QMainWindow> #include <qwt_color_map.h> #include <qwt_plot.h> #include <qwt_plot_spectrogram.h> #include <qwt_raster_data.h> class SpectrogramData : public QwtRasterData { public: SpectrogramData(const Aquila::Spectrogram& spectrogram): m_spectrogram(spectrogram) { setInterval(Qt::XAxis, QwtInterval(0.0, m_spectrogram.getFrameCount())); setInterval(Qt::YAxis, QwtInterval(0.0, m_spectrogram.getSpectrumSize() / 2)); setInterval(Qt::ZAxis, QwtInterval(0.0, 50)); } double value(double x, double y) const { std::size_t frame = Aquila::clamp(0ul, static_cast<std::size_t>(x), m_spectrogram.getFrameCount() - 1ul); std::size_t peak = Aquila::clamp(0ul, static_cast<std::size_t>(y), m_spectrogram.getSpectrumSize() - 1ul); return Aquila::dB(m_spectrogram.getPoint(frame, peak)); } private: const Aquila::Spectrogram& m_spectrogram; }; int main(int argc, char *argv[]) { const Aquila::FrequencyType sampleFrequency = 44100; const std::size_t SIZE = sampleFrequency * 2; Aquila::SineGenerator generator(sampleFrequency); generator.setAmplitude(5).setFrequency(1000).generate(SIZE); Aquila::FramesCollection frames(generator, 1024); Aquila::Spectrogram spectrogram(frames); QApplication a(argc, argv); auto plot = new QwtPlot(); plot->setTitle("Spectrogram"); auto plotSpectrogram = new QwtPlotSpectrogram(); QwtLinearColorMap colorMap(Qt::black, Qt::red); colorMap.addColorStop(0.3, Qt::darkBlue); colorMap.addColorStop(0.4, Qt::blue); colorMap.addColorStop(0.65, Qt::green); colorMap.addColorStop(0.85, Qt::yellow); plotSpectrogram->setColorMap(&colorMap); auto data = new SpectrogramData(spectrogram); plotSpectrogram->setData(data); plotSpectrogram->attach(plot); plot->show(); return a.exec(); }
#include "aquila/global.h" #include "aquila/functions.h" #include "aquila/source/WaveFile.h" #include "aquila/source/generator/SineGenerator.h" #include "aquila/source/FramesCollection.h" #include "aquila/transform/Spectrogram.h" #include <QApplication> #include <QMainWindow> #include <qwt_color_map.h> #include <qwt_plot.h> #include <qwt_plot_spectrogram.h> #include <qwt_raster_data.h> class SpectrogramData : public QwtRasterData { public: SpectrogramData(const Aquila::Spectrogram& spectrogram): m_spectrogram(spectrogram) { setInterval(Qt::XAxis, QwtInterval(0.0, m_spectrogram.getFrameCount())); setInterval(Qt::YAxis, QwtInterval(0.0, m_spectrogram.getSpectrumSize() / 2)); setInterval(Qt::ZAxis, QwtInterval(0.0, 50)); } double value(double x, double y) const { std::size_t frame = Aquila::clamp(0ul, static_cast<std::size_t>(x), m_spectrogram.getFrameCount() - 1ul); std::size_t peak = Aquila::clamp(0ul, static_cast<std::size_t>(y), m_spectrogram.getSpectrumSize() - 1ul); return Aquila::dB(m_spectrogram.getPoint(frame, peak)); } private: const Aquila::Spectrogram& m_spectrogram; }; int main(int argc, char *argv[]) { const Aquila::FrequencyType sampleFrequency = 44100; const std::size_t SIZE = sampleFrequency * 2; Aquila::SignalSource* source = nullptr; if (argc >= 2) { source = new Aquila::WaveFile(argv[1]); } else { auto generator = new Aquila::SineGenerator(sampleFrequency); generator->setAmplitude(5).setFrequency(1000).generate(SIZE); source = generator; } Aquila::FramesCollection frames(*source, 1024); Aquila::Spectrogram spectrogram(frames); QApplication a(argc, argv); auto plot = new QwtPlot(); plot->setTitle("Spectrogram"); auto plotSpectrogram = new QwtPlotSpectrogram(); QwtLinearColorMap colorMap(Qt::black, Qt::red); colorMap.addColorStop(0.3, Qt::darkBlue); colorMap.addColorStop(0.4, Qt::blue); colorMap.addColorStop(0.65, Qt::green); colorMap.addColorStop(0.85, Qt::yellow); plotSpectrogram->setColorMap(&colorMap); auto data = new SpectrogramData(spectrogram); plotSpectrogram->setData(data); plotSpectrogram->attach(plot); plot->show(); return a.exec(); }
Allow for arbitrary input from .wav file.
Allow for arbitrary input from .wav file.
C++
apache-2.0
sav6622/aquila,synkarae/aquila,sav6622/aquila,synkarae/aquila,synkarae/Quasar,tempbottle/aquila,sav6622/aquila,zsiciarz/aquila,zsiciarz/aquila,zsiciarz/aquila,tempbottle/aquila,Aldor007/aquila,Aldor007/aquila,synkarae/aquila,synkarae/Quasar,zsiciarz/aquila,tempbottle/aquila,synkarae/Quasar,Aldor007/aquila
649784214d93cc3fcb13df3c42ce255e61d2adee
widgets/PHNTextBox.cpp
widgets/PHNTextBox.cpp
#include "PHNTextBox.h" PHN_TextBox::PHN_TextBox() { this->length = 0; this->selStart = 0; this->selLength = 0; this->selEnd = 0; this->invalidateStart = -1; this->invalidateEnd = -1; this->cursor_x = -1; this->cursor_y = -1; this->scrollOffset = 0; this->scrollVisible = true; this->dragStart = -1; this->setTextSize(2); this->setMaxLength(100); } void PHN_TextBox::setDimension(int rows, int columns) { // Use the known column/row/scrollbar states to calculate the bounds if (rows > 1) { // Multiple rows - vertical scrollbar setSize(columns*chr_w+chr_w+4, rows*chr_h+2); } else { // Only a single row setSize((columns*chr_w)+chr_h+6, chr_h+2); } } void PHN_TextBox::setMaxLength(int length) { if (length < this->length) { this->length = length; } textBuff.resize(length + 1); } void PHN_TextBox::setTextSize(int size) { _textSize = size; chr_w = _textSize * 6; chr_h = _textSize * 8; invalidate(); } void PHN_TextBox::setScrollbarVisible(bool visible) { // Update the scroll visible property - invalidate to refresh scrollVisible = visible; invalidate(); } void PHN_TextBox::setTextRaw(const char* text, int textLen) { length = min(textBuff.dataSize-1, textLen); memcpy(textBuff.data, text, sizeof(char) * length); textBuff.text()[length] = 0; updateScrollLimit(); setSelectionRange(length, 0); invalidate(); } bool PHN_TextBox::ensureVisible(int charPosition) { int col = 0; int row = -scrollOffset; char* text = (char*) textBuff.data; for (int i = 0; i <= length; i++) { if (text[i] == '\r') continue; if (text[i] == '\n' || col >= cols) { row++; col = 0; } if (i == charPosition) { break; } if (text[i] != '\n') col++; } // Not found, scroll to it int newScroll = scrollOffset; if (row >= rows) { // Scroll down the required amount of rows newScroll = scrollOffset + row - rows + 1; } else if (row < 0) { // Scroll up the required amount of rows newScroll = scrollOffset + row; } scroll.setValue(newScroll); return newScroll != scrollOffset; } void PHN_TextBox::updateScrollLimit() { int row = 0; int col = 0; char* text = (char*) textBuff.data; for (int i = 0; i <= length; i++) { if (text[i] == '\r') continue; if (text[i] == '\n' || col >= cols) { row++; col = 0; } if (text[i] != '\n') col++; } // Update scroll maximum based on the amount of rows int scrollMax = row - rows + 1; if (col == cols) scrollMax++; scroll.setRange(max(0, scrollMax), 0); } void PHN_TextBox::setSelectionRange(int position, int length) { if (position == selStart && length == selLength) { return; } int end = position + length; // Perform character invalidation (redrawing) if (!selLength && !length) { // When only the cursor changes, only redraw the cursor // This is done by re-drawing past the text length limit invalidate(this->length); } else if (length && !selLength) { // No previous selection to a selection invalidate(position, position+length); } else if (!length && selLength) { // Previous selection to no selection invalidate(selStart, selEnd); } else { // Undo edges in previous selection if (position > selStart) invalidate(selStart, position); if (end < selEnd) invalidate(end, selEnd); // Add changes of the new selection if (position > selEnd) invalidate(position, end); if (position < selStart) invalidate(position, selStart); if (end > selEnd) invalidate(selEnd, end); } // Update selection information selStart = position; selLength = length; selEnd = end; } void PHN_TextBox::setSelection(char character) { const char seltext[] = {character, 0}; setSelection(seltext); } void PHN_TextBox::backspace() { if (selLength) { const char seltext[] = {0}; setSelection(seltext); } else if (selStart) { // Shift ending one to the left char* text = (char*) textBuff.data; memmove(text+selStart-1, text+selStart, length-selStart); length -= 1; text[length] = 0; updateScrollLimit(); setSelectionRange(selStart-1, 0); invalidate(selStart); } } void PHN_TextBox::setSelection(const char* selectionText) { // Handle backspace characters here while (*selectionText == '\b') { backspace(); selectionText++; } // Now enter the actual text int len = min((int) strlen(selectionText), (int) (textBuff.dataSize-length+selLength)); char* text = (char*) textBuff.data; bool appended = (selLength == 0 && selStart == length); // If nothing is set, do nothing if (!len) return; // Shift everything after the selection to the right memmove(text+selStart+len, text+selEnd, length-selEnd); // Insert the text value memcpy(text+selStart, selectionText, len); // Update length length = length - selLength + len; text[length] = 0; updateScrollLimit(); // Invalidate the changed area if (len == selLength) { invalidate(selStart, selEnd); } else { invalidate(selStart); } // Update the start and length of selection setSelectionRange(selStart+len, 0); ensureVisible(selStart); // If text was appended (cursor at the end), use faster redraw invalidateAppended = appended; } void PHN_TextBox::invalidate(int startPosition) { invalidate(startPosition, length); } void PHN_TextBox::invalidate(int startPosition, int endPosition) { invalidateAppended = false; if (invalidateStart == -1 || invalidateStart > startPosition) invalidateStart = startPosition; if (invalidateEnd == -1 || invalidateEnd < endPosition) invalidateEnd = endPosition; } void PHN_TextBox::update() { // Update scrollbar layout changes if (invalidated) { // Remove scrollbar up-front removeWidget(scroll); // Update row count rows = (height-2) / chr_h; // Update width and column count, applying this to the scrollbar int scrollWidth; if (scrollVisible) { if (rows > 1) { scrollWidth = chr_h+2; } else { scrollWidth = height*2+2; } addWidget(scroll); } else { scrollWidth = 0; } textAreaWidth = (width - scrollWidth); cols = (textAreaWidth-2) / chr_w; scroll.setBounds(x+textAreaWidth, y, scrollWidth, height); } // Handle Touch selection changes char* text = (char*) textBuff.data; if (display.isTouched(x+_textSize+1, y+_textSize+1, cols*chr_w, rows*chr_h)) { PressPoint pos = display.getTouch(); int posRow = (pos.y-(this->y+_textSize+1)) / chr_h; // Go by all characters until found int x; int col = 0; int row = -scrollOffset; int pressedIdx = this->length; for (int i = 0; i <= length; i++) { if (text[i] == '\r') continue; if (col >= cols) { row++; col = 0; } if (row == posRow) { x = this->x + _textSize + 1 + col * chr_w; if ((text[i] == '\n') || (pos.x <= x+(chr_w>>1))) { pressedIdx = i; break; } else if (col == (cols-1)) { pressedIdx = i+1; break; } } if (text[i] == '\n') { row++; col = 0; } else { col++; } } if (display.isTouchDown()) { // Drag start dragStart = pressedIdx; setSelectionRange(pressedIdx, 0); dragLastClick = millis(); } else if (dragStart != -1 && (millis() - dragLastClick) > PHN_WIDGET_TEXT_DRAGSELDELAY) { // Drag selection int start = min(dragStart, pressedIdx); int end = max(dragStart, pressedIdx); setSelectionRange(start, max(1, end-start)); } else if (dragStart != pressedIdx) { // Repositioned the character dragStart = pressedIdx; setSelectionRange(pressedIdx, 0); dragLastClick = millis(); } ensureVisible(pressedIdx); } else if (!display.isTouched()) { dragStart = -1; } // Update scrolling if (scrollOffset != scroll.value()) { scrollOffset = scroll.value(); invalidate(); } // Partial redraws if (!invalidated) { if (invalidateStart != -1) { // Redraw parts of changed text drawTextFromTo(invalidateStart, invalidateEnd, !invalidateAppended); } else if ((millis() - cursor_blinkLast) >= PHN_WIDGET_TEXT_BLINKINTERVAL) { // Blink the cursor cursor_blinkLast = millis(); drawCursor(!cursor_blinkVisible); } } invalidateStart = -1; invalidateEnd = -1; invalidateAppended = false; } void PHN_TextBox::draw() { // Draw background color and grid display.fillRect(x+1, y+1, textAreaWidth-2, height-2, color(FOREGROUND)); display.drawRect(x, y, textAreaWidth, height, color(FRAME)); // Draw text drawTextFromTo(0, this->length, false); } void PHN_TextBox::drawCursor(bool visible) { cursor_blinkVisible = visible; if (cursor_x != -1 && cursor_y != -1) { color_t clr = cursor_blinkVisible ? color(CONTENT) : color(FOREGROUND); display.fillRect(cursor_x, cursor_y, _textSize, _textSize*8, clr); } } void PHN_TextBox::drawTextFromTo(int charStart, int charEnd, bool drawBackground) { // Reset cursor blinking to draw next update cursor_blinkLast = millis() - PHN_WIDGET_TEXT_BLINKINTERVAL; // When all empty, just wipe the screen and reset if (!length) { scroll.setRange(0, 0); display.fillRect(x+1, y+1, textAreaWidth-1, height-2, color(FOREGROUND)); cursor_x = x+_textSize+1; cursor_y = y+_textSize+1; selStart = 0; selLength = 0; return; } // First hide cursor to prevent glitches if (cursor_blinkVisible) { drawCursor(false); } Viewport old = display.getViewport(); display.setViewport(x+_textSize+1, y+_textSize+1, width, height); display.setTextColor(color(CONTENT), color(FOREGROUND)); // Draw selection highlight, cursor and text int row = -scrollOffset; int col = 0; int x, y; bool bgDrawn = false; bool charSel; cursor_x = -1; cursor_y = -1; char* text = (char*) textBuff.data; for (int i = 0; i <= length; i++) { if (text[i] == '\r') continue; if (col >= cols) { row++; col = 0; } if (row >= 0 && row < rows) { x = col * chr_w; y = row * chr_h; if (i == selStart && !selLength) { // Set up cursor cursor_x = display.getViewport().x + x + 1 - _textSize - (_textSize>>1); cursor_y = display.getViewport().y + y; } // Only do drawing operations in the selected range if (i >= charStart && i <= charEnd) { charSel = i >= selStart && i < (selStart+selLength); // Fill the current row and all rows below with background color if (drawBackground) { if (charEnd < length) { // End selection exists, draw a background rectangle one at a time if (!charSel) display.fillRect(x - 1, y, chr_w+1, chr_h, color(FOREGROUND)); } else if (!bgDrawn) { bgDrawn = true; if (col == 0) { display.fillRect(-1, y, cols*chr_w, chr_h*(rows-row)+1, color(FOREGROUND)); } else { display.fillRect(x-1, y, (cols-col)*chr_w+1, chr_h, color(FOREGROUND)); display.fillRect(-1, y+chr_h, cols*chr_w+1, chr_h*(rows-row-1), color(FOREGROUND)); } } } // Only do drawing when not a newline if (text[i] != '\n' && text[i]) { // Draw highlight box if (charSel) display.fillRect(x - 1, y, chr_w+1, chr_h, color(HIGHLIGHT)); // Draw text display.drawChar(x, y, text[i], _textSize); } } } if (text[i] == '\n') { row++; col = 0; } else { col++; } } // Update scroll maximum based on the amount of rows int scrollMax = row - rows + scrollOffset + 1; if (col == cols) scrollMax++; scroll.setRange(max(0, scrollMax), 0); // Restore viewport display.setViewport(old); }
#include "PHNTextBox.h" PHN_TextBox::PHN_TextBox() { this->length = 0; this->selStart = 0; this->selLength = 0; this->selEnd = 0; this->invalidateStart = -1; this->invalidateEnd = -1; this->cursor_x = -1; this->cursor_y = -1; this->scrollOffset = 0; this->scrollVisible = true; this->dragStart = -1; this->setTextSize(2); this->setMaxLength(100); } void PHN_TextBox::setDimension(int rows, int columns) { // Use the known column/row/scrollbar states to calculate the bounds if (rows > 1) { // Multiple rows - vertical scrollbar setSize(columns*chr_w+chr_w+4, rows*chr_h+2); } else { // Only a single row setSize((columns*chr_w)+chr_h+6, chr_h+2); } } void PHN_TextBox::setMaxLength(int length) { if (length < this->length) { this->length = length; } textBuff.resize(length + 1); } void PHN_TextBox::setTextSize(int size) { _textSize = size; chr_w = _textSize * 6; chr_h = _textSize * 8; invalidate(); } void PHN_TextBox::setScrollbarVisible(bool visible) { // Update the scroll visible property - invalidate to refresh scrollVisible = visible; invalidate(); } void PHN_TextBox::setTextRaw(const char* text, int textLen) { length = min(textBuff.dataSize-1, textLen); memcpy(textBuff.data, text, sizeof(char) * length); textBuff.text()[length] = 0; updateScrollLimit(); setSelectionRange(length, 0); invalidate(); } bool PHN_TextBox::ensureVisible(int charPosition) { int col = 0; int row = -scrollOffset; char* text = (char*) textBuff.data; for (int i = 0; i <= length; i++) { if (text[i] == '\r') continue; if (text[i] == '\n' || col >= cols) { row++; col = 0; } if (i == charPosition) { break; } if (text[i] != '\n') col++; } // Not found, scroll to it int newScroll = scrollOffset; if (row >= rows) { // Scroll down the required amount of rows newScroll = scrollOffset + row - rows + 1; } else if (row < 0) { // Scroll up the required amount of rows newScroll = scrollOffset + row; } scroll.setValue(newScroll); return newScroll != scrollOffset; } void PHN_TextBox::updateScrollLimit() { int row = 0; int col = 0; char* text = (char*) textBuff.data; for (int i = 0; i <= length; i++) { if (text[i] == '\r') continue; if (text[i] == '\n' || col >= cols) { row++; col = 0; } if (text[i] != '\n') col++; } // Update scroll maximum based on the amount of rows int scrollMax = row - rows + 1; if (col == cols) scrollMax++; scroll.setRange(max(0, scrollMax), 0); } void PHN_TextBox::setSelectionRange(int position, int length) { // Protection against selection past the limit if (position >= this->length) { position = this->length; length = 0; } // If unchanged, do nothing if (position == selStart && length == selLength) { return; } int end = position + length; // Perform character invalidation (redrawing) if (!selLength && !length) { // When only the cursor changes, only redraw the cursor // This is done by re-drawing past the text length limit invalidate(this->length); } else if (length && !selLength) { // No previous selection to a selection invalidate(position, position+length); } else if (!length && selLength) { // Previous selection to no selection invalidate(selStart, selEnd); } else { // Undo edges in previous selection if (position > selStart) invalidate(selStart, position); if (end < selEnd) invalidate(end, selEnd); // Add changes of the new selection if (position > selEnd) invalidate(position, end); if (position < selStart) invalidate(position, selStart); if (end > selEnd) invalidate(selEnd, end); } // Update selection information selStart = position; selLength = length; selEnd = end; } void PHN_TextBox::setSelection(char character) { const char seltext[] = {character, 0}; setSelection(seltext); } void PHN_TextBox::backspace() { if (selLength) { const char seltext[] = {0}; setSelection(seltext); } else if (selStart) { // Shift ending one to the left char* text = (char*) textBuff.data; memmove(text+selStart-1, text+selStart, length-selStart); length -= 1; text[length] = 0; updateScrollLimit(); setSelectionRange(selStart-1, 0); invalidate(selStart); } } void PHN_TextBox::setSelection(const char* selectionText) { // Handle backspace characters here while (*selectionText == '\b') { backspace(); selectionText++; } // Now enter the actual text int len = min((int) strlen(selectionText), (int) (textBuff.dataSize-length+selLength)); char* text = textBuff.text(); bool appended = (selLength == 0 && selStart == length); // If nothing is set, do nothing if (!len && (selLength == 0)) return; // Shift everything after the selection to the right memmove(text+selStart+len, text+selEnd, length-selEnd); // Insert the text value memcpy(text+selStart, selectionText, len); // Update length length = length - selLength + len; text[length] = 0; updateScrollLimit(); // Invalidate the changed area if (len == selLength) { invalidate(selStart, selEnd); } else { invalidate(selStart); } // Update the start and length of selection setSelectionRange(selStart+len, 0); ensureVisible(selStart); // If text was appended (cursor at the end), use faster redraw invalidateAppended = appended; } void PHN_TextBox::invalidate(int startPosition) { invalidate(startPosition, length); } void PHN_TextBox::invalidate(int startPosition, int endPosition) { invalidateAppended = false; if (invalidateStart == -1 || invalidateStart > startPosition) invalidateStart = startPosition; if (invalidateEnd == -1 || invalidateEnd < endPosition) invalidateEnd = endPosition; } void PHN_TextBox::update() { // Update scrollbar layout changes if (invalidated) { // Remove scrollbar up-front removeWidget(scroll); // Update row count rows = (height-2) / chr_h; // Update width and column count, applying this to the scrollbar int scrollWidth; if (scrollVisible) { if (rows > 1) { scrollWidth = chr_h+2; } else { scrollWidth = height*2+2; } addWidget(scroll); } else { scrollWidth = 0; } textAreaWidth = (width - scrollWidth); cols = (textAreaWidth-2) / chr_w; scroll.setBounds(x+textAreaWidth, y, scrollWidth, height); } // Handle Touch selection changes char* text = (char*) textBuff.data; if (display.isTouched(x+_textSize+1, y+_textSize+1, cols*chr_w, rows*chr_h)) { PressPoint pos = display.getTouch(); int posRow = (pos.y-(this->y+_textSize+1)) / chr_h; // Go by all characters until found int x; int col = 0; int row = -scrollOffset; int pressedIdx = this->length; for (int i = 0; i <= length; i++) { if (text[i] == '\r') continue; if (col >= cols) { row++; col = 0; } if (row == posRow) { x = this->x + _textSize + 1 + col * chr_w; if ((text[i] == '\n') || (pos.x <= x+(chr_w>>1))) { pressedIdx = i; break; } else if (col == (cols-1)) { pressedIdx = i+1; break; } } if (text[i] == '\n') { row++; col = 0; } else { col++; } } if (display.isTouchDown()) { // Drag start dragStart = pressedIdx; setSelectionRange(pressedIdx, 0); dragLastClick = millis(); } else if (dragStart != -1 && (millis() - dragLastClick) > PHN_WIDGET_TEXT_DRAGSELDELAY) { // Drag selection int start = min(dragStart, pressedIdx); int end = max(dragStart, pressedIdx); setSelectionRange(start, max(1, end-start)); } else if (dragStart != pressedIdx) { // Repositioned the character dragStart = pressedIdx; setSelectionRange(pressedIdx, 0); dragLastClick = millis(); } ensureVisible(pressedIdx); } else if (!display.isTouched()) { dragStart = -1; } // Update scrolling if (scrollOffset != scroll.value()) { scrollOffset = scroll.value(); invalidate(); } // Partial redraws if (!invalidated) { if (invalidateStart != -1) { // Redraw parts of changed text drawTextFromTo(invalidateStart, invalidateEnd, !invalidateAppended); } else if ((millis() - cursor_blinkLast) >= PHN_WIDGET_TEXT_BLINKINTERVAL) { // Blink the cursor cursor_blinkLast = millis(); drawCursor(!cursor_blinkVisible); } } invalidateStart = -1; invalidateEnd = -1; invalidateAppended = false; } void PHN_TextBox::draw() { // Draw background color and grid display.fillRect(x+1, y+1, textAreaWidth-2, height-2, color(FOREGROUND)); display.drawRect(x, y, textAreaWidth, height, color(FRAME)); // Draw text drawTextFromTo(0, this->length, false); } void PHN_TextBox::drawCursor(bool visible) { cursor_blinkVisible = visible; if (cursor_x != -1 && cursor_y != -1) { color_t clr = cursor_blinkVisible ? color(CONTENT) : color(FOREGROUND); display.fillRect(cursor_x, cursor_y, _textSize, _textSize*8, clr); } } void PHN_TextBox::drawTextFromTo(int charStart, int charEnd, bool drawBackground) { // Reset cursor blinking to draw next update cursor_blinkLast = millis() - PHN_WIDGET_TEXT_BLINKINTERVAL; // When all empty, just wipe the screen and reset if (!length) { scroll.setRange(0, 0); display.fillRect(x+1, y+1, textAreaWidth-1, height-2, color(FOREGROUND)); cursor_x = x+_textSize+1; cursor_y = y+_textSize+1; selStart = 0; selLength = 0; return; } // First hide cursor to prevent glitches if (cursor_blinkVisible) { drawCursor(false); } Viewport old = display.getViewport(); display.setViewport(x+_textSize+1, y+_textSize+1, width, height); // Draw selection highlight, cursor and text int row = -scrollOffset; int col = 0; int x, y; bool charSel; cursor_x = -1; cursor_y = -1; char* text = (char*) textBuff.data; for (int i = 0; i <= length; i++) { if (text[i] == '\r') continue; if (col >= cols) { row++; col = 0; } if (row >= 0 && row < rows) { x = col * chr_w; y = row * chr_h; if (i == selStart && !selLength) { // Set up cursor cursor_x = display.getViewport().x + x + 1 - _textSize - (_textSize>>1); cursor_y = display.getViewport().y + y; } // Only do drawing operations in the selected range if (i >= charStart && i <= charEnd) { charSel = i >= selStart && i < (selStart+selLength); // Fill the current row and all rows below with background color if (drawBackground && charEnd >= length) { // If last character of current line, clear right of character if ((i == length) || (text[i] == '\n')) { display.fillRect(x-1, y, (cols-col)*chr_w+1, chr_h, color(FOREGROUND)); } // If last character of all text, wipe the remaining rows if (i == length) { display.fillRect(-1, y+chr_h, cols*chr_w+1, chr_h*(rows-row-1), color(FOREGROUND)); } } // Only do drawing when not a newline if (text[i] != '\n' && text[i]) { // Update text color based on selection highlight color_t bgColor = color(charSel ? HIGHLIGHT : FOREGROUND); display.setTextColor(color(CONTENT), bgColor); // Draw text with a border for highlight updates int border_s = _textSize>>1; display.drawChar(x, y, text[i], _textSize); display.fillRect(x-border_s, y, border_s, chr_h, bgColor); display.fillRect(x+chr_w-_textSize, y, border_s, chr_h, bgColor); } } } if (text[i] == '\n') { row++; col = 0; } else { col++; } } // Update scroll maximum based on the amount of rows int scrollMax = row - rows + scrollOffset + 1; if (col == cols) scrollMax++; scroll.setRange(max(0, scrollMax), 0); // Restore viewport display.setViewport(old); }
reduce flicker and improve selection
Textbox: reduce flicker and improve selection Wipe-before-draw causes flicker, replaced by a 'smarter' algortihm. As well, fixed a problem where selections past the text length can cause corruptions.
C++
mit
wrh3c/Phoenard,Phoenard/Phoenard,wrh3c/Phoenard,Phoenard/Phoenard
6396e8fba870dbec1dd1f27f68456590e5135ff1
Samples/Isosurf/src/Isosurf.cpp
Samples/Isosurf/src/Isosurf.cpp
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Also see acknowledgements in Readme.html You may use this sample code for anything you like, it is not covered by the same license as the rest of the engine. ----------------------------------------------------------------------------- */ /* ----------------------------------------------------------------------------- Filename: IsoSurf.cpp Description: Demonstrates the use of the geometry shader to tessellate an isosurface using marching tetrahedrons. Partial implementation of cg Isosurf sample from NVIDIA's OpenGL SDK 10 : http://developer.download.nvidia.com/SDK/10/opengl/samples.html ----------------------------------------------------------------------------- */ #include "SdkSample.h" #include "SamplePlugin.h" #include "ProceduralTools.h" using namespace Ogre; using namespace OgreBites; SamplePlugin* sp; Sample* s; class _OgreSampleClassExport Sample_Isosurf : public SdkSample { Entity* tetrahedra; MeshPtr mTetrahedraMesh; public: Sample_Isosurf() { mInfo["Title"] = "Isosurf"; mInfo["Description"] = "A demo of procedural geometry manipulation using geometry shaders."; mInfo["Thumbnail"] = "thumb_isosurf.png"; mInfo["Category"] = "Geometry"; } StringVector getRequiredPlugins() { StringVector names; if (!GpuProgramManager::getSingleton().isSyntaxSupported("glsl150")) names.push_back("Cg Program Manager"); return names; } void testCapabilities(const RenderSystemCapabilities* caps) { if (!caps->hasCapability(RSC_GEOMETRY_PROGRAM)) { OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your render system / hardware does not support geometry programs, " "so you cannot run this sample. Sorry!", "Sample_Isosurf::testCapabilities"); } Ogre::LogManager::getSingleton().getDefaultLog()->stream() << "Num output vertices per geometry shader run : " << caps->getGeometryProgramNumOutputVertices(); } // Just override the mandatory create scene method void setupContent(void) { mCamera->setPosition(0, 0, -40); mCamera->lookAt(0,0,0); mCamera->setNearClipDistance(0.1); mCamera->setFarClipDistance(100); mTetrahedraMesh = ProceduralTools::generateTetrahedra(); //Create tetrahedra and add it to the root scene node tetrahedra = mSceneMgr->createEntity("TetrahedraEntity", mTetrahedraMesh->getName()); //tetraHedra->setDebugDisplayEnabled(true); Ogre::SceneNode* parentNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); parentNode->attachObject(tetrahedra); parentNode->setScale(10,10,10); } void cleanupContent() { MeshManager::getSingleton().remove(mTetrahedraMesh->getName()); } bool frameRenderingQueued(const FrameEvent& evt) { Real seconds = (Real)(Root::getSingleton().getTimer()->getMilliseconds()) / 1000.0; Ogre::Pass* renderPass = tetrahedra->getSubEntity(0)->getMaterial()->getTechnique(0)->getPass(0); if (renderPass->hasVertexProgram()) { Ogre::Vector4 constParam = Ogre::Vector4(-0.5, 0.0, 0.0, 0.2); renderPass->getVertexProgramParameters()->setNamedConstant("Metaballs[0]", constParam); Ogre::Vector4 timeParam = Ogre::Vector4( 0.1 + Ogre::Math::Sin(seconds)*0.5, Ogre::Math::Cos(seconds)*0.5, 0.0, 0.1); renderPass->getVertexProgramParameters()->setNamedConstant("Metaballs[1]", timeParam); } return SdkSample::frameRenderingQueued(evt); } }; #ifndef OGRE_STATIC_LIB extern "C" _OgreSampleExport void dllStartPlugin() { s = new Sample_Isosurf; sp = OGRE_NEW SamplePlugin(s->getInfo()["Title"] + " Sample"); sp->addSample(s); Root::getSingleton().installPlugin(sp); } extern "C" _OgreSampleExport void dllStopPlugin() { Root::getSingleton().uninstallPlugin(sp); OGRE_DELETE sp; delete s; } #endif
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Also see acknowledgements in Readme.html You may use this sample code for anything you like, it is not covered by the same license as the rest of the engine. ----------------------------------------------------------------------------- */ /* ----------------------------------------------------------------------------- Filename: IsoSurf.cpp Description: Demonstrates the use of the geometry shader to tessellate an isosurface using marching tetrahedrons. Partial implementation of cg Isosurf sample from NVIDIA's OpenGL SDK 10 : http://developer.download.nvidia.com/SDK/10/opengl/samples.html ----------------------------------------------------------------------------- */ #include "SdkSample.h" #include "SamplePlugin.h" #include "ProceduralTools.h" using namespace Ogre; using namespace OgreBites; SamplePlugin* sp; Sample* s; class _OgreSampleClassExport Sample_Isosurf : public SdkSample { Entity* tetrahedra; MeshPtr mTetrahedraMesh; public: Sample_Isosurf() { mInfo["Title"] = "Isosurf"; mInfo["Description"] = "A demo of procedural geometry manipulation using geometry shaders."; mInfo["Thumbnail"] = "thumb_isosurf.png"; mInfo["Category"] = "Geometry"; } StringVector getRequiredPlugins() { StringVector names; if(!GpuProgramManager::getSingleton().isSyntaxSupported("glsl150") && !GpuProgramManager::getSingleton().isSyntaxSupported("hlsl")) names.push_back("Cg Program Manager"); return names; } void testCapabilities(const RenderSystemCapabilities* caps) { if (!caps->hasCapability(RSC_GEOMETRY_PROGRAM)) { OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your render system / hardware does not support geometry programs, " "so you cannot run this sample. Sorry!", "Sample_Isosurf::testCapabilities"); } Ogre::LogManager::getSingleton().getDefaultLog()->stream() << "Num output vertices per geometry shader run : " << caps->getGeometryProgramNumOutputVertices(); } // Just override the mandatory create scene method void setupContent(void) { mCamera->setPosition(0, 0, -40); mCamera->lookAt(0,0,0); mCamera->setNearClipDistance(0.1); mCamera->setFarClipDistance(100); mTetrahedraMesh = ProceduralTools::generateTetrahedra(); //Create tetrahedra and add it to the root scene node tetrahedra = mSceneMgr->createEntity("TetrahedraEntity", mTetrahedraMesh->getName()); //tetraHedra->setDebugDisplayEnabled(true); Ogre::SceneNode* parentNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); parentNode->attachObject(tetrahedra); parentNode->setScale(10,10,10); } void cleanupContent() { MeshManager::getSingleton().remove(mTetrahedraMesh->getName()); } bool frameRenderingQueued(const FrameEvent& evt) { Real seconds = (Real)(Root::getSingleton().getTimer()->getMilliseconds()) / 1000.0; Ogre::Pass* renderPass = tetrahedra->getSubEntity(0)->getMaterial()->getTechnique(0)->getPass(0); if (renderPass->hasVertexProgram()) { Ogre::Vector4 constParam = Ogre::Vector4(-0.5, 0.0, 0.0, 0.2); renderPass->getVertexProgramParameters()->setNamedConstant("Metaballs[0]", constParam); Ogre::Vector4 timeParam = Ogre::Vector4( 0.1 + Ogre::Math::Sin(seconds)*0.5, Ogre::Math::Cos(seconds)*0.5, 0.0, 0.1); renderPass->getVertexProgramParameters()->setNamedConstant("Metaballs[1]", timeParam); } return SdkSample::frameRenderingQueued(evt); } }; #ifndef OGRE_STATIC_LIB extern "C" _OgreSampleExport void dllStartPlugin() { s = new Sample_Isosurf; sp = OGRE_NEW SamplePlugin(s->getInfo()["Title"] + " Sample"); sp->addSample(s); Root::getSingleton().installPlugin(sp); } extern "C" _OgreSampleExport void dllStopPlugin() { Root::getSingleton().uninstallPlugin(sp); OGRE_DELETE sp; delete s; } #endif
Enable IsoSurf sample to run in pure HLSL mode.
[Samples] Enable IsoSurf sample to run in pure HLSL mode. --HG-- branch : v1-9
C++
mit
digimatic/ogre,digimatic/ogre,digimatic/ogre,digimatic/ogre,digimatic/ogre,digimatic/ogre,digimatic/ogre
89a8b949fce1582f0dac38c751d9493f14f59d22
content/browser/in_process_webkit/indexed_db_browsertest.cc
content/browser/in_process_webkit/indexed_db_browsertest.cc
// 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 "base/bind.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/memory/ref_counted.h" #include "base/process_util.h" #include "base/test/thread_test_helper.h" #include "base/utf_string_conversions.h" #include "content/browser/in_process_webkit/indexed_db_context_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "content/public/test/browser_test_utils.h" #include "content/shell/shell.h" #include "content/test/content_browser_test.h" #include "content/test/content_browser_test_utils.h" #include "webkit/database/database_util.h" #include "webkit/quota/quota_manager.h" using quota::QuotaManager; using webkit_database::DatabaseUtil; namespace content { // This browser test is aimed towards exercising the IndexedDB bindings and // the actual implementation that lives in the browser side (in_process_webkit). class IndexedDBBrowserTest : public ContentBrowserTest { public: IndexedDBBrowserTest() {} void SimpleTest(const GURL& test_url, bool incognito = false) { // The test page will perform tests on IndexedDB, then navigate to either // a #pass or #fail ref. Shell* the_browser = incognito ? CreateOffTheRecordBrowser() : shell(); LOG(INFO) << "Navigating to URL and blocking."; NavigateToURLBlockUntilNavigationsComplete(the_browser, test_url, 2); LOG(INFO) << "Navigation done."; std::string result = the_browser->web_contents()->GetURL().ref(); if (result != "pass") { std::string js_result; ASSERT_TRUE(ExecuteJavaScriptAndExtractString( the_browser->web_contents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(getLog())", &js_result)); FAIL() << "Failed: " << js_result; } } void NavigateAndWaitForTitle(Shell* shell, const char* filename, const char* hash, const char* expected_string) { GURL url = GetTestUrl("indexeddb", filename); if (hash) url = GURL(url.spec() + hash); string16 expected_title16(ASCIIToUTF16(expected_string)); TitleWatcher title_watcher(shell->web_contents(), expected_title16); NavigateToURL(shell, url); EXPECT_EQ(expected_title16, title_watcher.WaitAndGetTitle()); } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) { SimpleTest(GetTestUrl("indexeddb", "cursor_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTestIncognito) { SimpleTest(GetTestUrl("indexeddb", "cursor_test.html"), true /* incognito */); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorPrefetch) { SimpleTest(GetTestUrl("indexeddb", "cursor_prefetch.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, IndexTest) { SimpleTest(GetTestUrl("indexeddb", "index_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, KeyPathTest) { SimpleTest(GetTestUrl("indexeddb", "key_path_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) { SimpleTest(GetTestUrl("indexeddb", "transaction_get_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, KeyTypesTest) { SimpleTest(GetTestUrl("indexeddb", "key_types_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ObjectStoreTest) { SimpleTest(GetTestUrl("indexeddb", "object_store_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) { SimpleTest(GetTestUrl("indexeddb", "database_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionTest) { SimpleTest(GetTestUrl("indexeddb", "transaction_test.html")); } // Appears flaky/slow, see: http://crbug.com/120298 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_ValueSizeTest) { SimpleTest(GetTestUrl("indexeddb", "value_size_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DoesntHangTest) { SimpleTest(GetTestUrl("indexeddb", "transaction_run_forever.html")); CrashTab(shell()->web_contents()); SimpleTest(GetTestUrl("indexeddb", "transaction_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug84933Test) { const GURL url = GetTestUrl("indexeddb", "bug_84933.html"); // Just navigate to the URL. Test will crash if it fails. NavigateToURLBlockUntilNavigationsComplete(shell(), url, 1); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug106883Test) { const GURL url = GetTestUrl("indexeddb", "bug_106883.html"); // Just navigate to the URL. Test will crash if it fails. NavigateToURLBlockUntilNavigationsComplete(shell(), url, 1); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug109187Test) { const GURL url = GetTestUrl("indexeddb", "bug_109187.html"); // Just navigate to the URL. Test will crash if it fails. NavigateToURLBlockUntilNavigationsComplete(shell(), url, 1); } class IndexedDBBrowserTestWithLowQuota : public IndexedDBBrowserTest { public: virtual void SetUpOnMainThread() { const int kInitialQuotaKilobytes = 5000; const int kTemporaryStorageQuotaMaxSize = kInitialQuotaKilobytes * 1024 * QuotaManager::kPerHostTemporaryPortion; SetTempQuota( kTemporaryStorageQuotaMaxSize, BrowserContext::GetDefaultStoragePartition( shell()->web_contents()->GetBrowserContext())->GetQuotaManager()); } static void SetTempQuota(int64 bytes, scoped_refptr<QuotaManager> qm) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&IndexedDBBrowserTestWithLowQuota::SetTempQuota, bytes, qm)); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); qm->SetTemporaryGlobalOverrideQuota(bytes, quota::QuotaCallback()); // Don't return until the quota has been set. scoped_refptr<base::ThreadTestHelper> helper( new base::ThreadTestHelper( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB))); ASSERT_TRUE(helper->Run()); } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithLowQuota, QuotaTest) { SimpleTest(GetTestUrl("indexeddb", "quota_test.html")); } class IndexedDBBrowserTestWithGCExposed : public IndexedDBBrowserTest { public: virtual void SetUpCommandLine(CommandLine* command_line) { command_line->AppendSwitchASCII(switches::kJavaScriptFlags, "--expose-gc"); } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithGCExposed, DatabaseCallbacksTest) { SimpleTest(GetTestUrl("indexeddb", "database_callbacks_first.html")); } class IndexedDBBrowserTestWithVersion0Schema : public IndexedDBBrowserTest { public: virtual void SetUpOnMainThread() { scoped_refptr<IndexedDBContext> context = BrowserContext::GetDefaultStoragePartition( shell()->web_contents()->GetBrowserContext())-> GetIndexedDBContext(); BrowserThread::PostTask( BrowserThread::WEBKIT_DEPRECATED, FROM_HERE, base::Bind( &IndexedDBBrowserTestWithVersion0Schema::CopyLevelDBToProfile, shell(), context)); scoped_refptr<base::ThreadTestHelper> helper( new base::ThreadTestHelper(BrowserThread::GetMessageLoopProxyForThread( BrowserThread::WEBKIT_DEPRECATED))); ASSERT_TRUE(helper->Run()); } static void CopyLevelDBToProfile(Shell* shell, scoped_refptr<IndexedDBContext> context) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED)); FilePath leveldb_dir(FILE_PATH_LITERAL("file__0.indexeddb.leveldb")); FilePath test_data_dir = GetTestFilePath("indexeddb", "migration_from_0").Append(leveldb_dir); IndexedDBContextImpl* context_impl = static_cast<IndexedDBContextImpl*>(context.get()); FilePath dest = context_impl->data_path().Append(leveldb_dir); // If we don't create the destination directory first, the contents of the // leveldb directory are copied directly into profile/IndexedDB instead of // profile/IndexedDB/file__0.xxx/ ASSERT_TRUE(file_util::CreateDirectory(dest)); const bool kRecursive = true; ASSERT_TRUE(file_util::CopyDirectory(test_data_dir, context_impl->data_path(), kRecursive)); } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithVersion0Schema, MigrationTest) { SimpleTest(GetTestUrl("indexeddb", "migration_test.html")); } // Verify null key path persists after restarting browser. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, PRE_NullKeyPathPersistence) { NavigateAndWaitForTitle(shell(), "bug_90635.html", "#part1", "pass - first run"); } // Verify null key path persists after restarting browser. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, NullKeyPathPersistence) { NavigateAndWaitForTitle(shell(), "bug_90635.html", "#part2", "pass - second run"); } // Verify that a VERSION_CHANGE transaction is rolled back after a // renderer/browser crash IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, PRE_PRE_VersionChangeCrashResilience) { NavigateAndWaitForTitle(shell(), "version_change_crash.html", "#part1", "pass - part1 - complete"); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, PRE_VersionChangeCrashResilience) { NavigateAndWaitForTitle(shell(), "version_change_crash.html", "#part2", "pass - part2 - crash me"); NavigateToURL(shell(), GURL(chrome::kChromeUIBrowserCrashHost)); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, VersionChangeCrashResilience) { NavigateAndWaitForTitle(shell(), "version_change_crash.html", "#part3", "pass - part3 - rolled back"); } // Verify that open DB connections are closed when a tab is destroyed. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ConnectionsClosedOnTabClose) { NavigateAndWaitForTitle(shell(), "version_change_blocked.html", "#tab1", "setVersion(1) complete"); // Start on a different URL to force a new renderer process. Shell* new_shell = CreateBrowser(); NavigateToURL(new_shell, GURL(chrome::kAboutBlankURL)); NavigateAndWaitForTitle(new_shell, "version_change_blocked.html", "#tab2", "setVersion(2) blocked"); string16 expected_title16(ASCIIToUTF16("setVersion(2) complete")); TitleWatcher title_watcher(new_shell->web_contents(), expected_title16); base::KillProcess( shell()->web_contents()->GetRenderProcessHost()->GetHandle(), 0, true); shell()->Close(); EXPECT_EQ(expected_title16, title_watcher.WaitAndGetTitle()); } } // namespace content
// 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 "base/bind.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/memory/ref_counted.h" #include "base/process_util.h" #include "base/test/thread_test_helper.h" #include "base/utf_string_conversions.h" #include "content/browser/in_process_webkit/indexed_db_context_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "content/public/test/browser_test_utils.h" #include "content/shell/shell.h" #include "content/test/content_browser_test.h" #include "content/test/content_browser_test_utils.h" #include "webkit/database/database_util.h" #include "webkit/quota/quota_manager.h" using quota::QuotaManager; using webkit_database::DatabaseUtil; namespace content { // This browser test is aimed towards exercising the IndexedDB bindings and // the actual implementation that lives in the browser side (in_process_webkit). class IndexedDBBrowserTest : public ContentBrowserTest { public: IndexedDBBrowserTest() {} void SimpleTest(const GURL& test_url, bool incognito = false) { // The test page will perform tests on IndexedDB, then navigate to either // a #pass or #fail ref. Shell* the_browser = incognito ? CreateOffTheRecordBrowser() : shell(); LOG(INFO) << "Navigating to URL and blocking."; NavigateToURLBlockUntilNavigationsComplete(the_browser, test_url, 2); LOG(INFO) << "Navigation done."; std::string result = the_browser->web_contents()->GetURL().ref(); if (result != "pass") { std::string js_result; ASSERT_TRUE(ExecuteJavaScriptAndExtractString( the_browser->web_contents()->GetRenderViewHost(), L"", L"window.domAutomationController.send(getLog())", &js_result)); FAIL() << "Failed: " << js_result; } } void NavigateAndWaitForTitle(Shell* shell, const char* filename, const char* hash, const char* expected_string) { GURL url = GetTestUrl("indexeddb", filename); if (hash) url = GURL(url.spec() + hash); string16 expected_title16(ASCIIToUTF16(expected_string)); TitleWatcher title_watcher(shell->web_contents(), expected_title16); NavigateToURL(shell, url); EXPECT_EQ(expected_title16, title_watcher.WaitAndGetTitle()); } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) { SimpleTest(GetTestUrl("indexeddb", "cursor_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTestIncognito) { SimpleTest(GetTestUrl("indexeddb", "cursor_test.html"), true /* incognito */); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorPrefetch) { SimpleTest(GetTestUrl("indexeddb", "cursor_prefetch.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, IndexTest) { SimpleTest(GetTestUrl("indexeddb", "index_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, KeyPathTest) { SimpleTest(GetTestUrl("indexeddb", "key_path_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) { SimpleTest(GetTestUrl("indexeddb", "transaction_get_test.html")); } // Needs to be disabled until after WK 129037 rolls into chromium and we can // update this expectation. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_KeyTypesTest) { SimpleTest(GetTestUrl("indexeddb", "key_types_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ObjectStoreTest) { SimpleTest(GetTestUrl("indexeddb", "object_store_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) { SimpleTest(GetTestUrl("indexeddb", "database_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionTest) { SimpleTest(GetTestUrl("indexeddb", "transaction_test.html")); } // Appears flaky/slow, see: http://crbug.com/120298 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_ValueSizeTest) { SimpleTest(GetTestUrl("indexeddb", "value_size_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DoesntHangTest) { SimpleTest(GetTestUrl("indexeddb", "transaction_run_forever.html")); CrashTab(shell()->web_contents()); SimpleTest(GetTestUrl("indexeddb", "transaction_test.html")); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug84933Test) { const GURL url = GetTestUrl("indexeddb", "bug_84933.html"); // Just navigate to the URL. Test will crash if it fails. NavigateToURLBlockUntilNavigationsComplete(shell(), url, 1); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug106883Test) { const GURL url = GetTestUrl("indexeddb", "bug_106883.html"); // Just navigate to the URL. Test will crash if it fails. NavigateToURLBlockUntilNavigationsComplete(shell(), url, 1); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug109187Test) { const GURL url = GetTestUrl("indexeddb", "bug_109187.html"); // Just navigate to the URL. Test will crash if it fails. NavigateToURLBlockUntilNavigationsComplete(shell(), url, 1); } class IndexedDBBrowserTestWithLowQuota : public IndexedDBBrowserTest { public: virtual void SetUpOnMainThread() { const int kInitialQuotaKilobytes = 5000; const int kTemporaryStorageQuotaMaxSize = kInitialQuotaKilobytes * 1024 * QuotaManager::kPerHostTemporaryPortion; SetTempQuota( kTemporaryStorageQuotaMaxSize, BrowserContext::GetDefaultStoragePartition( shell()->web_contents()->GetBrowserContext())->GetQuotaManager()); } static void SetTempQuota(int64 bytes, scoped_refptr<QuotaManager> qm) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&IndexedDBBrowserTestWithLowQuota::SetTempQuota, bytes, qm)); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); qm->SetTemporaryGlobalOverrideQuota(bytes, quota::QuotaCallback()); // Don't return until the quota has been set. scoped_refptr<base::ThreadTestHelper> helper( new base::ThreadTestHelper( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB))); ASSERT_TRUE(helper->Run()); } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithLowQuota, QuotaTest) { SimpleTest(GetTestUrl("indexeddb", "quota_test.html")); } class IndexedDBBrowserTestWithGCExposed : public IndexedDBBrowserTest { public: virtual void SetUpCommandLine(CommandLine* command_line) { command_line->AppendSwitchASCII(switches::kJavaScriptFlags, "--expose-gc"); } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithGCExposed, DatabaseCallbacksTest) { SimpleTest(GetTestUrl("indexeddb", "database_callbacks_first.html")); } class IndexedDBBrowserTestWithVersion0Schema : public IndexedDBBrowserTest { public: virtual void SetUpOnMainThread() { scoped_refptr<IndexedDBContext> context = BrowserContext::GetDefaultStoragePartition( shell()->web_contents()->GetBrowserContext())-> GetIndexedDBContext(); BrowserThread::PostTask( BrowserThread::WEBKIT_DEPRECATED, FROM_HERE, base::Bind( &IndexedDBBrowserTestWithVersion0Schema::CopyLevelDBToProfile, shell(), context)); scoped_refptr<base::ThreadTestHelper> helper( new base::ThreadTestHelper(BrowserThread::GetMessageLoopProxyForThread( BrowserThread::WEBKIT_DEPRECATED))); ASSERT_TRUE(helper->Run()); } static void CopyLevelDBToProfile(Shell* shell, scoped_refptr<IndexedDBContext> context) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED)); FilePath leveldb_dir(FILE_PATH_LITERAL("file__0.indexeddb.leveldb")); FilePath test_data_dir = GetTestFilePath("indexeddb", "migration_from_0").Append(leveldb_dir); IndexedDBContextImpl* context_impl = static_cast<IndexedDBContextImpl*>(context.get()); FilePath dest = context_impl->data_path().Append(leveldb_dir); // If we don't create the destination directory first, the contents of the // leveldb directory are copied directly into profile/IndexedDB instead of // profile/IndexedDB/file__0.xxx/ ASSERT_TRUE(file_util::CreateDirectory(dest)); const bool kRecursive = true; ASSERT_TRUE(file_util::CopyDirectory(test_data_dir, context_impl->data_path(), kRecursive)); } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithVersion0Schema, MigrationTest) { SimpleTest(GetTestUrl("indexeddb", "migration_test.html")); } // Verify null key path persists after restarting browser. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, PRE_NullKeyPathPersistence) { NavigateAndWaitForTitle(shell(), "bug_90635.html", "#part1", "pass - first run"); } // Verify null key path persists after restarting browser. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, NullKeyPathPersistence) { NavigateAndWaitForTitle(shell(), "bug_90635.html", "#part2", "pass - second run"); } // Verify that a VERSION_CHANGE transaction is rolled back after a // renderer/browser crash IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, PRE_PRE_VersionChangeCrashResilience) { NavigateAndWaitForTitle(shell(), "version_change_crash.html", "#part1", "pass - part1 - complete"); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, PRE_VersionChangeCrashResilience) { NavigateAndWaitForTitle(shell(), "version_change_crash.html", "#part2", "pass - part2 - crash me"); NavigateToURL(shell(), GURL(chrome::kChromeUIBrowserCrashHost)); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, VersionChangeCrashResilience) { NavigateAndWaitForTitle(shell(), "version_change_crash.html", "#part3", "pass - part3 - rolled back"); } // Verify that open DB connections are closed when a tab is destroyed. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ConnectionsClosedOnTabClose) { NavigateAndWaitForTitle(shell(), "version_change_blocked.html", "#tab1", "setVersion(1) complete"); // Start on a different URL to force a new renderer process. Shell* new_shell = CreateBrowser(); NavigateToURL(new_shell, GURL(chrome::kAboutBlankURL)); NavigateAndWaitForTitle(new_shell, "version_change_blocked.html", "#tab2", "setVersion(2) blocked"); string16 expected_title16(ASCIIToUTF16("setVersion(2) complete")); TitleWatcher title_watcher(new_shell->web_contents(), expected_title16); base::KillProcess( shell()->web_contents()->GetRenderProcessHost()->GetHandle(), 0, true); shell()->Close(); EXPECT_EQ(expected_title16, title_watcher.WaitAndGetTitle()); } } // namespace content
Disable IndexedDBBrowserTest.KeyTypesTest
Disable IndexedDBBrowserTest.KeyTypesTest It is broken by WK 129037. Review URL: https://codereview.chromium.org/10958003 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@157634 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
bright-sparks/chromium-spacewalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,ltilve/chromium,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,littlstar/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,Just-D/chromium-1,dednal/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src,Fireblend/chromium-crosswalk,anirudhSK/chromium,patrickm/chromium.src,ltilve/chromium,jaruba/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,axinging/chromium-crosswalk,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,ChromiumWebApps/chromium,jaruba/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,nacl-webkit/chrome_deps,jaruba/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,dednal/chromium.src,ltilve/chromium,Just-D/chromium-1,timopulkkinen/BubbleFish,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,markYoungH/chromium.src,ondra-novak/chromium.src,chuan9/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,jaruba/chromium.src,timopulkkinen/BubbleFish,dednal/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,ondra-novak/chromium.src,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,hujiajie/pa-chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,anirudhSK/chromium,ondra-novak/chromium.src,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,ondra-novak/chromium.src,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,zcbenz/cefode-chromium,jaruba/chromium.src,markYoungH/chromium.src,dednal/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,dednal/chromium.src,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,Chilledheart/chromium,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,jaruba/chromium.src,timopulkkinen/BubbleFish,ondra-novak/chromium.src,hujiajie/pa-chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,Chilledheart/chromium,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,anirudhSK/chromium,patrickm/chromium.src,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,dushu1203/chromium.src,hujiajie/pa-chromium,patrickm/chromium.src,axinging/chromium-crosswalk,ondra-novak/chromium.src,Chilledheart/chromium,ltilve/chromium,zcbenz/cefode-chromium,patrickm/chromium.src,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,Chilledheart/chromium,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,anirudhSK/chromium,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,ondra-novak/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,M4sse/chromium.src,anirudhSK/chromium,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,anirudhSK/chromium,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,ltilve/chromium,zcbenz/cefode-chromium,hujiajie/pa-chromium,nacl-webkit/chrome_deps,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,ltilve/chromium,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,markYoungH/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,anirudhSK/chromium,littlstar/chromium.src,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,Chilledheart/chromium,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,littlstar/chromium.src,chuan9/chromium-crosswalk,dushu1203/chromium.src,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,dednal/chromium.src,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,M4sse/chromium.src,jaruba/chromium.src,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,littlstar/chromium.src,hujiajie/pa-chromium,hujiajie/pa-chromium,M4sse/chromium.src,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,ltilve/chromium,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,dednal/chromium.src,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl
5e23d5f628918c1e140c48f44be6f63217d9cec3
playerJoinHandler.cpp
playerJoinHandler.cpp
/* Copyright (C) 2016 Vladimir "allejo" Jimenez 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 <map> #include <memory> #include <sstream> #include "bzfsAPI.h" #include "plugin_utils.h" // Define plugin name const std::string PLUGIN_NAME = "Player Join Handler"; // Define plugin version numbering const int MAJOR = 1; const int MINOR = 0; const int REV = 1; const int BUILD = 12; class PlayerJoinHandler : public bz_Plugin { public: virtual const char* Name (); virtual void Init (const char* config); virtual void Event (bz_EventData *eventData); virtual void Cleanup (void); typedef std::map<std::string, double> SessionList; virtual bool checkSession(SessionList &list, std::string target); SessionList bzidSessions, ipSessions; std::string bzdb_SessionTime, bzdb_AllowUnregistered; }; BZ_PLUGIN(PlayerJoinHandler) const char* PlayerJoinHandler::Name (void) { static std::string pluginBuild = ""; if (!pluginBuild.size()) { std::ostringstream pluginBuildStream; pluginBuildStream << PLUGIN_NAME << " " << MAJOR << "." << MINOR << "." << REV << " (" << BUILD << ")"; pluginBuild = pluginBuildStream.str(); } return pluginBuild.c_str(); } void PlayerJoinHandler::Init (const char* /*commandLine*/) { Register(bz_eGetAutoTeamEvent); Register(bz_ePlayerPartEvent); bzdb_SessionTime = "_sessionTime"; bzdb_AllowUnregistered = "_allowUnverified"; if (!bz_BZDBItemExists(bzdb_SessionTime.c_str())) { bz_setBZDBInt(bzdb_SessionTime.c_str(), 120); } if (!bz_BZDBItemExists(bzdb_AllowUnregistered.c_str())) { bz_setBZDBBool(bzdb_AllowUnregistered.c_str(), false); } } void PlayerJoinHandler::Cleanup (void) { Flush(); } void PlayerJoinHandler::Event (bz_EventData *eventData) { switch (eventData->eventType) { case bz_eGetAutoTeamEvent: { bz_GetAutoTeamEventData_V1* autoTeamData = (bz_GetAutoTeamEventData_V1*)eventData; std::unique_ptr<bz_BasePlayerRecord> pr(bz_getPlayerByIndex(autoTeamData->playerID)); std::string bzID = pr->bzID.c_str(); std::string ipAddress = pr->ipAddress.c_str(); bool allowUnregistered = bz_getBZDBBool(bzdb_AllowUnregistered.c_str()); if ((bz_isCountDownActive() || bz_isCountDownInProgress() || bz_isCountDownPaused()) && autoTeamData->team != eObservers) { autoTeamData->handled = true; autoTeamData->team = eObservers; if ((pr->verified && checkSession(bzidSessions, bzID)) || (!pr->verified && checkSession(ipSessions, ipAddress)) || (!pr->verified && !allowUnregistered)) { bz_sendTextMessage(BZ_SERVER, autoTeamData->playerID, "An active match is currently in progress. You have been automatically moved to the observer team to avoid disruption."); bz_sendTextMessage(BZ_SERVER, autoTeamData->playerID, "If you intend to substitute another player, you may now rejoin as a player."); } } } break; case bz_ePlayerPartEvent: { bz_PlayerJoinPartEventData_V1* partData = (bz_PlayerJoinPartEventData_V1*)eventData; bz_BasePlayerRecord* &pr = partData->record; std::string ipAddress = pr->ipAddress.c_str(); std::string bzID = pr->bzID.c_str(); if (pr->verified) { bzidSessions[bzID] = bz_getCurrentTime(); } else { ipSessions[ipAddress] = bz_getCurrentTime(); } } break; default: break; } } bool PlayerJoinHandler::checkSession(SessionList &list, std::string target) { int rejoinTime = bz_getBZDBInt(bzdb_SessionTime.c_str()); return (list.find(target) == list.end()) || (list[target] + rejoinTime < bz_getCurrentTime()); }
/* Copyright (C) 2016 Vladimir "allejo" Jimenez 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 <map> #include <memory> #include <sstream> #include "bzfsAPI.h" #include "plugin_utils.h" // Define plugin name const std::string PLUGIN_NAME = "Player Join Handler"; // Define plugin version numbering const int MAJOR = 1; const int MINOR = 0; const int REV = 2; const int BUILD = 16; class PlayerJoinHandler : public bz_Plugin { public: virtual const char* Name (); virtual void Init (const char* config); virtual void Event (bz_EventData *eventData); virtual void Cleanup (void); typedef std::map<std::string, double> SessionList; virtual bool sessionExists(SessionList &list, std::string target); SessionList bzidSessions, ipSessions; std::string bzdb_SessionTime, bzdb_AllowUnregistered; }; BZ_PLUGIN(PlayerJoinHandler) const char* PlayerJoinHandler::Name (void) { static std::string pluginBuild = ""; if (!pluginBuild.size()) { std::ostringstream pluginBuildStream; pluginBuildStream << PLUGIN_NAME << " " << MAJOR << "." << MINOR << "." << REV << " (" << BUILD << ")"; pluginBuild = pluginBuildStream.str(); } return pluginBuild.c_str(); } void PlayerJoinHandler::Init (const char* /*commandLine*/) { Register(bz_eGetAutoTeamEvent); Register(bz_ePlayerPartEvent); bzdb_SessionTime = "_sessionTime"; bzdb_AllowUnregistered = "_allowUnverified"; if (!bz_BZDBItemExists(bzdb_SessionTime.c_str())) { bz_setBZDBInt(bzdb_SessionTime.c_str(), 120); } if (!bz_BZDBItemExists(bzdb_AllowUnregistered.c_str())) { bz_setBZDBBool(bzdb_AllowUnregistered.c_str(), false); } } void PlayerJoinHandler::Cleanup (void) { Flush(); } void PlayerJoinHandler::Event (bz_EventData *eventData) { switch (eventData->eventType) { case bz_eGetAutoTeamEvent: { bz_GetAutoTeamEventData_V1* autoTeamData = (bz_GetAutoTeamEventData_V1*)eventData; std::unique_ptr<bz_BasePlayerRecord> pr(bz_getPlayerByIndex(autoTeamData->playerID)); std::string bzID = pr->bzID.c_str(); std::string ipAddress = pr->ipAddress.c_str(); bool allowUnregistered = bz_getBZDBBool(bzdb_AllowUnregistered.c_str()); if ((bz_isCountDownActive() || bz_isCountDownInProgress() || bz_isCountDownPaused()) && autoTeamData->team != eObservers) { if ((pr->verified && !sessionExists(bzidSessions, bzID)) || (!pr->verified && !sessionExists(ipSessions, ipAddress)) || (!pr->verified && !allowUnregistered)) { autoTeamData->handled = true; autoTeamData->team = eObservers; bz_sendTextMessage(BZ_SERVER, autoTeamData->playerID, "An active match is currently in progress. You have been automatically moved to the observer team to avoid disruption."); if (pr->verified) { bz_sendTextMessage(BZ_SERVER, autoTeamData->playerID, "If you intend to substitute another player, you may now rejoin as a player."); } else { if (!allowUnregistered) { bz_sendTextMessage(BZ_SERVER, autoTeamData->playerID, "This server only allows registered players to join as a subtitute, please use a registered account."); } } } } } break; case bz_ePlayerPartEvent: { bz_PlayerJoinPartEventData_V1* partData = (bz_PlayerJoinPartEventData_V1*)eventData; bz_BasePlayerRecord* &pr = partData->record; std::string ipAddress = pr->ipAddress.c_str(); std::string bzID = pr->bzID.c_str(); if (pr->verified) { bzidSessions[bzID] = bz_getCurrentTime(); } else { ipSessions[ipAddress] = bz_getCurrentTime(); } } break; default: break; } } bool PlayerJoinHandler::sessionExists(SessionList &list, std::string target) { int rejoinTime = bz_getBZDBInt(bzdb_SessionTime.c_str()); return (list.count(target)) && (list[target] + rejoinTime > bz_getCurrentTime()); }
Fix bug where plugin didn't work at all
Fix bug where plugin didn't work at all
C++
mit
allejo/playerJoinHandler
e4694369de35cb9dc97ffab010372df0061202f2
Source/Example/HowToUse_Dll.cpp
Source/Example/HowToUse_Dll.cpp
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Example for MediaInfoLib // Command line version // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #ifdef MEDIAINFO_LIBRARY #include "MediaInfo/MediaInfo.h" //Staticly-loaded library (.lib or .a or .so) #define MediaInfoNameSpace MediaInfoLib; #else //MEDIAINFO_LIBRARY #include "MediaInfoDLL/MediaInfoDLL.h" //Dynamicly-loaded library (.dll or .so) #define MediaInfoNameSpace MediaInfoDLL; #endif //MEDIAINFO_LIBRARY #include <iostream> #include <iomanip> using namespace MediaInfoNameSpace; #ifdef __MINGW32__ #ifdef _UNICODE #define _itot _itow #else //_UNICODE #define _itot itoa #endif //_UNICODE #endif //__MINGW32 int main (int /*argc*/, Char * /*argv[]*/) { //Information about MediaInfo MediaInfo MI; String To_Display=MI.Option(__T("Info_Version"), __T("0.7.13;MediaInfoDLL_Example_MSVC;0.7.13")).c_str(); To_Display += __T("\r\n\r\nInfo_Parameters\r\n"); To_Display += MI.Option(__T("Info_Parameters")).c_str(); To_Display += __T("\r\n\r\nInfo_Codecs\r\n"); To_Display += MI.Option(__T("Info_Codecs")).c_str(); //An example of how to use the library To_Display += __T("\r\n\r\nOpen\r\n"); MI.Open(__T("Example.ogg")); To_Display += __T("\r\n\r\nInform with Complete=false\r\n"); MI.Option(__T("Complete")); To_Display += MI.Inform().c_str(); To_Display += __T("\r\n\r\nInform with Complete=true\r\n"); MI.Option(__T("Complete"), __T("1")); To_Display += MI.Inform().c_str(); To_Display += __T("\r\n\r\nCustom Inform\r\n"); MI.Option(__T("Inform"), __T("General;Example : FileSize=%FileSize%")); To_Display += MI.Inform().c_str(); To_Display += __T("\r\n\r\nGet with Stream=General and Parameter=\"FileSize\"\r\n"); To_Display += MI.Get(Stream_General, 0, __T("FileSize"), Info_Text, Info_Name).c_str(); To_Display += __T("\r\n\r\nGetI with Stream=General and Parameter=46\r\n"); To_Display += MI.Get(Stream_General, 0, 46, Info_Text).c_str(); To_Display += __T("\r\n\r\nCount_Get with StreamKind=Stream_Audio\r\n"); #ifdef __MINGW32__ Char* C1=new Char[33]; _itot (MI.Count_Get(Stream_Audio), C1, 10); To_Display +=C1; delete[] C1; #else toStringStream SS; SS << std::setbase(10) << MI.Count_Get(Stream_Audio); To_Display += SS.str(); #endif To_Display += __T("\r\n\r\nGet with Stream=General and Parameter=\"AudioCount\"\r\n"); To_Display += MI.Get(Stream_General, 0, __T("AudioCount"), Info_Text, Info_Name).c_str(); To_Display += __T("\r\n\r\nGet with Stream=Audio and Parameter=\"StreamCount\"\r\n"); To_Display += MI.Get(Stream_Audio, 0, __T("StreamCount"), Info_Text, Info_Name).c_str(); To_Display += __T("\r\n\r\nClose\r\n"); MI.Close(); #ifdef _UNICODE std::wcout << To_Display; #else std::cout << To_Display; #endif return 0; } //*************************************************************************** // By buffer example //*************************************************************************** /* //--------------------------------------------------------------------------- //Note: you can replace file operations by your own buffer management class #include <stdio.h> int main (int argc, Char *argv[]) { //From: preparing an example file for reading FILE* F=fopen("Example.ogg", "rb"); //You can use something else than a file if (F==0) return 1; //From: preparing a memory buffer for reading unsigned char* From_Buffer=new unsigned char[7*188]; //Note: you can do your own buffer size_t From_Buffer_Size; //The size of the read file buffer //From: retrieving file size fseek(F, 0, SEEK_END); long F_Size=ftell(F); fseek(F, 0, SEEK_SET); //Initializing MediaInfo MediaInfo MI; //Preparing to fill MediaInfo with a buffer MI.Open_Buffer_Init(F_Size, 0); //The parsing loop do { //Reading data somewhere, do what you want for this. From_Buffer_Size=fread(From_Buffer, 1, 7*188, F); //Sending the buffer to MediaInfo size_t Status=MI.Open_Buffer_Continue(From_Buffer, From_Buffer_Size); if (Status&0x08) //Bit3=Finished break; //Testing if there is a MediaInfo request to go elsewhere if (MI.Open_Buffer_Continue_GoTo_Get()!=(MediaInfo_int64u)-1) { fseek(F, (long)MI.Open_Buffer_Continue_GoTo_Get(), SEEK_SET); //Position the file MI.Open_Buffer_Init(F_Size, ftell(F)); //Informing MediaInfo we have seek } } while (From_Buffer_Size>0); //Finalizing MI.Open_Buffer_Finalize(); //This is the end of the stream, MediaInfo must finnish some work //Get() example String To_Display=MI.Get(Stream_General, 0, __T("Format")); #ifdef _UNICODE std::wcout << To_Display; #else std::cout << To_Display; #endif } */
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Example for MediaInfoLib // Command line version // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #ifdef MEDIAINFO_LIBRARY #include "MediaInfo/MediaInfo.h" //Staticly-loaded library (.lib or .a or .so) #define MediaInfoNameSpace MediaInfoLib; #else //MEDIAINFO_LIBRARY #include "MediaInfoDLL/MediaInfoDLL.h" //Dynamicly-loaded library (.dll or .so) #define MediaInfoNameSpace MediaInfoDLL; #endif //MEDIAINFO_LIBRARY #include <iostream> #include <iomanip> using namespace MediaInfoNameSpace; #ifdef __MINGW32__ #ifdef _UNICODE #define _itot _itow #else //_UNICODE #define _itot itoa #endif //_UNICODE #endif //__MINGW32 int main (int /*argc*/, Char * /*argv[]*/) { //Information about MediaInfo MediaInfo MI; String To_Display=MI.Option(__T("Info_Version"), __T("0.7.13;MediaInfoDLL_Example_MSVC;0.7.13")); To_Display += __T("\r\n\r\nInfo_Parameters\r\n"); To_Display += MI.Option(__T("Info_Parameters")); To_Display += __T("\r\n\r\nInfo_Codecs\r\n"); To_Display += MI.Option(__T("Info_Codecs")); //An example of how to use the library To_Display += __T("\r\n\r\nOpen\r\n"); MI.Open(__T("Example.ogg")); To_Display += __T("\r\n\r\nInform with Complete=false\r\n"); MI.Option(__T("Complete")); To_Display += MI.Inform(); To_Display += __T("\r\n\r\nInform with Complete=true\r\n"); MI.Option(__T("Complete"), __T("1")); To_Display += MI.Inform(); To_Display += __T("\r\n\r\nCustom Inform\r\n"); MI.Option(__T("Inform"), __T("General;Example : FileSize=%FileSize%")); To_Display += MI.Inform(); To_Display += __T("\r\n\r\nGet with Stream=General and Parameter=\"FileSize\"\r\n"); To_Display += MI.Get(Stream_General, 0, __T("FileSize"), Info_Text, Info_Name); To_Display += __T("\r\n\r\nGetI with Stream=General and Parameter=46\r\n"); To_Display += MI.Get(Stream_General, 0, 46, Info_Text); To_Display += __T("\r\n\r\nCount_Get with StreamKind=Stream_Audio\r\n"); #ifdef __MINGW32__ Char* C1=new Char[33]; _itot (MI.Count_Get(Stream_Audio), C1, 10); To_Display +=C1; delete[] C1; #else toStringStream SS; SS << std::setbase(10) << MI.Count_Get(Stream_Audio); To_Display += SS.str(); #endif To_Display += __T("\r\n\r\nGet with Stream=General and Parameter=\"AudioCount\"\r\n"); To_Display += MI.Get(Stream_General, 0, __T("AudioCount"), Info_Text, Info_Name); To_Display += __T("\r\n\r\nGet with Stream=Audio and Parameter=\"StreamCount\"\r\n"); To_Display += MI.Get(Stream_Audio, 0, __T("StreamCount"), Info_Text, Info_Name); To_Display += __T("\r\n\r\nClose\r\n"); MI.Close(); #ifdef _UNICODE std::wcout << To_Display; #else std::cout << To_Display; #endif return 0; } //*************************************************************************** // By buffer example //*************************************************************************** /* //--------------------------------------------------------------------------- //Note: you can replace file operations by your own buffer management class #include <stdio.h> int main (int argc, Char *argv[]) { //From: preparing an example file for reading FILE* F=fopen("Example.ogg", "rb"); //You can use something else than a file if (F==0) return 1; //From: preparing a memory buffer for reading unsigned char* From_Buffer=new unsigned char[7*188]; //Note: you can do your own buffer size_t From_Buffer_Size; //The size of the read file buffer //From: retrieving file size fseek(F, 0, SEEK_END); long F_Size=ftell(F); fseek(F, 0, SEEK_SET); //Initializing MediaInfo MediaInfo MI; //Preparing to fill MediaInfo with a buffer MI.Open_Buffer_Init(F_Size, 0); //The parsing loop do { //Reading data somewhere, do what you want for this. From_Buffer_Size=fread(From_Buffer, 1, 7*188, F); //Sending the buffer to MediaInfo size_t Status=MI.Open_Buffer_Continue(From_Buffer, From_Buffer_Size); if (Status&0x08) //Bit3=Finished break; //Testing if there is a MediaInfo request to go elsewhere if (MI.Open_Buffer_Continue_GoTo_Get()!=(MediaInfo_int64u)-1) { fseek(F, (long)MI.Open_Buffer_Continue_GoTo_Get(), SEEK_SET); //Position the file MI.Open_Buffer_Init(F_Size, ftell(F)); //Informing MediaInfo we have seek } } while (From_Buffer_Size>0); //Finalizing MI.Open_Buffer_Finalize(); //This is the end of the stream, MediaInfo must finnish some work //Get() example String To_Display=MI.Get(Stream_General, 0, __T("Format")); #ifdef _UNICODE std::wcout << To_Display; #else std::cout << To_Display; #endif } */
Fix V811 Decreased performance. Excessive type casting: string -> char * -> string.
Fix V811 Decreased performance. Excessive type casting: string -> char * -> string.
C++
bsd-2-clause
MediaArea/MediaInfoLib,JeromeMartinez/MediaInfoLib,JeromeMartinez/MediaInfoLib,MediaArea/MediaInfoLib,JeromeMartinez/MediaInfoLib,JeromeMartinez/MediaInfoLib,JeromeMartinez/MediaInfoLib,MediaArea/MediaInfoLib,JeromeMartinez/MediaInfoLib,JeromeMartinez/MediaInfoLib,MediaArea/MediaInfoLib,JeromeMartinez/MediaInfoLib,MediaArea/MediaInfoLib,MediaArea/MediaInfoLib,MediaArea/MediaInfoLib,MediaArea/MediaInfoLib,MediaArea/MediaInfoLib,JeromeMartinez/MediaInfoLib
4983a518d1add2587ce2f4bf0e081bf6ad3d4fdd
plugins/ipc/stipc.cpp
plugins/ipc/stipc.cpp
#include <wayfire/singleton-plugin.hpp> #include <wayfire/view.hpp> #include <wayfire/output.hpp> #include <wayfire/workspace-manager.hpp> #include <getopt.h> #include "ipc.hpp" extern "C" { #include <wlr/backend/wayland.h> #include <wlr/backend/multi.h> #include <wlr/backend/headless.h> #include <wlr/types/wlr_pointer.h> #include <wlr/types/wlr_keyboard.h> #include <wlr/interfaces/wlr_keyboard.h> #include <libevdev/libevdev.h> } #include <wayfire/util/log.hpp> #include <wayfire/core.hpp> static void locate_wayland_backend(wlr_backend *backend, void *data) { if (wlr_backend_is_wl(backend)) { wlr_backend **result = (wlr_backend**)data; *result = backend; } } namespace wf { static nlohmann::json geometry_to_json(wf::geometry_t g) { nlohmann::json j; j["x"] = g.x; j["y"] = g.y; j["width"] = g.width; j["height"] = g.height; return j; } static std::string layer_to_string(uint32_t layer) { switch (layer) { case LAYER_BACKGROUND: return "background"; case LAYER_BOTTOM: return "bottom"; case LAYER_WORKSPACE: return "workspace"; case LAYER_TOP: return "top"; case LAYER_UNMANAGED: return "unmanaged"; case LAYER_LOCK: return "lock"; case LAYER_DESKTOP_WIDGET: return "dew"; case LAYER_MINIMIZED: return "minimized"; default: break; } return "none"; } class headless_input_backend_t { public: wlr_backend *backend; wlr_input_device *pointer; wlr_input_device *keyboard; headless_input_backend_t() { auto& core = wf::get_core(); backend = wlr_headless_backend_create(core.display); wlr_multi_backend_add(core.backend, backend); wlr_backend_start(backend); pointer = wlr_headless_add_input_device(backend, WLR_INPUT_DEVICE_POINTER); keyboard = wlr_headless_add_input_device(backend, WLR_INPUT_DEVICE_KEYBOARD); } ~headless_input_backend_t() { auto& core = wf::get_core(); wlr_multi_backend_remove(core.backend, backend); wlr_backend_destroy(backend); } void do_key(uint32_t key, wl_keyboard_key_state state) { wlr_event_keyboard_key ev; ev.keycode = key; ev.state = state; ev.update_state = true; ev.time_msec = get_current_time(); wlr_keyboard_notify_key(keyboard->keyboard, &ev); } void do_button(uint32_t button, wlr_button_state state) { wlr_event_pointer_button ev; ev.device = pointer; ev.button = button; ev.state = state; ev.time_msec = get_current_time(); wl_signal_emit(&pointer->pointer->events.button, &ev); } headless_input_backend_t(const headless_input_backend_t&) = delete; headless_input_backend_t(headless_input_backend_t&&) = delete; headless_input_backend_t& operator =(const headless_input_backend_t&) = delete; headless_input_backend_t& operator =(headless_input_backend_t&&) = delete; }; static inline nlohmann::json get_ok() { return nlohmann::json{ {"result", "ok"} }; } static inline nlohmann::json get_error(std::string msg) { return nlohmann::json{ {"error", std::string(msg)} }; } class ipc_plugin_t { public: ipc_plugin_t() { input = std::make_unique<headless_input_backend_t>(); char *pre_socket = getenv("_WAYFIRE_SOCKET"); const auto& dname = wf::get_core().wayland_display; std::string socket = pre_socket ?: "/tmp/wayfire-" + dname + ".socket"; setenv("WAYFIRE_SOCKET", socket.c_str(), 1); server = std::make_unique<ipc::server_t>(socket); server->register_method("core/list_views", list_views); server->register_method("core/create_wayland_output", create_wayland_output); server->register_method("core/feed_key", feed_key); } using method_t = ipc::server_t::method_cb; method_t list_views = [] (nlohmann::json) { auto response = nlohmann::json::array(); for (auto& view : wf::get_core().get_all_views()) { nlohmann::json v; v["title"] = view->get_title(); v["app-id"] = view->get_app_id(); v["geometry"] = geometry_to_json(view->get_wm_geometry()); v["base-geometry"] = geometry_to_json(view->get_output_geometry()); v["state"] = { {"tiled", view->tiled_edges}, {"fullscreen", view->fullscreen}, {"minimized", view->minimized}, }; uint32_t layer = -1; if (view->get_output()) { layer = view->get_output()->workspace->get_view_layer(view); } v["layer"] = layer_to_string(layer); response.push_back(v); } return response; }; method_t create_wayland_output = [] (nlohmann::json) { auto backend = wf::get_core().backend; wlr_backend *wayland_backend = NULL; wlr_multi_for_each_backend(backend, locate_wayland_backend, &wayland_backend); if (!wayland_backend) { return get_error("Wayfire is not running in nested wayland mode!"); } wlr_wl_output_create(wayland_backend); return get_ok(); }; struct key_t { bool modifier; int code; }; std::variant<key_t, std::string> parse_key(nlohmann::json data) { if (!data.count("combo") || !data["combo"].is_string()) { return std::string("Missing or wrong json type for `combo`!"); } std::string combo = data["combo"]; if (combo.size() < 4) { return std::string("Missing or wrong json type for `combo`!"); } // Check super modifier bool modifier = false; if (combo.substr(0, 2) == "S-") { modifier = true; combo = combo.substr(2); } int key = libevdev_event_code_from_name(EV_KEY, combo.c_str()); if (key == -1) { return std::string("Failed to parse combo \"" + combo + "\""); } return key_t{modifier, key}; } method_t feed_key = [=] (nlohmann::json data) { auto result = parse_key(data); auto key = std::get_if<key_t>(&result); if (!key) { return get_error(std::get<std::string>(result)); } if (key->modifier) { input->do_key(KEY_LEFTMETA, WL_KEYBOARD_KEY_STATE_PRESSED); } input->do_key(key->code, WL_KEYBOARD_KEY_STATE_PRESSED); input->do_key(key->code, WL_KEYBOARD_KEY_STATE_RELEASED); if (key->modifier) { input->do_key(KEY_LEFTMETA, WL_KEYBOARD_KEY_STATE_RELEASED); } return get_ok(); }; method_t feed_button = [=] (nlohmann::json data) { auto result = parse_key(data); auto button = std::get_if<key_t>(&result); if (!button) { return get_error(std::get<std::string>(result)); } if (!data.count("mode") || !data["mode"].is_string()) { return get_error("No mode specified"); } auto mode = data["mode"]; if ((mode == "press") || (mode == "full")) { if (button->modifier) { input->do_key(KEY_LEFTMETA, WL_KEYBOARD_KEY_STATE_PRESSED); } input->do_button(button->code, WLR_BUTTON_PRESSED); } if ((mode == "release") || (mode == "full")) { input->do_button(button->code, WLR_BUTTON_RELEASED); if (button->modifier) { input->do_key(KEY_LEFTMETA, WL_KEYBOARD_KEY_STATE_RELEASED); } } return get_ok(); }; std::unique_ptr<ipc::server_t> server; std::unique_ptr<headless_input_backend_t> input; }; } DECLARE_WAYFIRE_PLUGIN((wf::singleton_plugin_t<wf::ipc_plugin_t, false>));
#include <wayfire/singleton-plugin.hpp> #include <wayfire/view.hpp> #include <wayfire/output.hpp> #include <wayfire/workspace-manager.hpp> #include <wayfire/output-layout.hpp> #include <getopt.h> #include "ipc.hpp" extern "C" { #include <wlr/backend/wayland.h> #include <wlr/backend/multi.h> #include <wlr/backend/headless.h> #include <wlr/types/wlr_pointer.h> #include <wlr/types/wlr_keyboard.h> #include <wlr/interfaces/wlr_keyboard.h> #include <wlr/types/wlr_output_layout.h> #include <libevdev/libevdev.h> } #include <wayfire/util/log.hpp> #include <wayfire/core.hpp> static void locate_wayland_backend(wlr_backend *backend, void *data) { if (wlr_backend_is_wl(backend)) { wlr_backend **result = (wlr_backend**)data; *result = backend; } } namespace wf { static nlohmann::json geometry_to_json(wf::geometry_t g) { nlohmann::json j; j["x"] = g.x; j["y"] = g.y; j["width"] = g.width; j["height"] = g.height; return j; } static std::string layer_to_string(uint32_t layer) { switch (layer) { case LAYER_BACKGROUND: return "background"; case LAYER_BOTTOM: return "bottom"; case LAYER_WORKSPACE: return "workspace"; case LAYER_TOP: return "top"; case LAYER_UNMANAGED: return "unmanaged"; case LAYER_LOCK: return "lock"; case LAYER_DESKTOP_WIDGET: return "dew"; case LAYER_MINIMIZED: return "minimized"; default: break; } return "none"; } class headless_input_backend_t { public: wlr_backend *backend; wlr_input_device *pointer; wlr_input_device *keyboard; headless_input_backend_t() { auto& core = wf::get_core(); backend = wlr_headless_backend_create(core.display); wlr_multi_backend_add(core.backend, backend); wlr_backend_start(backend); pointer = wlr_headless_add_input_device(backend, WLR_INPUT_DEVICE_POINTER); keyboard = wlr_headless_add_input_device(backend, WLR_INPUT_DEVICE_KEYBOARD); } ~headless_input_backend_t() { auto& core = wf::get_core(); wlr_multi_backend_remove(core.backend, backend); wlr_backend_destroy(backend); } void do_key(uint32_t key, wl_keyboard_key_state state) { wlr_event_keyboard_key ev; ev.keycode = key; ev.state = state; ev.update_state = true; ev.time_msec = get_current_time(); wlr_keyboard_notify_key(keyboard->keyboard, &ev); } void do_button(uint32_t button, wlr_button_state state) { wlr_event_pointer_button ev; ev.device = pointer; ev.button = button; ev.state = state; ev.time_msec = get_current_time(); wl_signal_emit(&pointer->pointer->events.button, &ev); } void do_motion(double x, double y) { auto layout = wf::get_core().output_layout->get_handle(); auto box = wlr_output_layout_get_box(layout, NULL); wlr_event_pointer_motion_absolute ev; ev.device = pointer; ev.time_msec = get_current_time(); ev.x = 1.0 * (x - box->x) / box->width; ev.y = 1.0 * (y - box->y) / box->height; wl_signal_emit(&pointer->pointer->events.motion_absolute, &ev); } headless_input_backend_t(const headless_input_backend_t&) = delete; headless_input_backend_t(headless_input_backend_t&&) = delete; headless_input_backend_t& operator =(const headless_input_backend_t&) = delete; headless_input_backend_t& operator =(headless_input_backend_t&&) = delete; }; static inline nlohmann::json get_ok() { return nlohmann::json{ {"result", "ok"} }; } static inline nlohmann::json get_error(std::string msg) { return nlohmann::json{ {"error", std::string(msg)} }; } class ipc_plugin_t { public: ipc_plugin_t() { input = std::make_unique<headless_input_backend_t>(); char *pre_socket = getenv("_WAYFIRE_SOCKET"); const auto& dname = wf::get_core().wayland_display; std::string socket = pre_socket ?: "/tmp/wayfire-" + dname + ".socket"; setenv("WAYFIRE_SOCKET", socket.c_str(), 1); server = std::make_unique<ipc::server_t>(socket); server->register_method("core/list_views", list_views); server->register_method("core/create_wayland_output", create_wayland_output); server->register_method("core/feed_key", feed_key); } using method_t = ipc::server_t::method_cb; method_t list_views = [] (nlohmann::json) { auto response = nlohmann::json::array(); for (auto& view : wf::get_core().get_all_views()) { nlohmann::json v; v["title"] = view->get_title(); v["app-id"] = view->get_app_id(); v["geometry"] = geometry_to_json(view->get_wm_geometry()); v["base-geometry"] = geometry_to_json(view->get_output_geometry()); v["state"] = { {"tiled", view->tiled_edges}, {"fullscreen", view->fullscreen}, {"minimized", view->minimized}, }; uint32_t layer = -1; if (view->get_output()) { layer = view->get_output()->workspace->get_view_layer(view); } v["layer"] = layer_to_string(layer); response.push_back(v); } return response; }; method_t create_wayland_output = [] (nlohmann::json) { auto backend = wf::get_core().backend; wlr_backend *wayland_backend = NULL; wlr_multi_for_each_backend(backend, locate_wayland_backend, &wayland_backend); if (!wayland_backend) { return get_error("Wayfire is not running in nested wayland mode!"); } wlr_wl_output_create(wayland_backend); return get_ok(); }; struct key_t { bool modifier; int code; }; std::variant<key_t, std::string> parse_key(nlohmann::json data) { if (!data.count("combo") || !data["combo"].is_string()) { return std::string("Missing or wrong json type for `combo`!"); } std::string combo = data["combo"]; if (combo.size() < 4) { return std::string("Missing or wrong json type for `combo`!"); } // Check super modifier bool modifier = false; if (combo.substr(0, 2) == "S-") { modifier = true; combo = combo.substr(2); } int key = libevdev_event_code_from_name(EV_KEY, combo.c_str()); if (key == -1) { return std::string("Failed to parse combo \"" + combo + "\""); } return key_t{modifier, key}; } method_t feed_key = [=] (nlohmann::json data) { auto result = parse_key(data); auto key = std::get_if<key_t>(&result); if (!key) { return get_error(std::get<std::string>(result)); } if (key->modifier) { input->do_key(KEY_LEFTMETA, WL_KEYBOARD_KEY_STATE_PRESSED); } input->do_key(key->code, WL_KEYBOARD_KEY_STATE_PRESSED); input->do_key(key->code, WL_KEYBOARD_KEY_STATE_RELEASED); if (key->modifier) { input->do_key(KEY_LEFTMETA, WL_KEYBOARD_KEY_STATE_RELEASED); } return get_ok(); }; method_t feed_button = [=] (nlohmann::json data) { auto result = parse_key(data); auto button = std::get_if<key_t>(&result); if (!button) { return get_error(std::get<std::string>(result)); } if (!data.count("mode") || !data["mode"].is_string()) { return get_error("No mode specified"); } auto mode = data["mode"]; if ((mode == "press") || (mode == "full")) { if (button->modifier) { input->do_key(KEY_LEFTMETA, WL_KEYBOARD_KEY_STATE_PRESSED); } input->do_button(button->code, WLR_BUTTON_PRESSED); } if ((mode == "release") || (mode == "full")) { input->do_button(button->code, WLR_BUTTON_RELEASED); if (button->modifier) { input->do_key(KEY_LEFTMETA, WL_KEYBOARD_KEY_STATE_RELEASED); } } return get_ok(); }; method_t move_cursor = [=] (nlohmann::json data) { if (!data.count("x") || !data.count("y") || !data["x"].is_number() || !data["y"].is_number()) { return get_error("Move cursor needs double x/y arguments"); } double x = data["x"]; double y = data["y"]; input->do_motion(x, y); return get_ok(); }; std::unique_ptr<ipc::server_t> server; std::unique_ptr<headless_input_backend_t> input; }; } DECLARE_WAYFIRE_PLUGIN((wf::singleton_plugin_t<wf::ipc_plugin_t, false>));
add command to move cursor
stipc: add command to move cursor
C++
mit
ammen99/wayfire,ammen99/wayfire
c761da7bd373e9007413ebcf9033d4008113e4db
folly/experimental/coro/test/InlineTaskTest.cpp
folly/experimental/coro/test/InlineTaskTest.cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/Portability.h> #if FOLLY_HAS_COROUTINES #include <folly/experimental/coro/BlockingWait.h> #include <folly/experimental/coro/detail/InlineTask.h> #include <folly/portability/GTest.h> #include <tuple> template <typename T> using InlineTask = folly::coro::detail::InlineTask<T>; class InlineTaskTest : public testing::Test {}; TEST_F(InlineTaskTest, CallVoidTaskWithoutAwaitingNeverRuns) { bool hasStarted = false; auto f = [&]() -> InlineTask<void> { hasStarted = true; co_return; }; { auto task = f(); EXPECT_FALSE(hasStarted); } EXPECT_FALSE(hasStarted); } TEST_F(InlineTaskTest, CallValueTaskWithoutAwaitingNeverRuns) { bool hasStarted = false; auto f = [&]() -> InlineTask<int> { hasStarted = true; co_return 123; }; { auto task = f(); EXPECT_FALSE(hasStarted); } EXPECT_FALSE(hasStarted); } TEST_F(InlineTaskTest, CallRefTaskWithoutAwaitingNeverRuns) { bool hasStarted = false; int value; auto f = [&]() -> InlineTask<int&> { hasStarted = true; co_return value; }; { auto task = f(); EXPECT_FALSE(hasStarted); } EXPECT_FALSE(hasStarted); } TEST_F(InlineTaskTest, SimpleVoidTask) { bool hasRun = false; auto f = [&]() -> InlineTask<void> { hasRun = true; co_return; }; auto t = f(); EXPECT_FALSE(hasRun); folly::coro::blockingWait(std::move(t)); EXPECT_TRUE(hasRun); } TEST_F(InlineTaskTest, SimpleValueTask) { bool hasRun = false; auto f = [&]() -> InlineTask<int> { hasRun = true; co_return 42; }; auto t = f(); EXPECT_FALSE(hasRun); EXPECT_EQ(42, folly::coro::blockingWait(std::move(t))); EXPECT_TRUE(hasRun); } TEST_F(InlineTaskTest, SimpleRefTask) { bool hasRun = false; auto f = [&]() -> InlineTask<bool&> { hasRun = true; co_return hasRun; }; auto t = f(); EXPECT_FALSE(hasRun); auto& result = folly::coro::blockingWait(std::move(t)); EXPECT_TRUE(hasRun); EXPECT_EQ(&hasRun, &result); } struct MoveOnlyType { int value_; explicit MoveOnlyType(int value) noexcept : value_(value) {} MoveOnlyType(MoveOnlyType&& other) noexcept : value_(std::exchange(other.value_, -1)) {} MoveOnlyType& operator=(MoveOnlyType&& other) noexcept { value_ = std::exchange(other.value_, -1); return *this; } ~MoveOnlyType() { value_ = -2; } }; struct TypeWithImplicitSingleValueConstructor { float value_; /* implicit */ TypeWithImplicitSingleValueConstructor(float x) : value_(x) {} }; TEST_F(InlineTaskTest, ReturnValueWithInitializerListSyntax) { auto f = []() -> InlineTask<TypeWithImplicitSingleValueConstructor> { co_return{1.23f}; }; auto result = folly::coro::blockingWait(f()); EXPECT_EQ(1.23f, result.value_); } struct TypeWithImplicitMultiValueConstructor { std::string s_; float x_; /* implicit */ TypeWithImplicitMultiValueConstructor( std::string s, float x) noexcept : s_(s), x_(x) {} }; TEST_F(InlineTaskTest, ReturnValueWithInitializerListSyntax2) { auto f = []() -> InlineTask<TypeWithImplicitMultiValueConstructor> { #if 0 // Under clang: // error: cannot compile this scalar expression yet. co_return{"hello", 3.1415f}; #else co_return TypeWithImplicitMultiValueConstructor{"hello", 3.1415f}; #endif }; auto result = folly::coro::blockingWait(f()); EXPECT_EQ("hello", result.s_); EXPECT_EQ(3.1415f, result.x_); } TEST_F(InlineTaskTest, TaskOfMoveOnlyType) { auto f = []() -> InlineTask<MoveOnlyType> { co_return MoveOnlyType{42}; }; auto x = folly::coro::blockingWait(f()); EXPECT_EQ(42, x.value_); bool executed = false; auto g = [&]() -> InlineTask<void> { auto result = co_await f(); EXPECT_EQ(42, result.value_); executed = true; }; folly::coro::blockingWait(g()); EXPECT_TRUE(executed); } TEST_F(InlineTaskTest, MoveOnlyTypeNRVO) { auto f = []() -> InlineTask<MoveOnlyType> { MoveOnlyType x{10}; co_return x; }; auto x = folly::coro::blockingWait(f()); EXPECT_EQ(10, x.value_); } TEST_F(InlineTaskTest, ReturnLvalueReference) { int value = 0; auto f = [&]() -> InlineTask<int&> { co_return value; }; auto& x = folly::coro::blockingWait(f()); EXPECT_EQ(&value, &x); } struct MyException : std::exception {}; TEST_F(InlineTaskTest, ExceptionsPropagateFromVoidTask) { auto f = []() -> InlineTask<void> { co_await std::experimental::suspend_never{}; throw MyException{}; }; EXPECT_THROW(folly::coro::blockingWait(f()), MyException); } TEST_F(InlineTaskTest, ExceptionsPropagateFromValueTask) { auto f = []() -> InlineTask<int> { co_await std::experimental::suspend_never{}; throw MyException{}; }; EXPECT_THROW(folly::coro::blockingWait(f()), MyException); } TEST_F(InlineTaskTest, ExceptionsPropagateFromRefTask) { auto f = []() -> InlineTask<int&> { co_await std::experimental::suspend_never{}; throw MyException{}; }; EXPECT_THROW(folly::coro::blockingWait(f()), MyException); } struct ThrowingCopyConstructor { ThrowingCopyConstructor() noexcept = default; [[noreturn]] ThrowingCopyConstructor(const ThrowingCopyConstructor&) noexcept( false) { throw MyException{}; } ThrowingCopyConstructor& operator=(const ThrowingCopyConstructor&) = delete; }; TEST_F(InlineTaskTest, ExceptionsPropagateFromReturnValueConstructor) { auto f = []() -> InlineTask<ThrowingCopyConstructor> { co_return{}; }; EXPECT_THROW(folly::coro::blockingWait(f()), MyException); } InlineTask<void> recursiveTask(int depth) { if (depth > 0) { co_await recursiveTask(depth - 1); } } TEST_F(InlineTaskTest, DeepRecursionDoesntStackOverflow) { folly::coro::blockingWait(recursiveTask(500000)); } InlineTask<int> recursiveValueTask(int depth) { if (depth > 0) { co_return co_await recursiveValueTask(depth - 1) + 1; } co_return 0; } TEST_F(InlineTaskTest, DeepRecursionOfValueTaskDoesntStackOverflow) { EXPECT_EQ(500000, folly::coro::blockingWait(recursiveValueTask(500000))); } InlineTask<void> recursiveThrowingTask(int depth) { if (depth > 0) { co_await recursiveThrowingTask(depth - 1); } throw MyException{}; } TEST_F(InlineTaskTest, DeepRecursionOfExceptions) { EXPECT_THROW( folly::coro::blockingWait(recursiveThrowingTask(50000)), MyException); } #endif
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/Portability.h> #if FOLLY_HAS_COROUTINES #include <folly/experimental/coro/BlockingWait.h> #include <folly/experimental/coro/detail/InlineTask.h> #include <folly/portability/GTest.h> #include <tuple> template <typename T> using InlineTask = folly::coro::detail::InlineTask<T>; class InlineTaskTest : public testing::Test {}; TEST_F(InlineTaskTest, CallVoidTaskWithoutAwaitingNeverRuns) { bool hasStarted = false; auto f = [&]() -> InlineTask<void> { hasStarted = true; co_return; }; { auto task = f(); EXPECT_FALSE(hasStarted); } EXPECT_FALSE(hasStarted); } TEST_F(InlineTaskTest, CallValueTaskWithoutAwaitingNeverRuns) { bool hasStarted = false; auto f = [&]() -> InlineTask<int> { hasStarted = true; co_return 123; }; { auto task = f(); EXPECT_FALSE(hasStarted); } EXPECT_FALSE(hasStarted); } TEST_F(InlineTaskTest, CallRefTaskWithoutAwaitingNeverRuns) { bool hasStarted = false; int value; auto f = [&]() -> InlineTask<int&> { hasStarted = true; co_return value; }; { auto task = f(); EXPECT_FALSE(hasStarted); } EXPECT_FALSE(hasStarted); } TEST_F(InlineTaskTest, SimpleVoidTask) { bool hasRun = false; auto f = [&]() -> InlineTask<void> { hasRun = true; co_return; }; auto t = f(); EXPECT_FALSE(hasRun); folly::coro::blockingWait(std::move(t)); EXPECT_TRUE(hasRun); } TEST_F(InlineTaskTest, SimpleValueTask) { bool hasRun = false; auto f = [&]() -> InlineTask<int> { hasRun = true; co_return 42; }; auto t = f(); EXPECT_FALSE(hasRun); EXPECT_EQ(42, folly::coro::blockingWait(std::move(t))); EXPECT_TRUE(hasRun); } TEST_F(InlineTaskTest, SimpleRefTask) { bool hasRun = false; auto f = [&]() -> InlineTask<bool&> { hasRun = true; co_return hasRun; }; auto t = f(); EXPECT_FALSE(hasRun); auto& result = folly::coro::blockingWait(std::move(t)); EXPECT_TRUE(hasRun); EXPECT_EQ(&hasRun, &result); } struct MoveOnlyType { int value_; explicit MoveOnlyType(int value) noexcept : value_(value) {} MoveOnlyType(MoveOnlyType&& other) noexcept : value_(std::exchange(other.value_, -1)) {} MoveOnlyType& operator=(MoveOnlyType&& other) noexcept { value_ = std::exchange(other.value_, -1); return *this; } ~MoveOnlyType() { value_ = -2; } }; struct TypeWithImplicitSingleValueConstructor { float value_; /* implicit */ TypeWithImplicitSingleValueConstructor(float x) : value_(x) {} }; TEST_F(InlineTaskTest, ReturnValueWithInitializerListSyntax) { auto f = []() -> InlineTask<TypeWithImplicitSingleValueConstructor> { co_return{1.23f}; }; auto result = folly::coro::blockingWait(f()); EXPECT_EQ(1.23f, result.value_); } struct TypeWithImplicitMultiValueConstructor { std::string s_; float x_; /* implicit */ TypeWithImplicitMultiValueConstructor( std::string s, float x) noexcept : s_(s), x_(x) {} }; TEST_F(InlineTaskTest, ReturnValueWithInitializerListSyntax2) { auto f = []() -> InlineTask<TypeWithImplicitMultiValueConstructor> { co_return{"hello", 3.1415f}; }; auto result = folly::coro::blockingWait(f()); EXPECT_EQ("hello", result.s_); EXPECT_EQ(3.1415f, result.x_); } TEST_F(InlineTaskTest, TaskOfMoveOnlyType) { auto f = []() -> InlineTask<MoveOnlyType> { co_return MoveOnlyType{42}; }; auto x = folly::coro::blockingWait(f()); EXPECT_EQ(42, x.value_); bool executed = false; auto g = [&]() -> InlineTask<void> { auto result = co_await f(); EXPECT_EQ(42, result.value_); executed = true; }; folly::coro::blockingWait(g()); EXPECT_TRUE(executed); } TEST_F(InlineTaskTest, MoveOnlyTypeNRVO) { auto f = []() -> InlineTask<MoveOnlyType> { MoveOnlyType x{10}; co_return x; }; auto x = folly::coro::blockingWait(f()); EXPECT_EQ(10, x.value_); } TEST_F(InlineTaskTest, ReturnLvalueReference) { int value = 0; auto f = [&]() -> InlineTask<int&> { co_return value; }; auto& x = folly::coro::blockingWait(f()); EXPECT_EQ(&value, &x); } struct MyException : std::exception {}; TEST_F(InlineTaskTest, ExceptionsPropagateFromVoidTask) { auto f = []() -> InlineTask<void> { co_await std::experimental::suspend_never{}; throw MyException{}; }; EXPECT_THROW(folly::coro::blockingWait(f()), MyException); } TEST_F(InlineTaskTest, ExceptionsPropagateFromValueTask) { auto f = []() -> InlineTask<int> { co_await std::experimental::suspend_never{}; throw MyException{}; }; EXPECT_THROW(folly::coro::blockingWait(f()), MyException); } TEST_F(InlineTaskTest, ExceptionsPropagateFromRefTask) { auto f = []() -> InlineTask<int&> { co_await std::experimental::suspend_never{}; throw MyException{}; }; EXPECT_THROW(folly::coro::blockingWait(f()), MyException); } struct ThrowingCopyConstructor { ThrowingCopyConstructor() noexcept = default; [[noreturn]] ThrowingCopyConstructor(const ThrowingCopyConstructor&) noexcept( false) { throw MyException{}; } ThrowingCopyConstructor& operator=(const ThrowingCopyConstructor&) = delete; }; TEST_F(InlineTaskTest, ExceptionsPropagateFromReturnValueConstructor) { auto f = []() -> InlineTask<ThrowingCopyConstructor> { co_return{}; }; EXPECT_THROW(folly::coro::blockingWait(f()), MyException); } InlineTask<void> recursiveTask(int depth) { if (depth > 0) { co_await recursiveTask(depth - 1); } } TEST_F(InlineTaskTest, DeepRecursionDoesntStackOverflow) { folly::coro::blockingWait(recursiveTask(500000)); } InlineTask<int> recursiveValueTask(int depth) { if (depth > 0) { co_return co_await recursiveValueTask(depth - 1) + 1; } co_return 0; } TEST_F(InlineTaskTest, DeepRecursionOfValueTaskDoesntStackOverflow) { EXPECT_EQ(500000, folly::coro::blockingWait(recursiveValueTask(500000))); } InlineTask<void> recursiveThrowingTask(int depth) { if (depth > 0) { co_await recursiveThrowingTask(depth - 1); } throw MyException{}; } TEST_F(InlineTaskTest, DeepRecursionOfExceptions) { EXPECT_THROW( folly::coro::blockingWait(recursiveThrowingTask(50000)), MyException); } #endif
Remove workaround for co_return with uniform initializer
Remove workaround for co_return with uniform initializer Summary: This workaround is no longer necessary for a Clang that includes patch https://reviews.llvm.org/D76118. Reviewed By: ispeters, lewissbaker Differential Revision: D20486353 fbshipit-source-id: cab137ed557ba8aa6ec86ec7011cc4fc7c46fe82
C++
apache-2.0
facebook/folly,facebook/folly,facebook/folly,facebook/folly,facebook/folly
c01c4038cb41bbb43055ef2962b2e93926b12144
JContainers/src/collections/dyn_form_watcher.hpp
JContainers/src/collections/dyn_form_watcher.hpp
#pragma once #include <boost/smart_ptr/make_shared_object.hpp> #include <boost/range.hpp> //#include <boost/algorithm/string/join.hpp> #include <assert.h> #include <inttypes.h> #include <map> #include <tuple> #include <mutex> //#include "skse/GameForms.h" //#include "skse/PapyrusVM.h" #include "skse/skse.h" #include "util/stl_ext.h" #include "util/util.h" #include "collections/form_handling.h" #include "collections/dyn_form_watcher.h" BOOST_CLASS_VERSION(collections::form_watching::form_ref, 2); namespace collections { namespace form_watching { namespace fh = form_handling; template<class ...Params> inline void log(const char* fmt, Params&& ...ps) { JC_log(fmt, std::forward<Params ...>(ps ...)); } class form_entry : public boost::noncopyable { FormId _handle = FormId::Zero; std::atomic<bool> _deleted = false; // to not release the handle if the handle can't be retained (for ex. handle's object was not loaded) bool _is_handle_retained = false; public: form_entry(FormId handle, bool deleted, bool handle_was_retained) : _handle(handle) , _deleted(deleted) , _is_handle_retained(handle_was_retained) {} form_entry() = default; static form_entry_ref make(FormId handle) { //log("form_entry retains %X", handle); return boost::make_shared<form_entry>( handle, false, skse::try_retain_handle(handle)); } static form_entry_ref make_expired(FormId handle) { return boost::make_shared<form_entry>(handle, true, false); } ~form_entry() { if (!is_deleted() && _is_handle_retained) { //log("form_entry releases %X", _handle); skse::release_handle(_handle); } } FormId id() const { return _handle; } bool is_deleted() const { return _deleted.load(std::memory_order_acquire); } void set_deleted() { _deleted.store(true, std::memory_order_release); } bool u_is_deleted() const { return _deleted._My_val; } void u_set_deleted() { _deleted._My_val = true; } friend class boost::serialization::access; BOOST_SERIALIZATION_SPLIT_MEMBER(); template<class Archive> void save(Archive & ar, const unsigned int version) const { ar << util::to_integral_ref(_handle); ar << _deleted._My_val; } template<class Archive> void load(Archive & ar, const unsigned int version) { ar >> util::to_integral_ref(_handle); ar >> _deleted._My_val; if (u_is_deleted() == false) { _handle = skse::resolve_handle(_handle); if (_handle != FormId::Zero) { _is_handle_retained = skse::try_retain_handle(_handle); } else { u_set_deleted(); } } } }; void form_observer::u_remove_expired_forms() { util::tree_erase_if(_watched_forms, [](const watched_forms_t::value_type& pair) { return pair.second.expired(); }); } /*form_observer::form_observer() { _is_inside_unsafe_func._My_flag = false; }*/ using spinlock_pool = boost::detail::spinlock_pool < 'DyFW' > ; void form_observer::on_form_deleted(FormHandle handle) { // already failed, there are plenty of any kind of objects that are deleted every moment, even during initial splash screen //jc_assert_msg(form_handling::is_static((FormId)handle) == false, //"If failed, then there is static form destruction event too? fId %" PRIX64, handle); if (!fh::is_form_handle(handle)) { return; } // to test whether static form gets ever destroyed or not //jc_assert(form_handling::is_static((FormId)handle) == false); ///log("on_form_deleted: %" PRIX64, handle); auto formId = fh::form_handle_to_id(handle); { read_lock r(_mutex); auto itr = _watched_forms.find(formId); if (itr != _watched_forms.end()) { // read and write std::lock_guard<boost::detail::spinlock> guard{ spinlock_pool::spinlock_for(&itr->second) }; auto watched = itr->second.lock(); if (watched) { watched->set_deleted(); log("flag form-entry %" PRIX32 " as deleted", formId); } itr->second.reset(); } } } form_entry_ref form_observer::watch_form(FormId fId) { if (fId == FormId::Zero) { return nullptr; } log("watching form %X", fId); auto get_or_assign = [fId](boost::weak_ptr<form_entry> & watched_weak) -> form_entry_ref { std::lock_guard<boost::detail::spinlock> guard{ spinlock_pool::spinlock_for(&watched_weak) }; auto watched = watched_weak.lock(); if (!watched) { // what if two threads trying assign?? // both threads are here or one is here and another performing @on_form_deleted func. watched_weak = watched = form_entry::make(fId); } return watched; }; { read_lock r(_mutex); auto itr = _watched_forms.find(fId); if (itr != _watched_forms.end()) { return get_or_assign(itr->second); } } { write_lock r(_mutex); auto itr = _watched_forms.find(fId); if (itr != _watched_forms.end()) { return get_or_assign(itr->second); } else { auto watched = form_entry::make(fId); _watched_forms[fId] = watched; return watched; } } } struct lock_or_fail { std::atomic_flag& flag; explicit lock_or_fail(std::atomic_flag& flg) : flag(flg) { jc_assert_msg(false == flg.test_and_set(std::memory_order_acquire), "My dyn_form_watcher test has failed? Report this please"); } ~lock_or_fail() { flag.clear(std::memory_order_release); } }; //////////////////////////////////////// form_ref::form_ref(FormId id, form_observer& watcher) : _watched_form(watcher.watch_form(id)) { } form_ref::form_ref(const TESForm& form, form_observer& watcher) : _watched_form(watcher.watch_form(util::to_enum<FormId>(form.formID))) { } bool form_ref::is_not_expired() const { return _watched_form && !_watched_form->is_deleted(); } form_ref::form_ref(FormId oldId, form_observer& watcher, load_old_id_t) : _watched_form(watcher.watch_form(skse::resolve_handle(oldId))) { } form_ref form_ref::make_expired(FormId formId) { auto entry = form_entry::make_expired(formId); return form_ref{ entry }; } ////////////////// FormId form_ref::get() const { return is_not_expired() ? _watched_form->id() : FormId::Zero; } FormId form_ref::get_raw() const { return _watched_form ? _watched_form->id() : FormId::Zero; } template<class Archive> void form_ref::save(Archive & ar, const unsigned int version) const { // optimization: the form was deleted - write null instead if (is_not_expired()) ar << _watched_form; else { decltype(_watched_form) fake; ar << fake; } } template<class Archive> void form_ref::load(Archive & ar, const unsigned int version) { switch (version) { case 0: {// v3.3 alpha-1 format FormId oldId = FormId::Zero; ar >> oldId; FormId id = skse::resolve_handle(oldId); bool expired = false; ar >> expired; if (!expired) { auto watcher = hack::iarchive_with_blob::from_base_get<tes_context>(ar).form_watcher.get(); _watched_form = watcher->watch_form(id); } break; } case 1: { // Remove this case !!! This format wasn't ever published FormId oldId = FormId::Zero; ar >> oldId; FormId id = skse::resolve_handle(oldId); bool expired = false; ar >> expired; if (!expired) { ar >> _watched_form; } else { auto watcher = hack::iarchive_with_blob::from_base_get<tes_context>(ar).form_watcher.get(); _watched_form = watcher->watch_form(id); } break; } case 2: ar >> _watched_form; break; default: assert(false); break; } } namespace tests { namespace bs = boost; TEST(form_watching, simple){ form_ref id; EXPECT_TRUE(!id); EXPECT_TRUE(id.get() == FormId::Zero); EXPECT_TRUE(id.get_raw() == FormId::Zero); } TEST(form_watching, simple_2){ const auto fid = util::to_enum<FormId>(0xff000014); form_observer watcher; form_ref id{ fid, watcher }; EXPECT_FALSE(!id); EXPECT_TRUE(id.get() == fid); EXPECT_TRUE(id.get_raw() == fid); { form_ref copy = id; EXPECT_FALSE(!copy); EXPECT_TRUE(copy.get() == fid); EXPECT_TRUE(copy.get_raw() == fid); } } /* TEST(form_observer, u_remove_expired_forms){ form_observer watcher; const auto fid = util::to_enum<FormId>(0xff000014); auto entry = watcher.watch_form(fid); EXPECT_TRUE(watcher.u_forms_count() == 1); EXPECT_NOT_NIL(entry.get()); watcher.on_form_deleted(fh::form_id_to_handle(fid)); watcher.u_remove_expired_forms(); EXPECT_TRUE(watcher.u_forms_count() == 0); EXPECT_TRUE(entry->is_deleted()); }*/ TEST(form_watching, bug_1) { const auto fid = util::to_enum<FormId>(0x14); form_observer watcher; form_ref non_expired{ fid, watcher }; std::vector<form_ref> forms = { form_ref::make_expired(fid) }; EXPECT_FALSE(std::find(forms.begin(), forms.end(), non_expired) != forms.end()); // had to be EXPECT_FALSE } template<class T, class V> bool contains(T&& cnt, V&& value) { return cnt.find(value) != cnt.end(); } TEST(form_watching, bug_2) { const auto fid = util::to_enum<FormId>(0x14); form_observer watcher; form_ref non_expired{ fid, watcher }; std::map<form_ref, int> forms = { { form_ref::make_expired(fid), 0 } }; EXPECT_FALSE( contains(forms, non_expired) ); // had to be EXPECT_FALSE } TEST(form_watching, bug_3) { const auto fid = util::to_enum<FormId>(0x14); form_observer watcher; form_ref non_expired{ fid, watcher }; auto expired = form_ref::make_expired(fid); std::map<form_ref, int> forms = { { non_expired, 0 } }; EXPECT_FALSE(contains(forms, expired)); // had to be EXPECT_FALSE } TEST(form_watching, bug_4) { const auto fid = util::to_enum<FormId>(0xff000014); const auto fhid = fh::form_id_to_handle(fid); form_observer watcher; std::map<form_ref, int> forms = { { form_ref{ fid, watcher }, 0 } }; watcher.on_form_deleted(fhid); EXPECT_TRUE(forms.begin()->first.is_expired()); forms[form_ref{ fid, watcher }] = 0; EXPECT_TRUE(forms.size() == 2); // one of the keys should be non-expired EXPECT_TRUE(forms.begin()->first.is_not_expired() != (++forms.begin())->first.is_not_expired()); } TEST(form_watching, dynamic_form_id){ const auto fid = util::to_enum<FormId>(0xff000014); const auto fhid = fh::form_id_to_handle(fid); // EXPECT_TRUE(fh::is_static(fid) == false); form_observer watcher; form_ref id{ fid, watcher }; form_ref id2{ fid, watcher }; auto expectNotExpired = [&](const form_ref& id) { EXPECT_TRUE(id.is_not_expired()); EXPECT_TRUE(id.get() == fid); }; auto expectExpired = [&](const form_ref& id) { EXPECT_FALSE(id.is_not_expired()); EXPECT_TRUE(id.get() == FormId::Zero); EXPECT_TRUE(id.get_raw() == fid); }; expectNotExpired(id); expectNotExpired(id2); watcher.on_form_deleted(fhid); expectExpired(id); expectExpired(id2); } } } }
#pragma once #include <boost/smart_ptr/make_shared_object.hpp> #include <boost/range.hpp> //#include <boost/algorithm/string/join.hpp> #include <assert.h> #include <inttypes.h> #include <map> #include <tuple> #include <mutex> //#include "skse/GameForms.h" //#include "skse/PapyrusVM.h" #include "skse/skse.h" #include "util/stl_ext.h" #include "util/util.h" #include "collections/form_handling.h" #include "collections/dyn_form_watcher.h" BOOST_CLASS_VERSION(collections::form_watching::form_ref, 2); namespace collections { namespace form_watching { namespace fh = form_handling; template<class ...Params> inline void log(const char* fmt, Params&& ...ps) { JC_log(fmt, std::forward<Params ...>(ps ...)); } class form_entry : public boost::noncopyable { FormId _handle = FormId::Zero; std::atomic<bool> _deleted = false; // to not release the handle if the handle can't be retained (for ex. handle's object was not loaded) bool _is_handle_retained = false; public: form_entry(FormId handle, bool deleted, bool handle_was_retained) : _handle(handle) , _deleted(deleted) , _is_handle_retained(handle_was_retained) {} form_entry() = default; static form_entry_ref make(FormId handle) { //log("form_entry retains %X", handle); return boost::make_shared<form_entry>( handle, false, skse::try_retain_handle(handle)); } static form_entry_ref make_expired(FormId handle) { return boost::make_shared<form_entry>(handle, true, false); } ~form_entry() { if (!is_deleted() && _is_handle_retained) { //log("form_entry releases %X", _handle); skse::release_handle(_handle); } } FormId id() const { return _handle; } bool is_deleted() const { return _deleted.load(std::memory_order_acquire); } void set_deleted() { _deleted.store(true, std::memory_order_release); } bool u_is_deleted() const { return _deleted._My_val; } void u_set_deleted() { _deleted._My_val = true; } friend class boost::serialization::access; BOOST_SERIALIZATION_SPLIT_MEMBER(); template<class Archive> void save(Archive & ar, const unsigned int version) const { ar << util::to_integral_ref(_handle); ar << _deleted._My_val; } template<class Archive> void load(Archive & ar, const unsigned int version) { ar >> util::to_integral_ref(_handle); ar >> _deleted._My_val; if (u_is_deleted() == false) { _handle = skse::resolve_handle(_handle); if (_handle != FormId::Zero) { _is_handle_retained = skse::try_retain_handle(_handle); } else { u_set_deleted(); } } } }; void form_observer::u_remove_expired_forms() { util::tree_erase_if(_watched_forms, [](const watched_forms_t::value_type& pair) { return pair.second.expired(); }); } /*form_observer::form_observer() { _is_inside_unsafe_func._My_flag = false; }*/ using spinlock_pool = boost::detail::spinlock_pool < 'DyFW' > ; void form_observer::on_form_deleted(FormHandle handle) { // already failed, there are plenty of any kind of objects that are deleted every moment, even during initial splash screen //jc_assert_msg(form_handling::is_static((FormId)handle) == false, //"If failed, then there is static form destruction event too? fId %" PRIX64, handle); if (!fh::is_form_handle(handle)) { return; } // to test whether static form gets ever destroyed or not //jc_assert(form_handling::is_static((FormId)handle) == false); ///log("on_form_deleted: %" PRIX64, handle); auto formId = fh::form_handle_to_id(handle); { read_lock r(_mutex); auto itr = _watched_forms.find(formId); if (itr != _watched_forms.end()) { // read and write std::lock_guard<boost::detail::spinlock> guard{ spinlock_pool::spinlock_for(&itr->second) }; auto watched = itr->second.lock(); if (watched) { watched->set_deleted(); log("flag form-entry %" PRIX32 " as deleted", formId); } itr->second.reset(); } } } form_entry_ref form_observer::watch_form(FormId fId) { if (fId == FormId::Zero) { return nullptr; } log("watching form %X", fId); auto get_or_assign = [fId](boost::weak_ptr<form_entry> & watched_weak) -> form_entry_ref { std::lock_guard<boost::detail::spinlock> guard{ spinlock_pool::spinlock_for(&watched_weak) }; auto watched = watched_weak.lock(); if (!watched) { // what if two threads trying assign?? // both threads are here or one is here and another performing @on_form_deleted func. watched_weak = watched = form_entry::make(fId); } return watched; }; { read_lock r(_mutex); auto itr = _watched_forms.find(fId); if (itr != _watched_forms.end()) { return get_or_assign(itr->second); } } { write_lock r(_mutex); auto itr = _watched_forms.find(fId); if (itr != _watched_forms.end()) { return get_or_assign(itr->second); } else { auto watched = form_entry::make(fId); _watched_forms[fId] = watched; return watched; } } } struct lock_or_fail { std::atomic_flag& flag; explicit lock_or_fail(std::atomic_flag& flg) : flag(flg) { jc_assert_msg(false == flg.test_and_set(std::memory_order_acquire), "My dyn_form_watcher test has failed? Report this please"); } ~lock_or_fail() { flag.clear(std::memory_order_release); } }; //////////////////////////////////////// form_ref::form_ref(FormId id, form_observer& watcher) : _watched_form(watcher.watch_form(id)) { } form_ref::form_ref(const TESForm& form, form_observer& watcher) : _watched_form(watcher.watch_form(util::to_enum<FormId>(form.formID))) { } bool form_ref::is_not_expired() const { return _watched_form && !_watched_form->is_deleted(); } form_ref::form_ref(FormId oldId, form_observer& watcher, load_old_id_t) : _watched_form(watcher.watch_form(skse::resolve_handle(oldId))) { } form_ref form_ref::make_expired(FormId formId) { auto entry = form_entry::make_expired(formId); return form_ref{ entry }; } ////////////////// FormId form_ref::get() const { return is_not_expired() ? _watched_form->id() : FormId::Zero; } FormId form_ref::get_raw() const { return _watched_form ? _watched_form->id() : FormId::Zero; } template<class Archive> void form_ref::save(Archive & ar, const unsigned int version) const { // optimization: the form was deleted - write null instead if (is_not_expired()) ar << _watched_form; else { decltype(_watched_form) fake; ar << fake; } } template<class Archive> void form_ref::load(Archive & ar, const unsigned int version) { switch (version) { case 0: {// v3.3 alpha-1 format FormId oldId = FormId::Zero; ar >> oldId; FormId id = skse::resolve_handle(oldId); bool expired = false; ar >> expired; if (!expired) { auto watcher = hack::iarchive_with_blob::from_base_get<tes_context>(ar).form_watcher.get(); _watched_form = watcher->watch_form(id); } break; } case 1: { // Remove this case !!! This format wasn't ever published FormId oldId = FormId::Zero; ar >> oldId; FormId id = skse::resolve_handle(oldId); bool expired = false; ar >> expired; if (!expired) { ar >> _watched_form; } else { auto watcher = hack::iarchive_with_blob::from_base_get<tes_context>(ar).form_watcher.get(); _watched_form = watcher->watch_form(id); } break; } case 2: ar >> _watched_form; break; default: assert(false); break; } } namespace tests { namespace bs = boost; TEST(form_watching, perft){ form_observer watcher; util::do_with_timing("form_observer performance", [&](){ for (int i = 0; i < 1000000; ++i) { watcher.watch_form(util::to_enum<FormId>(i % 1000)); } }); } TEST(form_watching, simple){ form_ref id; EXPECT_TRUE(!id); EXPECT_TRUE(id.get() == FormId::Zero); EXPECT_TRUE(id.get_raw() == FormId::Zero); } TEST(form_watching, simple_2){ const auto fid = util::to_enum<FormId>(0xff000014); form_observer watcher; form_ref id{ fid, watcher }; EXPECT_FALSE(!id); EXPECT_TRUE(id.get() == fid); EXPECT_TRUE(id.get_raw() == fid); { form_ref copy = id; EXPECT_FALSE(!copy); EXPECT_TRUE(copy.get() == fid); EXPECT_TRUE(copy.get_raw() == fid); } } /* TEST(form_observer, u_remove_expired_forms){ form_observer watcher; const auto fid = util::to_enum<FormId>(0xff000014); auto entry = watcher.watch_form(fid); EXPECT_TRUE(watcher.u_forms_count() == 1); EXPECT_NOT_NIL(entry.get()); watcher.on_form_deleted(fh::form_id_to_handle(fid)); watcher.u_remove_expired_forms(); EXPECT_TRUE(watcher.u_forms_count() == 0); EXPECT_TRUE(entry->is_deleted()); }*/ TEST(form_watching, bug_1) { const auto fid = util::to_enum<FormId>(0x14); form_observer watcher; form_ref non_expired{ fid, watcher }; std::vector<form_ref> forms = { form_ref::make_expired(fid) }; EXPECT_FALSE(std::find(forms.begin(), forms.end(), non_expired) != forms.end()); // had to be EXPECT_FALSE } template<class T, class V> bool contains(T&& cnt, V&& value) { return cnt.find(value) != cnt.end(); } TEST(form_watching, bug_2) { const auto fid = util::to_enum<FormId>(0x14); form_observer watcher; form_ref non_expired{ fid, watcher }; std::map<form_ref, int> forms = { { form_ref::make_expired(fid), 0 } }; EXPECT_FALSE( contains(forms, non_expired) ); // had to be EXPECT_FALSE } TEST(form_watching, bug_3) { const auto fid = util::to_enum<FormId>(0x14); form_observer watcher; form_ref non_expired{ fid, watcher }; auto expired = form_ref::make_expired(fid); std::map<form_ref, int> forms = { { non_expired, 0 } }; EXPECT_FALSE(contains(forms, expired)); // had to be EXPECT_FALSE } TEST(form_watching, bug_4) { const auto fid = util::to_enum<FormId>(0xff000014); const auto fhid = fh::form_id_to_handle(fid); form_observer watcher; std::map<form_ref, int> forms = { { form_ref{ fid, watcher }, 0 } }; watcher.on_form_deleted(fhid); EXPECT_TRUE(forms.begin()->first.is_expired()); forms[form_ref{ fid, watcher }] = 0; EXPECT_TRUE(forms.size() == 2); // one of the keys should be non-expired EXPECT_TRUE(forms.begin()->first.is_not_expired() != (++forms.begin())->first.is_not_expired()); } TEST(form_watching, dynamic_form_id){ const auto fid = util::to_enum<FormId>(0xff000014); const auto fhid = fh::form_id_to_handle(fid); // EXPECT_TRUE(fh::is_static(fid) == false); form_observer watcher; form_ref id{ fid, watcher }; form_ref id2{ fid, watcher }; auto expectNotExpired = [&](const form_ref& id) { EXPECT_TRUE(id.is_not_expired()); EXPECT_TRUE(id.get() == fid); }; auto expectExpired = [&](const form_ref& id) { EXPECT_FALSE(id.is_not_expired()); EXPECT_TRUE(id.get() == FormId::Zero); EXPECT_TRUE(id.get_raw() == fid); }; expectNotExpired(id); expectNotExpired(id2); watcher.on_form_deleted(fhid); expectExpired(id); expectExpired(id2); } } } }
test form observer performance
test form observer performance
C++
mit
SilverIce/JContainers,SilverIce/JContainers,SilverIce/JContainers,SilverIce/JContainers,SilverIce/JContainers,SilverIce/JContainers
58b7bcebb739ca0714e9b6012f14ca63240885d8
Sources/Interface/Interface.cpp
Sources/Interface/Interface.cpp
/************************************************************************* > File Name: Interface.cpp > Project Name: Hearthstone++ > Author: Young-Joong Kim > Purpose: Interface for Hearthstone Game Agent > Created Time: 2017/10/24 > Copyright (c) 2017, Young-Joong Kim *************************************************************************/ #include <Interface/Interface.h> namespace Hearthstonepp { GameInterface::GameInterface(GameAgent& agent) : m_agent(agent) , m_bufferCapacity(agent.GetBufferCapacity()) { m_buffer = new BYTE[m_bufferCapacity]; } GameResult GameInterface::StartGame() { GameResult result; std::thread* at = m_agent.StartAgent(result); while (true) { int result = HandleMessage(); if (result == HANDLE_STOP) break; } at->join(); // join agent thread delete at; return result; } int GameInterface::HandleMessage() { m_agent.ReadBuffer(m_buffer, m_bufferCapacity); if (m_buffer[0] == static_cast<BYTE>(Step::FINAL_GAMEOVER)) { return HANDLE_STOP; } else if (m_handler.find(m_buffer[0]) != m_handler.end()) { m_handler[m_buffer[0]](*this); } return HANDLE_CONTINUE; } void GameInterface::LogWriter(std::string& name, std::string message) { std::cout << "[*] " << name << " : " << message << std::endl; } void GameInterface::BeginFirst() { BeginFirstStructure* data = (BeginFirstStructure*)m_buffer; m_users[0] = data->userFirst; m_users[1] = data->userLast; LogWriter(m_users[0], "Begin First"); LogWriter(m_users[1], "Begin Last"); } void GameInterface::BeginShuffle() { BeginShuffleStructure* data = (BeginShuffleStructure*)m_buffer; LogWriter(m_users[data->userID], "Begin Shuffle"); } void GameInterface::BeginDraw() { DrawStructure* data = (DrawStructure*)m_buffer; LogWriter(m_users[data->userID], "Begin Draw"); for (int i = 0; i < NUM_BEGIN_DRAW; ++i) { std::cout << "[" << data->cards[i]->GetCardName() << "] "; } std::cout << std::endl; } void GameInterface::BeginMulligan() { BeginMulliganStructure* data = (BeginMulliganStructure*)m_buffer; LogWriter(m_users[data->userID], "Begin Mulligan"); int numMulligan; while (true) { std::cout << "[*] How many cards to mulligan ? (0 ~ 3) "; std::cin >> numMulligan; if (numMulligan >= 0 && numMulligan <= NUM_BEGIN_DRAW) { break; } } BYTE mulligan[NUM_BEGIN_DRAW] = { 0, }; for (int i = 0; i < numMulligan; ++i) { while (true) { int index = 0; std::cout << "[*] Input card index " << i+1 << " (0 ~ 2) : "; std::cin >> index; if (index >= 0 && index <= NUM_BEGIN_DRAW - 1) { mulligan[i] = index; break; } } } m_agent.WriteBuffer(mulligan, numMulligan); // send index to agent m_agent.ReadBuffer(m_buffer, sizeof(DrawStructure)); // get new card data LogWriter(m_users[data->userID], "Mulligan Result"); DrawStructure* draw = (DrawStructure*)m_buffer; for (int i = 0; i < NUM_BEGIN_DRAW; ++i) { std::cout << "[" << draw->cards[i]->GetCardName() << "] "; } std::cout << std::endl; } }
/************************************************************************* > File Name: Interface.cpp > Project Name: Hearthstone++ > Author: Young-Joong Kim > Purpose: Interface for Hearthstone Game Agent > Created Time: 2017/10/24 > Copyright (c) 2017, Young-Joong Kim *************************************************************************/ #include <Interface/Interface.h> namespace Hearthstonepp { GameInterface::GameInterface(GameAgent& agent) : m_agent(agent) , m_bufferCapacity(agent.GetBufferCapacity()) { m_buffer = new BYTE[m_bufferCapacity]; } GameResult GameInterface::StartGame() { GameResult result; std::thread* at = m_agent.StartAgent(result); while (true) { int result = HandleMessage(); if (result == HANDLE_STOP) break; } at->join(); // join agent thread delete at; return result; } int GameInterface::HandleMessage() { m_agent.ReadBuffer(m_buffer, m_bufferCapacity); if (m_buffer[0] == static_cast<BYTE>(Step::FINAL_GAMEOVER)) { return HANDLE_STOP; } else if (m_handler.find(m_buffer[0]) != m_handler.end()) { m_handler[m_buffer[0]](*this); } return HANDLE_CONTINUE; } void GameInterface::LogWriter(std::string& name, std::string message) { std::cout << "[*] " << name << " : " << message << std::endl; } void GameInterface::BeginFirst() { BeginFirstStructure* data = (BeginFirstStructure*)m_buffer; m_users[0] = data->userFirst; m_users[1] = data->userLast; LogWriter(m_users[0], "Begin First"); LogWriter(m_users[1], "Begin Last"); } void GameInterface::BeginShuffle() { BeginShuffleStructure* data = (BeginShuffleStructure*)m_buffer; LogWriter(m_users[data->userID], "Begin Shuffle"); } void GameInterface::BeginDraw() { DrawStructure* data = (DrawStructure*)m_buffer; LogWriter(m_users[data->userID], "Begin Draw"); for (int i = 0; i < NUM_BEGIN_DRAW; ++i) { std::cout << "[" << data->cards[i]->GetName() << "] "; } std::cout << std::endl; } void GameInterface::BeginMulligan() { BeginMulliganStructure* data = (BeginMulliganStructure*)m_buffer; LogWriter(m_users[data->userID], "Begin Mulligan"); int numMulligan; while (true) { std::cout << "[*] How many cards to mulligan ? (0 ~ 3) "; std::cin >> numMulligan; if (numMulligan >= 0 && numMulligan <= NUM_BEGIN_DRAW) { break; } } BYTE mulligan[NUM_BEGIN_DRAW] = { 0, }; for (int i = 0; i < numMulligan; ++i) { while (true) { int index = 0; std::cout << "[*] Input card index " << i+1 << " (0 ~ 2) : "; std::cin >> index; if (index >= 0 && index <= NUM_BEGIN_DRAW - 1) { mulligan[i] = index; break; } } } m_agent.WriteBuffer(mulligan, numMulligan); // send index to agent m_agent.ReadBuffer(m_buffer, sizeof(DrawStructure)); // get new card data LogWriter(m_users[data->userID], "Mulligan Result"); DrawStructure* draw = (DrawStructure*)m_buffer; for (int i = 0; i < NUM_BEGIN_DRAW; ++i) { std::cout << "[" << draw->cards[i]->GetName() << "] "; } std::cout << std::endl; } }
Update Interface - Fix compile error
Update Interface - Fix compile error
C++
mit
Hearthstonepp/Hearthstonepp,Hearthstonepp/Hearthstonepp
e119f81991208fa9ec6ebb42a16b19e1e221c397
ft/tests/cachetable-prefetch-checkpoint-test.cc
ft/tests/cachetable-prefetch-checkpoint-test.cc
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: // verify that the cache table checkpoint with prefetched blocks active works. // the blocks in the reading state should be ignored. #ident "$Id$" #ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved." #include "test.h" #include <stdio.h> #include <unistd.h> #include "cachetable-test.h" #include "checkpoint.h" const int item_size = 1; int n_flush, n_write_me, n_keep_me, n_fetch; static void flush( CACHEFILE UU(cf), int UU(fd), CACHEKEY UU(key), void *UU(value), void** UU(dd), void *UU(extraargs), PAIR_ATTR size, PAIR_ATTR* UU(new_size), bool write_me, bool keep_me, bool UU(for_checkpoint), bool UU(is_clone) ) { // assert(key == make_blocknum((long)value)); assert(size.size == item_size); n_flush++; if (write_me) n_write_me++; if (keep_me) n_keep_me++; } static int fetch( CACHEFILE UU(cf), PAIR UU(p), int UU(fd), CACHEKEY UU(key), uint32_t UU(fullhash), void **UU(value), void** UU(dd), PAIR_ATTR *UU(sizep), int *dirtyp, void *UU(extraargs) ) { n_fetch++; sleep(10); *value = 0; *sizep = make_pair_attr(item_size); *dirtyp = 0; return 0; } // put n items into the cachetable, maybe mark them dirty, do a checkpoint, and // verify that all of the items have been written and are clean. static void cachetable_prefetch_checkpoint_test(int n, enum cachetable_dirty dirty) { if (verbose) printf("%s:%d n=%d dirty=%d\n", __FUNCTION__, __LINE__, n, (int) dirty); const int test_limit = n; int r; CACHETABLE ct; CACHETABLE_WRITE_CALLBACK wc = def_write_callback(NULL); wc.flush_callback = flush; toku_cachetable_create(&ct, test_limit, ZERO_LSN, NULL_LOGGER); char fname1[] = __SRCFILE__ "test1.dat"; unlink(fname1); CACHEFILE f1; r = toku_cachetable_openf(&f1, ct, fname1, O_RDWR|O_CREAT, S_IRWXU|S_IRWXG|S_IRWXO); assert(r == 0); create_dummy_functions(f1); // prefetch block n+1. this will take 10 seconds. { CACHEKEY key = make_blocknum(n+1); uint32_t fullhash = toku_cachetable_hash(f1, key); r = toku_cachefile_prefetch(f1, key, fullhash, wc, fetch, def_pf_req_callback, def_pf_callback, 0, NULL); toku_cachetable_verify(ct); } // insert items into the cachetable. all should be dirty int i; for (i=0; i<n; i++) { CACHEKEY key = make_blocknum(i); uint32_t hi = toku_cachetable_hash(f1, key); toku_cachetable_put(f1, key, hi, (void *)(long)i, make_pair_attr(1), wc, put_callback_nop); r = toku_test_cachetable_unpin(f1, key, hi, dirty, make_pair_attr(item_size)); assert(r == 0); void *v; int its_dirty; long long its_pin; long its_size; r = toku_cachetable_get_key_state(ct, key, f1, &v, &its_dirty, &its_pin, &its_size); if (r != 0) continue; assert(its_dirty == CACHETABLE_DIRTY); assert(its_pin == 0); assert(its_size == item_size); } // the checkpoint should cause n writes, but since n <= the cachetable size, // all items should be kept in the cachetable n_flush = n_write_me = n_keep_me = n_fetch = 0; CHECKPOINTER cp = toku_cachetable_get_checkpointer(ct); r = toku_checkpoint(cp, NULL, NULL, NULL, NULL, NULL, CLIENT_CHECKPOINT); assert(r == 0); assert(n_flush == n && n_write_me == n && n_keep_me == n); // after the checkpoint, all of the items should be clean for (i=0; i<n; i++) { CACHEKEY key = make_blocknum(i); uint32_t hi = toku_cachetable_hash(f1, key); void *v; r = toku_cachetable_maybe_get_and_pin(f1, key, hi, &v); if (r != 0) continue; r = toku_test_cachetable_unpin(f1, key, hi, CACHETABLE_CLEAN, make_pair_attr(item_size)); assert(r == 0); int its_dirty; long long its_pin; long its_size; r = toku_cachetable_get_key_state(ct, key, f1, &v, &its_dirty, &its_pin, &its_size); if (r != 0) continue; assert(its_dirty == CACHETABLE_CLEAN); assert(its_pin == 0); assert(its_size == item_size); } // a subsequent checkpoint should cause no flushes, or writes since all of the items are clean n_flush = n_write_me = n_keep_me = n_fetch = 0; r = toku_checkpoint(cp, NULL, NULL, NULL, NULL, NULL, CLIENT_CHECKPOINT); assert(r == 0); assert(n_flush == 0 && n_write_me == 0 && n_keep_me == 0); r = toku_cachefile_close(&f1, false, ZERO_LSN); assert(r == 0); toku_cachetable_close(&ct); } int test_main(int argc, const char *argv[]) { int i; for (i=1; i<argc; i++) { if (strcmp(argv[i], "-v") == 0) { verbose++; continue; } } for (i=0; i<8; i++) { cachetable_prefetch_checkpoint_test(i, CACHETABLE_CLEAN); cachetable_prefetch_checkpoint_test(i, CACHETABLE_DIRTY); } return 0; }
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: // verify that the cache table checkpoint with prefetched blocks active works. // the blocks in the reading state should be ignored. #ident "$Id$" #ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved." #include "test.h" #include <stdio.h> #include <unistd.h> #include "cachetable-test.h" #include "checkpoint.h" const int item_size = 1; int n_flush, n_write_me, n_keep_me, n_fetch; static void flush( CACHEFILE UU(cf), int UU(fd), CACHEKEY UU(key), void *UU(value), void** UU(dd), void *UU(extraargs), PAIR_ATTR size, PAIR_ATTR* UU(new_size), bool write_me, bool keep_me, bool UU(for_checkpoint), bool UU(is_clone) ) { // assert(key == make_blocknum((long)value)); assert(size.size == item_size); n_flush++; if (write_me) n_write_me++; if (keep_me) n_keep_me++; } static int fetch( CACHEFILE UU(cf), PAIR UU(p), int UU(fd), CACHEKEY UU(key), uint32_t UU(fullhash), void **UU(value), void** UU(dd), PAIR_ATTR *UU(sizep), int *dirtyp, void *UU(extraargs) ) { n_fetch++; sleep(10); *value = 0; *sizep = make_pair_attr(item_size); *dirtyp = 0; return 0; } // put n items into the cachetable, maybe mark them dirty, do a checkpoint, and // verify that all of the items have been written and are clean. static void cachetable_prefetch_checkpoint_test(int n, enum cachetable_dirty dirty) { if (verbose) printf("%s:%d n=%d dirty=%d\n", __FUNCTION__, __LINE__, n, (int) dirty); const int test_limit = n; int r; CACHETABLE ct; CACHETABLE_WRITE_CALLBACK wc = def_write_callback(NULL); wc.flush_callback = flush; toku_cachetable_create(&ct, test_limit, ZERO_LSN, NULL_LOGGER); char fname1[] = __SRCFILE__ "test1.dat"; unlink(fname1); CACHEFILE f1; r = toku_cachetable_openf(&f1, ct, fname1, O_RDWR|O_CREAT, S_IRWXU|S_IRWXG|S_IRWXO); assert(r == 0); create_dummy_functions(f1); // disable the eviction thread. this thread was written to assume // evictions hapepn on the client thread, which is no longer true. evictor_test_helpers::disable_ev_thread(&ct->ev); // prefetch block n+1. this will take 10 seconds. { CACHEKEY key = make_blocknum(n+1); uint32_t fullhash = toku_cachetable_hash(f1, key); r = toku_cachefile_prefetch(f1, key, fullhash, wc, fetch, def_pf_req_callback, def_pf_callback, 0, NULL); toku_cachetable_verify(ct); } // insert items into the cachetable. all should be dirty int i; for (i=0; i<n; i++) { CACHEKEY key = make_blocknum(i); uint32_t hi = toku_cachetable_hash(f1, key); toku_cachetable_put(f1, key, hi, (void *)(long)i, make_pair_attr(1), wc, put_callback_nop); r = toku_test_cachetable_unpin(f1, key, hi, dirty, make_pair_attr(item_size)); assert(r == 0); void *v; int its_dirty; long long its_pin; long its_size; r = toku_cachetable_get_key_state(ct, key, f1, &v, &its_dirty, &its_pin, &its_size); if (r != 0) continue; assert(its_dirty == CACHETABLE_DIRTY); assert(its_pin == 0); assert(its_size == item_size); } // the checkpoint should cause n writes, but since n <= the cachetable size, // all items should be kept in the cachetable n_flush = n_write_me = n_keep_me = n_fetch = 0; CHECKPOINTER cp = toku_cachetable_get_checkpointer(ct); r = toku_checkpoint(cp, NULL, NULL, NULL, NULL, NULL, CLIENT_CHECKPOINT); assert(r == 0); assert(n_flush == n && n_write_me == n && n_keep_me == n); // after the checkpoint, all of the items should be clean for (i=0; i<n; i++) { CACHEKEY key = make_blocknum(i); uint32_t hi = toku_cachetable_hash(f1, key); void *v; r = toku_cachetable_maybe_get_and_pin(f1, key, hi, &v); if (r != 0) continue; r = toku_test_cachetable_unpin(f1, key, hi, CACHETABLE_CLEAN, make_pair_attr(item_size)); assert(r == 0); int its_dirty; long long its_pin; long its_size; r = toku_cachetable_get_key_state(ct, key, f1, &v, &its_dirty, &its_pin, &its_size); if (r != 0) continue; assert(its_dirty == CACHETABLE_CLEAN); assert(its_pin == 0); assert(its_size == item_size); } // a subsequent checkpoint should cause no flushes, or writes since all of the items are clean n_flush = n_write_me = n_keep_me = n_fetch = 0; r = toku_checkpoint(cp, NULL, NULL, NULL, NULL, NULL, CLIENT_CHECKPOINT); assert(r == 0); assert(n_flush == 0 && n_write_me == 0 && n_keep_me == 0); r = toku_cachefile_close(&f1, false, ZERO_LSN); assert(r == 0); toku_cachetable_close(&ct); } int test_main(int argc, const char *argv[]) { int i; for (i=1; i<argc; i++) { if (strcmp(argv[i], "-v") == 0) { verbose++; continue; } } for (i=0; i<8; i++) { cachetable_prefetch_checkpoint_test(i, CACHETABLE_CLEAN); cachetable_prefetch_checkpoint_test(i, CACHETABLE_DIRTY); } return 0; }
fix flakey test
fix flakey test git-svn-id: b5c078ec0b4d3a50497e9dd3081db18a5b4f16e5@48123 c7de825b-a66e-492c-adef-691d508d4ae1
C++
lgpl-2.1
ollie314/server,davidl-zend/zenddbi,kuszmaul/PerconaFT,ollie314/server,ottok/PerconaFT,flynn1973/mariadb-aix,natsys/mariadb_10.2,davidl-zend/zenddbi,flynn1973/mariadb-aix,davidl-zend/zenddbi,ottok/PerconaFT,ollie314/server,davidl-zend/zenddbi,ollie314/server,natsys/mariadb_10.2,davidl-zend/zenddbi,slanterns/server,percona/PerconaFT,natsys/mariadb_10.2,BohuTANG/ft-index,davidl-zend/zenddbi,natsys/mariadb_10.2,flynn1973/mariadb-aix,kuszmaul/PerconaFT-tmp,kuszmaul/PerconaFT,kuszmaul/PerconaFT-tmp,kuszmaul/PerconaFT,BohuTANG/ft-index,natsys/mariadb_10.2,flynn1973/mariadb-aix,natsys/mariadb_10.2,natsys/mariadb_10.2,ollie314/server,flynn1973/mariadb-aix,percona/PerconaFT,kuszmaul/PerconaFT,davidl-zend/zenddbi,davidl-zend/zenddbi,natsys/mariadb_10.2,flynn1973/mariadb-aix,flynn1973/mariadb-aix,ottok/PerconaFT,BohuTANG/ft-index,kuszmaul/PerconaFT-tmp,flynn1973/mariadb-aix,percona/PerconaFT,ollie314/server,davidl-zend/zenddbi,ollie314/server,natsys/mariadb_10.2,ottok/PerconaFT,flynn1973/mariadb-aix,ollie314/server,natsys/mariadb_10.2,ollie314/server,flynn1973/mariadb-aix,ollie314/server,percona/PerconaFT,flynn1973/mariadb-aix,davidl-zend/zenddbi,ollie314/server,davidl-zend/zenddbi,kuszmaul/PerconaFT-tmp,BohuTANG/ft-index,natsys/mariadb_10.2
06a9eb70b572938bb0016cf80020386199e8352c
lib/aux_js.cpp
lib/aux_js.cpp
// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-443271. // // This file is part of the GLVis visualization tool and library. For more // information and source code availability see https://glvis.org. // // GLVis is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "visual.hpp" #include "palettes.hpp" #include "stream_reader.hpp" #include <SDL2/SDL_hints.h> #include <emscripten/bind.h> #include <emscripten/html5.h> std::string plot_caption; std::string extra_caption; // used in extern context mfem::GeometryRefiner GLVisGeometryRefiner; // used in extern context static VisualizationSceneScalarData * vs = nullptr; namespace js { using namespace mfem; // Replace a given VectorFiniteElement-based grid function (e.g. from a Nedelec // or Raviart-Thomas space) with a discontinuous piece-wise polynomial Cartesian // product vector grid function of the same order. GridFunction *ProjectVectorFEGridFunction(GridFunction *gf) { if ((gf->VectorDim() == 3) && (gf->FESpace()->GetVDim() == 1)) { int p = gf->FESpace()->GetOrder(0); cout << "Switching to order " << p << " discontinuous vector grid function..." << endl; int dim = gf->FESpace()->GetMesh()->Dimension(); FiniteElementCollection *d_fec = new L2_FECollection(p, dim, 1); FiniteElementSpace *d_fespace = new FiniteElementSpace(gf->FESpace()->GetMesh(), d_fec, 3); GridFunction *d_gf = new GridFunction(d_fespace); d_gf->MakeOwner(d_fec); gf->ProjectVectorFieldOn(*d_gf); delete gf; return d_gf; } return gf; } bool startVisualization(const std::string input, const std::string data_type, int w, int h) { std::stringstream ss(input); // 0 - scalar data, 1 - vector data, 2 - mesh only, (-1) - unknown const int field_type = ReadStream(ss, data_type); // reset antialiasing GetAppWindow()->getRenderer().setAntialiasing(0); std::string line; double minv = 0.0, maxv = 0.0; while (ss >> line) { if (line == "keys") { std::cout << "parsing 'keys'" << std::endl; ss >> stream_state.keys; } else if (line == "valuerange") { std::cout << "parsing 'valuerange'" << std::endl; ss >> minv >> maxv; } else { std::cout << "unknown line '" << line << "'" << std::endl; } } if (field_type < 0 || field_type > 2) { return false; } if (InitVisualization("glvis", 0, 0, w, h)) { return false; } delete vs; vs = nullptr; double mesh_range = -1.0; if (field_type == 0 || field_type == 2) { if (stream_state.grid_f) { stream_state.grid_f->GetNodalValues(stream_state.sol); } if (stream_state.mesh->SpaceDimension() == 2) { VisualizationSceneSolution * vss; if (stream_state.normals.Size() > 0) { vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol, &stream_state.normals); } else { vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol); } if (stream_state.grid_f) { vss->SetGridFunction(*stream_state.grid_f); } if (field_type == 2) { vs->OrthogonalProjection = 1; vs->SetLight(0); vs->Zoom(1.8); // Use the 'bone' palette when visualizing a 2D mesh only (otherwise // the 'jet-like' palette is used in 2D, see vssolution.cpp). paletteSet(4); } } else if (stream_state.mesh->SpaceDimension() == 3) { VisualizationSceneSolution3d * vss; vs = vss = new VisualizationSceneSolution3d(*stream_state.mesh, stream_state.sol); if (stream_state.grid_f) { vss->SetGridFunction(stream_state.grid_f); } if (field_type == 2) { if (stream_state.mesh->Dimension() == 3) { // Use the 'white' palette when visualizing a 3D volume mesh only // paletteSet(4); paletteSet(11); vss->SetLightMatIdx(4); } else { // Use the 'bone' palette when visualizing a surface mesh only // (the same as when visualizing a 2D mesh only) paletteSet(4); } // Otherwise, the 'vivid' palette is used in 3D see vssolution3d.cpp vss->ToggleDrawAxes(); vss->ToggleDrawMesh(); } } if (field_type == 2) { if (stream_state.grid_f) { mesh_range = stream_state.grid_f->Max() + 1.0; } else { mesh_range = stream_state.sol.Max() + 1.0; } } } else if (field_type == 1) { if (stream_state.mesh->SpaceDimension() == 2) { if (stream_state.grid_f) { vs = new VisualizationSceneVector(*stream_state.grid_f); } else { vs = new VisualizationSceneVector(*stream_state.mesh, stream_state.solu, stream_state.solv); } } else if (stream_state.mesh->SpaceDimension() == 3) { if (stream_state.grid_f) { stream_state.grid_f = ProjectVectorFEGridFunction(stream_state.grid_f); vs = new VisualizationSceneVector3d(*stream_state.grid_f); } else { vs = new VisualizationSceneVector3d(*stream_state.mesh, stream_state.solu, stream_state.solv, stream_state.solw); } } } if (vs) { // increase the refinement factors if visualizing a GridFunction if (stream_state.grid_f) { vs->AutoRefine(); vs->SetShading(2, true); } if (mesh_range > 0.0) { vs->SetValueRange(-mesh_range, mesh_range); vs->SetAutoscale(0); } if (stream_state.mesh->SpaceDimension() == 2 && field_type == 2) { SetVisualizationScene(vs, 2); } else { SetVisualizationScene(vs, 3); } } CallKeySequence(stream_state.keys.c_str()); if (minv || maxv) { vs->SetValueRange(minv, maxv); } SendExposeEvent(); return true; } int updateVisualization(std::string data_type, std::string stream) { std::stringstream ss(stream); if (data_type != "solution") { std::cerr << "unsupported data type '" << data_type << "' for stream update" << std::endl; return 1; } auto * new_m = new Mesh(ss, 1, 0, stream_state.fix_elem_orient); auto * new_g = new GridFunction(new_m, ss); double mesh_range = -1.0; if (new_m->SpaceDimension() == stream_state.mesh->SpaceDimension() && new_g->VectorDim() == stream_state.grid_f->VectorDim()) { if (new_m->SpaceDimension() == 2) { if (new_g->VectorDim() == 1) { VisualizationSceneSolution *vss = dynamic_cast<VisualizationSceneSolution *>(vs); new_g->GetNodalValues(stream_state.sol); vss->NewMeshAndSolution(new_m, &stream_state.sol, new_g); } else { VisualizationSceneVector *vsv = dynamic_cast<VisualizationSceneVector *>(vs); vsv->NewMeshAndSolution(*new_g); } } else { if (new_g->VectorDim() == 1) { VisualizationSceneSolution3d *vss = dynamic_cast<VisualizationSceneSolution3d *>(vs); new_g->GetNodalValues(stream_state.sol); vss->NewMeshAndSolution(new_m, &stream_state.sol, new_g); } else { new_g = ProjectVectorFEGridFunction(new_g); VisualizationSceneVector3d *vss = dynamic_cast<VisualizationSceneVector3d *>(vs); vss->NewMeshAndSolution(new_m, new_g); } } if (mesh_range > 0.0) { vs->SetValueRange(-mesh_range, mesh_range); } delete stream_state.grid_f; stream_state.grid_f = new_g; delete stream_state.mesh; stream_state.mesh = new_m; SendExposeEvent(); return 0; } else { cout << "Stream: field type does not match!" << endl; delete new_g; delete new_m; return 1; } } void iterVisualization() { GetAppWindow()->mainIter(); } void setCanvasId(const std::string & id) { std::cout << "glvis: setting canvas id to " << id << std::endl; GetAppWindow()->setCanvasId(id); } void disableKeyHandling() { SDL_EventState(SDL_KEYDOWN, SDL_DISABLE); SDL_EventState(SDL_KEYUP, SDL_DISABLE); } void enableKeyHandling() { SDL_EventState(SDL_KEYDOWN, SDL_ENABLE); SDL_EventState(SDL_KEYUP, SDL_ENABLE); } void setKeyboardListeningElementId(const std::string & id) { SDL_SetHint(SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT, id.c_str()); } void processKeys(const std::string & keys) { CallKeySequence(keys.c_str()); } void processKey(char sym, bool ctrl=false, bool shift=false, bool alt=false) { Uint16 mod = 0; mod |= ctrl ? KMOD_CTRL : 0; mod |= shift ? KMOD_SHIFT : 0; mod |= alt ? KMOD_ALT : 0; GetAppWindow()->callKeyDown(sym, mod); } void setupResizeEventCallback(const std::string & id) { // typedef EM_BOOL (*em_ui_callback_func)(int eventType, const EmscriptenUiEvent *uiEvent, void *userData); std::cout << "glvis: adding resize callback for " << id << std::endl; auto err = emscripten_set_resize_callback(id.c_str(), nullptr, true, [](int eventType, const EmscriptenUiEvent *uiEvent, void *userData) -> EM_BOOL { std::cout << "got resize event" << std::endl; return true; }); // TODO: macro to wrap this if (err != EMSCRIPTEN_RESULT_SUCCESS) { std::cerr << "error (emscripten_set_resize_callback): " << err << std::endl; } } std::string getHelpString() { VisualizationSceneScalarData* vss = dynamic_cast<VisualizationSceneScalarData*>(GetVisualizationScene()); return vss->GetHelpString(); } } // namespace js // Info on type conversion: // https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html#built-in-type-conversions namespace em = emscripten; EMSCRIPTEN_BINDINGS(js_funcs) { em::function("startVisualization", &js::startVisualization); em::function("updateVisualization", &js::updateVisualization); em::function("iterVisualization", &js::iterVisualization); em::function("sendExposeEvent", &SendExposeEvent); em::function("disableKeyHanding", &js::disableKeyHandling); em::function("enableKeyHandling", &js::enableKeyHandling); em::function("setKeyboardListeningElementId", js::setKeyboardListeningElementId); em::function("getTextureMode", &GetUseTexture); em::function("setTextureMode", &SetUseTexture); em::function("resizeWindow", &ResizeWindow); em::function("setCanvasId", &js::setCanvasId); em::function("setupResizeEventCallback", &js::setupResizeEventCallback); em::function("getHelpString", &js::getHelpString); em::function("processKeys", &js::processKeys); em::function("processKey", &js::processKey); }
// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-443271. // // This file is part of the GLVis visualization tool and library. For more // information and source code availability see https://glvis.org. // // GLVis is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "visual.hpp" #include "palettes.hpp" #include "stream_reader.hpp" #include <SDL2/SDL_hints.h> #include <emscripten/bind.h> #include <emscripten/html5.h> std::string plot_caption; std::string extra_caption; // used in extern context mfem::GeometryRefiner GLVisGeometryRefiner; // used in extern context static VisualizationSceneScalarData * vs = nullptr; namespace js { using namespace mfem; // Replace a given VectorFiniteElement-based grid function (e.g. from a Nedelec // or Raviart-Thomas space) with a discontinuous piece-wise polynomial Cartesian // product vector grid function of the same order. GridFunction *ProjectVectorFEGridFunction(GridFunction *gf) { if ((gf->VectorDim() == 3) && (gf->FESpace()->GetVDim() == 1)) { int p = gf->FESpace()->GetOrder(0); cout << "Switching to order " << p << " discontinuous vector grid function..." << endl; int dim = gf->FESpace()->GetMesh()->Dimension(); FiniteElementCollection *d_fec = new L2_FECollection(p, dim, 1); FiniteElementSpace *d_fespace = new FiniteElementSpace(gf->FESpace()->GetMesh(), d_fec, 3); GridFunction *d_gf = new GridFunction(d_fespace); d_gf->MakeOwner(d_fec); gf->ProjectVectorFieldOn(*d_gf); delete gf; return d_gf; } return gf; } bool startVisualization(const std::string input, const std::string data_type, int w, int h) { std::stringstream ss(input); // 0 - scalar data, 1 - vector data, 2 - mesh only, (-1) - unknown const int field_type = ReadStream(ss, data_type); // reset antialiasing GetAppWindow()->getRenderer().setAntialiasing(0); std::string line; double minv = 0.0, maxv = 0.0; while (ss >> line) { if (line == "keys") { std::cout << "parsing 'keys'" << std::endl; ss >> stream_state.keys; } else if (line == "valuerange") { std::cout << "parsing 'valuerange'" << std::endl; ss >> minv >> maxv; } else { std::cout << "unknown line '" << line << "'" << std::endl; } } if (field_type < 0 || field_type > 2) { return false; } if (InitVisualization("glvis", 0, 0, w, h)) { return false; } delete vs; vs = nullptr; double mesh_range = -1.0; if (field_type == 0 || field_type == 2) { if (stream_state.grid_f) { stream_state.grid_f->GetNodalValues(stream_state.sol); } if (stream_state.mesh->SpaceDimension() == 2) { VisualizationSceneSolution * vss; if (stream_state.normals.Size() > 0) { vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol, &stream_state.normals); } else { vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol); } if (stream_state.grid_f) { vss->SetGridFunction(*stream_state.grid_f); } if (field_type == 2) { vs->OrthogonalProjection = 1; vs->SetLight(0); vs->Zoom(1.8); // Use the 'bone' palette when visualizing a 2D mesh only (otherwise // the 'jet-like' palette is used in 2D, see vssolution.cpp). paletteSet(4); } } else if (stream_state.mesh->SpaceDimension() == 3) { VisualizationSceneSolution3d * vss; vs = vss = new VisualizationSceneSolution3d(*stream_state.mesh, stream_state.sol); if (stream_state.grid_f) { vss->SetGridFunction(stream_state.grid_f); } if (field_type == 2) { if (stream_state.mesh->Dimension() == 3) { // Use the 'white' palette when visualizing a 3D volume mesh only // paletteSet(4); paletteSet(11); vss->SetLightMatIdx(4); } else { // Use the 'bone' palette when visualizing a surface mesh only // (the same as when visualizing a 2D mesh only) paletteSet(4); } // Otherwise, the 'vivid' palette is used in 3D see vssolution3d.cpp vss->ToggleDrawAxes(); vss->ToggleDrawMesh(); } } if (field_type == 2) { if (stream_state.grid_f) { mesh_range = stream_state.grid_f->Max() + 1.0; } else { mesh_range = stream_state.sol.Max() + 1.0; } } } else if (field_type == 1) { if (stream_state.mesh->SpaceDimension() == 2) { if (stream_state.grid_f) { vs = new VisualizationSceneVector(*stream_state.grid_f); } else { vs = new VisualizationSceneVector(*stream_state.mesh, stream_state.solu, stream_state.solv); } } else if (stream_state.mesh->SpaceDimension() == 3) { if (stream_state.grid_f) { stream_state.grid_f = ProjectVectorFEGridFunction(stream_state.grid_f); vs = new VisualizationSceneVector3d(*stream_state.grid_f); } else { vs = new VisualizationSceneVector3d(*stream_state.mesh, stream_state.solu, stream_state.solv, stream_state.solw); } } } if (vs) { // increase the refinement factors if visualizing a GridFunction if (stream_state.grid_f) { vs->AutoRefine(); vs->SetShading(2, true); } if (mesh_range > 0.0) { vs->SetValueRange(-mesh_range, mesh_range); vs->SetAutoscale(0); } if (stream_state.mesh->SpaceDimension() == 2 && field_type == 2) { SetVisualizationScene(vs, 2); } else { SetVisualizationScene(vs, 3); } } CallKeySequence(stream_state.keys.c_str()); if (minv || maxv) { vs->SetValueRange(minv, maxv); } SendExposeEvent(); return true; } int updateVisualization(std::string data_type, std::string stream) { std::stringstream ss(stream); if (data_type != "solution") { std::cerr << "unsupported data type '" << data_type << "' for stream update" << std::endl; return 1; } auto * new_m = new Mesh(ss, 1, 0, stream_state.fix_elem_orient); auto * new_g = new GridFunction(new_m, ss); double mesh_range = -1.0; if (new_m->SpaceDimension() == stream_state.mesh->SpaceDimension() && new_g->VectorDim() == stream_state.grid_f->VectorDim()) { if (new_m->SpaceDimension() == 2) { if (new_g->VectorDim() == 1) { VisualizationSceneSolution *vss = dynamic_cast<VisualizationSceneSolution *>(vs); new_g->GetNodalValues(stream_state.sol); vss->NewMeshAndSolution(new_m, &stream_state.sol, new_g); } else { VisualizationSceneVector *vsv = dynamic_cast<VisualizationSceneVector *>(vs); vsv->NewMeshAndSolution(*new_g); } } else { if (new_g->VectorDim() == 1) { VisualizationSceneSolution3d *vss = dynamic_cast<VisualizationSceneSolution3d *>(vs); new_g->GetNodalValues(stream_state.sol); vss->NewMeshAndSolution(new_m, &stream_state.sol, new_g); } else { new_g = ProjectVectorFEGridFunction(new_g); VisualizationSceneVector3d *vss = dynamic_cast<VisualizationSceneVector3d *>(vs); vss->NewMeshAndSolution(new_m, new_g); } } if (mesh_range > 0.0) { vs->SetValueRange(-mesh_range, mesh_range); } delete stream_state.grid_f; stream_state.grid_f = new_g; delete stream_state.mesh; stream_state.mesh = new_m; SendExposeEvent(); return 0; } else { cout << "Stream: field type does not match!" << endl; delete new_g; delete new_m; return 1; } } void iterVisualization() { GetAppWindow()->mainIter(); } void setCanvasId(const std::string & id) { std::cout << "glvis: setting canvas id to " << id << std::endl; GetAppWindow()->setCanvasId(id); } void disableKeyHandling() { SDL_EventState(SDL_KEYDOWN, SDL_DISABLE); SDL_EventState(SDL_KEYUP, SDL_DISABLE); } void enableKeyHandling() { SDL_EventState(SDL_KEYDOWN, SDL_ENABLE); SDL_EventState(SDL_KEYUP, SDL_ENABLE); } void setKeyboardListeningElementId(const std::string & id) { SDL_SetHint(SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT, id.c_str()); } void processKeys(const std::string & keys) { CallKeySequence(keys.c_str()); } void processKey(char sym, bool ctrl=false, bool shift=false, bool alt=false) { Uint16 mod = 0; mod |= ctrl ? KMOD_CTRL : 0; mod |= shift ? KMOD_SHIFT : 0; mod |= alt ? KMOD_ALT : 0; GetAppWindow()->callKeyDown(sym, mod); } void setupResizeEventCallback(const std::string & id) { // typedef EM_BOOL (*em_ui_callback_func)(int eventType, const EmscriptenUiEvent *uiEvent, void *userData); std::cout << "glvis: adding resize callback for " << id << std::endl; auto err = emscripten_set_resize_callback(id.c_str(), nullptr, true, [](int eventType, const EmscriptenUiEvent *uiEvent, void *userData) -> EM_BOOL { std::cout << "got resize event" << std::endl; return true; }); // TODO: macro to wrap this if (err != EMSCRIPTEN_RESULT_SUCCESS) { std::cerr << "error (emscripten_set_resize_callback): " << err << std::endl; } } std::string getHelpString() { VisualizationSceneScalarData* vss = dynamic_cast<VisualizationSceneScalarData*>(GetVisualizationScene()); return vss->GetHelpString(); } } // namespace js // Info on type conversion: // https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html#built-in-type-conversions namespace em = emscripten; EMSCRIPTEN_BINDINGS(js_funcs) { em::function("startVisualization", &js::startVisualization); em::function("updateVisualization", &js::updateVisualization); em::function("iterVisualization", &js::iterVisualization); em::function("sendExposeEvent", &SendExposeEvent); em::function("disableKeyHanding", &js::disableKeyHandling); em::function("enableKeyHandling", &js::enableKeyHandling); em::function("setKeyboardListeningElementId", js::setKeyboardListeningElementId); em::function("getTextureMode", &GetUseTexture); em::function("setTextureMode", &SetUseTexture); em::function("resizeWindow", &ResizeWindow); em::function("setCanvasId", &js::setCanvasId); em::function("setupResizeEventCallback", &js::setupResizeEventCallback); em::function("getHelpString", &js::getHelpString); em::function("processKeys", &js::processKeys); em::function("processKey", &js::processKey); }
make style
make style
C++
bsd-3-clause
GLVis/glvis,GLVis/glvis,GLVis/glvis,GLVis/glvis
545bc5f81d60fa6ff7c5cc43a2e9eef82f911466
src/util/readwritefile.cpp
src/util/readwritefile.cpp
// Copyright (c) 2015-2020 The Bitcoin Core developers // Copyright (c) 2017 The Zcash developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <fs.h> #include <limits> #include <stdio.h> #include <string> #include <utility> std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits<size_t>::max()) { FILE *f = fsbridge::fopen(filename, "rb"); if (f == nullptr) return std::make_pair(false,""); std::string retval; char buffer[128]; do { const size_t n = fread(buffer, 1, sizeof(buffer), f); // Check for reading errors so we don't return any data if we couldn't // read the entire file (or up to maxsize) if (ferror(f)) { fclose(f); return std::make_pair(false,""); } retval.append(buffer, buffer+n); } while (!feof(f) && retval.size() <= maxsize); fclose(f); return std::make_pair(true,retval); } bool WriteBinaryFile(const fs::path &filename, const std::string &data) { FILE *f = fsbridge::fopen(filename, "wb"); if (f == nullptr) return false; if (fwrite(data.data(), 1, data.size(), f) != data.size()) { fclose(f); return false; } fclose(f); return true; }
// Copyright (c) 2015-2020 The Bitcoin Core developers // Copyright (c) 2017 The Zcash developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <fs.h> #include <limits> #include <stdio.h> #include <string> #include <utility> std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits<size_t>::max()) { FILE *f = fsbridge::fopen(filename, "rb"); if (f == nullptr) return std::make_pair(false,""); std::string retval; char buffer[128]; do { const size_t n = fread(buffer, 1, sizeof(buffer), f); // Check for reading errors so we don't return any data if we couldn't // read the entire file (or up to maxsize) if (ferror(f)) { fclose(f); return std::make_pair(false,""); } retval.append(buffer, buffer+n); } while (!feof(f) && retval.size() <= maxsize); fclose(f); return std::make_pair(true,retval); } bool WriteBinaryFile(const fs::path &filename, const std::string &data) { FILE *f = fsbridge::fopen(filename, "wb"); if (f == nullptr) return false; if (fwrite(data.data(), 1, data.size(), f) != data.size()) { fclose(f); return false; } if (fclose(f) != 0) { return false; } return true; }
fix WriteBinaryFile() claiming success even if error occurred
util: fix WriteBinaryFile() claiming success even if error occurred `fclose()` is flushing any buffered data to disk, so if it fails then that could mean that the data was not completely written to disk. Thus, check if `fclose()` succeeds and only then claim success from `WriteBinaryFile()`.
C++
mit
domob1812/bitcoin,dscotese/bitcoin,anditto/bitcoin,yenliangl/bitcoin,ElementsProject/elements,Xekyo/bitcoin,sstone/bitcoin,jamesob/bitcoin,qtumproject/qtum,bitcoinsSG/bitcoin,domob1812/bitcoin,rnicoll/bitcoin,mruddy/bitcoin,fanquake/bitcoin,sipsorcery/bitcoin,tecnovert/particl-core,lateminer/bitcoin,bitcoin/bitcoin,lateminer/bitcoin,achow101/bitcoin,achow101/bitcoin,bitcoinsSG/bitcoin,JeremyRubin/bitcoin,fanquake/bitcoin,AkioNak/bitcoin,ajtowns/bitcoin,domob1812/namecore,domob1812/namecore,instagibbs/bitcoin,ElementsProject/elements,anditto/bitcoin,domob1812/bitcoin,JeremyRubin/bitcoin,andreaskern/bitcoin,mm-s/bitcoin,GroestlCoin/bitcoin,dscotese/bitcoin,jlopp/statoshi,rnicoll/bitcoin,GroestlCoin/bitcoin,qtumproject/qtum,particl/particl-core,MarcoFalke/bitcoin,fanquake/bitcoin,jamesob/bitcoin,mruddy/bitcoin,dscotese/bitcoin,GroestlCoin/GroestlCoin,kallewoof/bitcoin,prusnak/bitcoin,sstone/bitcoin,rnicoll/bitcoin,fujicoin/fujicoin,instagibbs/bitcoin,namecoin/namecoin-core,AkioNak/bitcoin,mruddy/bitcoin,n1bor/bitcoin,ElementsProject/elements,GroestlCoin/bitcoin,andreaskern/bitcoin,apoelstra/bitcoin,fanquake/bitcoin,pataquets/namecoin-core,domob1812/namecore,achow101/bitcoin,rnicoll/bitcoin,kallewoof/bitcoin,GroestlCoin/GroestlCoin,bitcoinsSG/bitcoin,pataquets/namecoin-core,namecoin/namecoin-core,prusnak/bitcoin,jambolo/bitcoin,n1bor/bitcoin,MeshCollider/bitcoin,dscotese/bitcoin,yenliangl/bitcoin,Sjors/bitcoin,pataquets/namecoin-core,MarcoFalke/bitcoin,n1bor/bitcoin,yenliangl/bitcoin,bitcoinknots/bitcoin,qtumproject/qtum,Sjors/bitcoin,bitcoinsSG/bitcoin,domob1812/bitcoin,bitcoin/bitcoin,jamesob/bitcoin,bitcoinknots/bitcoin,mruddy/bitcoin,prusnak/bitcoin,kallewoof/bitcoin,mm-s/bitcoin,Xekyo/bitcoin,instagibbs/bitcoin,lateminer/bitcoin,yenliangl/bitcoin,sipsorcery/bitcoin,domob1812/bitcoin,namecoin/namecoin-core,ajtowns/bitcoin,prusnak/bitcoin,JeremyRubin/bitcoin,Xekyo/bitcoin,mm-s/bitcoin,Xekyo/bitcoin,qtumproject/qtum,JeremyRubin/bitcoin,ajtowns/bitcoin,fujicoin/fujicoin,rnicoll/bitcoin,fujicoin/fujicoin,JeremyRubin/bitcoin,GroestlCoin/GroestlCoin,sstone/bitcoin,prusnak/bitcoin,yenliangl/bitcoin,qtumproject/qtum,GroestlCoin/GroestlCoin,MarcoFalke/bitcoin,bitcoinknots/bitcoin,AkioNak/bitcoin,domob1812/namecore,lateminer/bitcoin,namecoin/namecore,anditto/bitcoin,jambolo/bitcoin,jamesob/bitcoin,JeremyRubin/bitcoin,AkioNak/bitcoin,fujicoin/fujicoin,sstone/bitcoin,MeshCollider/bitcoin,ajtowns/bitcoin,apoelstra/bitcoin,namecoin/namecore,GroestlCoin/bitcoin,lateminer/bitcoin,jlopp/statoshi,Xekyo/bitcoin,qtumproject/qtum,particl/particl-core,ajtowns/bitcoin,apoelstra/bitcoin,bitcoin/bitcoin,fujicoin/fujicoin,fanquake/bitcoin,sipsorcery/bitcoin,jamesob/bitcoin,jlopp/statoshi,domob1812/namecore,MarcoFalke/bitcoin,n1bor/bitcoin,pataquets/namecoin-core,namecoin/namecore,domob1812/bitcoin,apoelstra/bitcoin,namecoin/namecore,domob1812/namecore,tecnovert/particl-core,namecoin/namecore,tecnovert/particl-core,MeshCollider/bitcoin,mruddy/bitcoin,fujicoin/fujicoin,bitcoinsSG/bitcoin,AkioNak/bitcoin,apoelstra/bitcoin,jlopp/statoshi,bitcoin/bitcoin,particl/particl-core,tecnovert/particl-core,jambolo/bitcoin,dscotese/bitcoin,achow101/bitcoin,GroestlCoin/GroestlCoin,namecoin/namecoin-core,instagibbs/bitcoin,achow101/bitcoin,particl/particl-core,bitcoinknots/bitcoin,bitcoin/bitcoin,jambolo/bitcoin,dscotese/bitcoin,rnicoll/bitcoin,particl/particl-core,anditto/bitcoin,jlopp/statoshi,Sjors/bitcoin,MarcoFalke/bitcoin,bitcoinsSG/bitcoin,andreaskern/bitcoin,fanquake/bitcoin,namecoin/namecoin-core,jambolo/bitcoin,mm-s/bitcoin,mruddy/bitcoin,n1bor/bitcoin,jlopp/statoshi,GroestlCoin/bitcoin,yenliangl/bitcoin,Sjors/bitcoin,ElementsProject/elements,instagibbs/bitcoin,kallewoof/bitcoin,Sjors/bitcoin,ElementsProject/elements,sipsorcery/bitcoin,sstone/bitcoin,GroestlCoin/GroestlCoin,jambolo/bitcoin,MarcoFalke/bitcoin,achow101/bitcoin,andreaskern/bitcoin,sipsorcery/bitcoin,andreaskern/bitcoin,prusnak/bitcoin,kallewoof/bitcoin,mm-s/bitcoin,n1bor/bitcoin,namecoin/namecore,particl/particl-core,Xekyo/bitcoin,anditto/bitcoin,tecnovert/particl-core,MeshCollider/bitcoin,pataquets/namecoin-core,jamesob/bitcoin,MeshCollider/bitcoin,andreaskern/bitcoin,bitcoin/bitcoin,instagibbs/bitcoin,GroestlCoin/bitcoin,lateminer/bitcoin,pataquets/namecoin-core,kallewoof/bitcoin,apoelstra/bitcoin,namecoin/namecoin-core,sipsorcery/bitcoin,anditto/bitcoin,mm-s/bitcoin,AkioNak/bitcoin,MeshCollider/bitcoin,sstone/bitcoin,qtumproject/qtum,tecnovert/particl-core,ElementsProject/elements,ajtowns/bitcoin,bitcoinknots/bitcoin
503198cd2a24f6fb6a6fbda9827451378515d4ad
SurgSim/Graphics/OsgManager.cpp
SurgSim/Graphics/OsgManager.cpp
// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <SurgSim/Graphics/OsgManager.h> #include <SurgSim/Framework/Log.h> #include <SurgSim/Graphics/OsgRepresentation.h> #include <SurgSim/Graphics/OsgCamera.h> #include <SurgSim/Graphics/OsgGroup.h> #include <SurgSim/Graphics/OsgView.h> #include <osgViewer/Scene> #include <osgDB/WriteFile> using SurgSim::Graphics::OsgRepresentation; using SurgSim::Graphics::OsgCamera; using SurgSim::Graphics::OsgGroup; using SurgSim::Graphics::OsgManager; OsgManager::OsgManager() : SurgSim::Graphics::Manager(), m_viewer(new osgViewer::CompositeViewer()), m_defaultGroup(std::make_shared<OsgGroup>("Default Group")) { m_defaultCamera = std::make_shared<OsgCamera>("Default Camera"); m_defaultCamera->setGroup(m_defaultGroup); } OsgManager::~OsgManager() { } bool OsgManager::setDefaultCamera(std::shared_ptr<OsgCamera> camera) { m_defaultCamera = camera; return true; } std::shared_ptr<OsgCamera> OsgManager::getDefaultCamera() const { return m_defaultCamera; } bool OsgManager::setDefaultGroup(std::shared_ptr<OsgGroup> group) { m_defaultGroup = group; return true; } std::shared_ptr<OsgGroup> OsgManager::getDefaultGroup() const { return m_defaultGroup; } bool OsgManager::addRepresentation(std::shared_ptr<SurgSim::Graphics::Representation> representation) { std::shared_ptr<OsgRepresentation> osgRepresentation = std::dynamic_pointer_cast<OsgRepresentation>(representation); if (osgRepresentation && Manager::addRepresentation(osgRepresentation)) { SURGSIM_ASSERT(m_defaultGroup->add(osgRepresentation)) << "Failed to add representation to default group!"; // Add the component to all the groups that it wants to be in std::vector<std::string> requestedGroups = representation->getGroupReferences(); std::vector<std::shared_ptr<Group>> groups = getGroups(); for (auto it = std::begin(requestedGroups); it != std::end(requestedGroups); ++it) { auto groupIt = std::find_if( std::begin(groups), std::end(groups), [it](std::shared_ptr<Group> group){return *it == group->getName();}); if (groupIt != std::end(groups)) { (*groupIt)->add(representation); } else { SURGSIM_LOG_WARNING(getLogger()) << "OsgManager::addRepresentation: " << "The component <" << representation->getName() << "> requested a group <" << *it << "> that could"<< " not be found"; } } return true; } else { SURGSIM_LOG_INFO(getLogger()) << __FUNCTION__ << " Representation is not a subclass of OsgRepresentation " << representation->getName(); return false; } } bool OsgManager::addGroup(std::shared_ptr<SurgSim::Graphics::Group> group) { std::shared_ptr<OsgGroup> osgGroup = std::dynamic_pointer_cast<OsgGroup>(group); if (osgGroup && Manager::addGroup(osgGroup)) { // Check if there are any represenations that might want to be included // in this group std::string name = group->getName(); auto representations = getRepresentations(); for (auto it = std::begin(representations); it != std::end(representations); ++it) { auto requested = (*it)->getGroupReferences(); if (std::find(std::begin(requested), std::end(requested), name) != std::end(requested)) { group->add(*it); } } return true; } else { SURGSIM_LOG_INFO(getLogger()) << __FUNCTION__ << " Group is not a subclass of OsgGroup " << group->getName(); return false; } } bool OsgManager::addView(std::shared_ptr<SurgSim::Graphics::View> view) { std::shared_ptr<OsgView> osgView = std::dynamic_pointer_cast<OsgView>(view); if (osgView && Manager::addView(osgView)) { if (! osgView->getCamera()) { osgView->setCamera(m_defaultCamera); } else if (! osgView->getCamera()->getGroup()) { osgView->getCamera()->setGroup(m_defaultGroup); } m_viewer->addView(osgView->getOsgView()); return true; } else { SURGSIM_LOG_INFO(getLogger()) << __FUNCTION__ << " View is not a subclass of OsgView " << view->getName(); return false; } } bool OsgManager::removeView(std::shared_ptr<SurgSim::Graphics::View> view) { std::shared_ptr<OsgView> osgView = std::dynamic_pointer_cast<OsgView>(view); if (osgView) { m_viewer->removeView(osgView->getOsgView()); } return Manager::removeView(view); } bool OsgManager::doInitialize() { return true; } bool OsgManager::doStartUp() { return true; } bool OsgManager::doUpdate(double dt) { m_defaultCamera->update(dt); if (Manager::doUpdate(dt)) { m_viewer->frame(); return true; } else { return false; } } void OsgManager::doBeforeStop() { // Delete the viewer so that the graphics context will be released in the manager's thread m_viewer = nullptr; } void SurgSim::Graphics::OsgManager::dumpDebugInfo() const { osgDB::writeNodeFile(*(m_defaultCamera->getOsgCamera()),"default_camera.osgt" ); }
// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <SurgSim/Graphics/OsgManager.h> #include <SurgSim/Framework/Log.h> #include <SurgSim/Graphics/OsgRepresentation.h> #include <SurgSim/Graphics/OsgCamera.h> #include <SurgSim/Graphics/OsgGroup.h> #include <SurgSim/Graphics/OsgView.h> #include <osgViewer/Scene> #include <osgDB/WriteFile> using SurgSim::Graphics::OsgRepresentation; using SurgSim::Graphics::OsgCamera; using SurgSim::Graphics::OsgGroup; using SurgSim::Graphics::OsgManager; OsgManager::OsgManager() : SurgSim::Graphics::Manager(), m_viewer(new osgViewer::CompositeViewer()), m_defaultGroup(std::make_shared<OsgGroup>("Default Group")) { m_defaultCamera = std::make_shared<OsgCamera>("Default Camera"); m_defaultCamera->setGroup(m_defaultGroup); m_defaultGroup->getOsgGroup()-> getOrCreateStateSet()->setGlobalDefaults(); } OsgManager::~OsgManager() { } bool OsgManager::setDefaultCamera(std::shared_ptr<OsgCamera> camera) { m_defaultCamera = camera; return true; } std::shared_ptr<OsgCamera> OsgManager::getDefaultCamera() const { return m_defaultCamera; } bool OsgManager::setDefaultGroup(std::shared_ptr<OsgGroup> group) { m_defaultGroup = group; return true; } std::shared_ptr<OsgGroup> OsgManager::getDefaultGroup() const { return m_defaultGroup; } bool OsgManager::addRepresentation(std::shared_ptr<SurgSim::Graphics::Representation> representation) { std::shared_ptr<OsgRepresentation> osgRepresentation = std::dynamic_pointer_cast<OsgRepresentation>(representation); if (osgRepresentation && Manager::addRepresentation(osgRepresentation)) { SURGSIM_ASSERT(m_defaultGroup->add(osgRepresentation)) << "Failed to add representation to default group!"; // Add the component to all the groups that it wants to be in std::vector<std::string> requestedGroups = representation->getGroupReferences(); std::vector<std::shared_ptr<Group>> groups = getGroups(); for (auto it = std::begin(requestedGroups); it != std::end(requestedGroups); ++it) { auto groupIt = std::find_if( std::begin(groups), std::end(groups), [it](std::shared_ptr<Group> group){return *it == group->getName();}); if (groupIt != std::end(groups)) { (*groupIt)->add(representation); } else { SURGSIM_LOG_WARNING(getLogger()) << "OsgManager::addRepresentation: " << "The component <" << representation->getName() << "> requested a group <" << *it << "> that could"<< " not be found"; } } return true; } else { SURGSIM_LOG_INFO(getLogger()) << __FUNCTION__ << " Representation is not a subclass of OsgRepresentation " << representation->getName(); return false; } } bool OsgManager::addGroup(std::shared_ptr<SurgSim::Graphics::Group> group) { std::shared_ptr<OsgGroup> osgGroup = std::dynamic_pointer_cast<OsgGroup>(group); if (osgGroup && Manager::addGroup(osgGroup)) { // Check if there are any represenations that might want to be included // in this group std::string name = group->getName(); auto representations = getRepresentations(); for (auto it = std::begin(representations); it != std::end(representations); ++it) { auto requested = (*it)->getGroupReferences(); if (std::find(std::begin(requested), std::end(requested), name) != std::end(requested)) { group->add(*it); } } return true; } else { SURGSIM_LOG_INFO(getLogger()) << __FUNCTION__ << " Group is not a subclass of OsgGroup " << group->getName(); return false; } } bool OsgManager::addView(std::shared_ptr<SurgSim::Graphics::View> view) { std::shared_ptr<OsgView> osgView = std::dynamic_pointer_cast<OsgView>(view); if (osgView && Manager::addView(osgView)) { if (! osgView->getCamera()) { osgView->setCamera(m_defaultCamera); } else if (! osgView->getCamera()->getGroup()) { osgView->getCamera()->setGroup(m_defaultGroup); } m_viewer->addView(osgView->getOsgView()); return true; } else { SURGSIM_LOG_INFO(getLogger()) << __FUNCTION__ << " View is not a subclass of OsgView " << view->getName(); return false; } } bool OsgManager::removeView(std::shared_ptr<SurgSim::Graphics::View> view) { std::shared_ptr<OsgView> osgView = std::dynamic_pointer_cast<OsgView>(view); if (osgView) { m_viewer->removeView(osgView->getOsgView()); } return Manager::removeView(view); } bool OsgManager::doInitialize() { return true; } bool OsgManager::doStartUp() { return true; } bool OsgManager::doUpdate(double dt) { m_defaultCamera->update(dt); if (Manager::doUpdate(dt)) { m_viewer->frame(); return true; } else { return false; } } void OsgManager::doBeforeStop() { // Delete the viewer so that the graphics context will be released in the manager's thread m_viewer = nullptr; } void SurgSim::Graphics::OsgManager::dumpDebugInfo() const { osgDB::writeNodeFile(*(m_defaultCamera->getOsgCamera()),"default_camera.osgt" ); }
Fix rendering problem under osg-3.2
Fix rendering problem under osg-3.2 problem was actuall introduced between 3.1.8 and 3.1.9, we needed to set the default state on one stateset to fix this, this might have to move further up the scenegraph
C++
apache-2.0
simquest/opensurgsim,simquest/opensurgsim,simquest/opensurgsim,simquest/opensurgsim
6dcbcead3da45604b84aef9d9496689fef5ff8f5
call/version.cc
call/version.cc
/* * Copyright (c) 2020 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 "call/version.h" namespace webrtc { // The timestamp is always in UTC. const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-19T04:01:32"; void LoadWebRTCVersionInRegister() { // Using volatile to instruct the compiler to not optimize `p` away even // if it looks unused. const char* volatile p = kSourceTimestamp; static_cast<void>(p); } } // namespace webrtc
/* * Copyright (c) 2020 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 "call/version.h" namespace webrtc { // The timestamp is always in UTC. const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-20T04:04:26"; void LoadWebRTCVersionInRegister() { // Using volatile to instruct the compiler to not optimize `p` away even // if it looks unused. const char* volatile p = kSourceTimestamp; static_cast<void>(p); } } // namespace webrtc
Update WebRTC code version (2021-01-20T04:04:26).
Update WebRTC code version (2021-01-20T04:04:26). TBR=26646219319870ca9d01017a011e960429912aaa@webrtc-ci.iam.gserviceaccount.com,[email protected] Bug: None Change-Id: I81bda176d7979d01e7d8c76a03af68d3101b9fc7 Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/202746 Reviewed-by: 26646219319870ca9d01017a011e960429912aaa@webrtc-ci.iam.gserviceaccount.com <26646219319870ca9d01017a011e960429912aaa@webrtc-ci.iam.gserviceaccount.com> Commit-Queue: 26646219319870ca9d01017a011e960429912aaa@webrtc-ci.iam.gserviceaccount.com <26646219319870ca9d01017a011e960429912aaa@webrtc-ci.iam.gserviceaccount.com> Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#33041}
C++
bsd-3-clause
TimothyGu/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,TimothyGu/libilbc
bc08b8eefe534bc930263437715a955e7c1e0f88
src/utp_socket_manager.cpp
src/utp_socket_manager.cpp
/* Copyright (c) 2009, Arvid Norberg 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 author 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 "libtorrent/utp_stream.hpp" #include "libtorrent/udp_socket.hpp" #include "libtorrent/utp_socket_manager.hpp" #include "libtorrent/instantiate_connection.hpp" #include "libtorrent/socket_io.hpp" // #define TORRENT_DEBUG_MTU 1135 namespace libtorrent { utp_socket_manager::utp_socket_manager(session_settings const& sett, udp_socket& s , incoming_utp_callback_t cb) : m_sock(s) , m_cb(cb) , m_last_socket(0) , m_new_connection(-1) , m_sett(sett) {} utp_socket_manager::~utp_socket_manager() { for (socket_map_t::iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end; ++i) { delete_utp_impl(i->second); } } void utp_socket_manager::get_status(utp_status& s) const { s.num_idle = 0; s.num_syn_sent = 0; s.num_connected = 0; s.num_fin_sent = 0; s.num_close_wait = 0; for (socket_map_t::const_iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end; ++i) { int state = utp_socket_state(i->second); switch (state) { case 0: ++s.num_idle; break; case 1: ++s.num_syn_sent; break; case 2: ++s.num_connected; break; case 3: ++s.num_fin_sent; break; case 4: ++s.num_close_wait; break; case 5: ++s.num_close_wait; break; } } } void utp_socket_manager::tick(ptime now) { for (socket_map_t::iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end;) { if (should_delete(i->second)) { delete_utp_impl(i->second); if (m_last_socket == i->second) m_last_socket = 0; m_utp_sockets.erase(i++); continue; } tick_utp_impl(i->second, now); ++i; } } void utp_socket_manager::send_packet(udp::endpoint const& ep, char const* p , int len, error_code& ec, int flags) { if (!m_sock.is_open()) { ec = asio::error::operation_aborted; return; } #ifdef TORRENT_DEBUG_MTU // drop packets that exceed the debug MTU if ((flags & dont_fragment) && len > TORRENT_DEBUG_MTU) return; #endif #ifdef TORRENT_HAS_DONT_FRAGMENT error_code tmp; if (flags & dont_fragment) m_sock.set_option(dont_fragment(true), tmp); #endif m_sock.send(ep, p, len, ec); #ifdef TORRENT_HAS_DONT_FRAGMENT if (flags & dont_fragment) m_sock.set_option(dont_fragment(false), tmp); #endif } tcp::endpoint utp_socket_manager::local_endpoint(error_code& ec) const { return m_sock.local_endpoint(ec); } bool utp_socket_manager::incoming_packet(char const* p, int size, udp::endpoint const& ep) { // UTP_LOGV("incoming packet size:%d\n", size); if (size < sizeof(utp_header)) return false; utp_header const* ph = (utp_header*)p; // UTP_LOGV("incoming packet version:%d\n", int(ph->get_version())); if (ph->get_version() != 1) return false; const ptime receive_time = time_now_hires(); // parse out connection ID and look for existing // connections. If found, forward to the utp_stream. boost::uint16_t id = ph->connection_id; // first test to see if it's the same socket as last time // in most cases it is if (m_last_socket && utp_match(m_last_socket, ep, id)) { return utp_incoming_packet(m_last_socket, p, size, ep, receive_time); } socket_map_t::iterator i = m_utp_sockets.find(id); std::pair<socket_map_t::iterator, socket_map_t::iterator> r = m_utp_sockets.equal_range(id); for (; r.first != r.second; ++r.first) { if (!utp_match(r.first->second, ep, id)) continue; bool ret = utp_incoming_packet(r.first->second, p, size, ep, receive_time); if (ret) m_last_socket = r.first->second; return ret; } // UTP_LOGV("incoming packet id:%d source:%s\n", id, print_endpoint(ep).c_str()); if (!m_sett.enable_incoming_utp) return false; // if not found, see if it's a SYN packet, if it is, // create a new utp_stream if (ph->get_type() == ST_SYN) { // create the new socket with this ID m_new_connection = id; // UTP_LOGV("not found, new connection id:%d\n", m_new_connection); boost::shared_ptr<socket_type> c(new (std::nothrow) socket_type(m_sock.get_io_service())); if (!c) return false; instantiate_connection(m_sock.get_io_service(), proxy_settings(), *c, 0, this); utp_stream* str = c->get<utp_stream>(); TORRENT_ASSERT(str); bool ret = utp_incoming_packet(str->get_impl(), p, size, ep, receive_time); if (!ret) return false; m_cb(c); // the connection most likely changed its connection ID here // we need to move it to the correct ID return true; } // #error send reset return false; } void utp_socket_manager::remove_socket(boost::uint16_t id) { socket_map_t::iterator i = m_utp_sockets.find(id); if (i == m_utp_sockets.end()) return; delete_utp_impl(i->second); if (m_last_socket == i->second) m_last_socket = 0; m_utp_sockets.erase(i); } utp_socket_impl* utp_socket_manager::new_utp_socket(utp_stream* str) { boost::uint16_t send_id = 0; boost::uint16_t recv_id = 0; if (m_new_connection != -1) { send_id = m_new_connection; recv_id = m_new_connection + 1; m_new_connection = -1; } else { send_id = rand(); recv_id = send_id - 1; } utp_socket_impl* impl = construct_utp_impl(recv_id, send_id, str, this); m_utp_sockets.insert(std::make_pair(recv_id, impl)); return impl; } }
/* Copyright (c) 2009, Arvid Norberg 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 author 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 "libtorrent/utp_stream.hpp" #include "libtorrent/udp_socket.hpp" #include "libtorrent/utp_socket_manager.hpp" #include "libtorrent/instantiate_connection.hpp" #include "libtorrent/socket_io.hpp" // #define TORRENT_DEBUG_MTU 1135 namespace libtorrent { utp_socket_manager::utp_socket_manager(session_settings const& sett, udp_socket& s , incoming_utp_callback_t cb) : m_sock(s) , m_cb(cb) , m_last_socket(0) , m_new_connection(-1) , m_sett(sett) {} utp_socket_manager::~utp_socket_manager() { for (socket_map_t::iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end; ++i) { delete_utp_impl(i->second); } } void utp_socket_manager::get_status(utp_status& s) const { s.num_idle = 0; s.num_syn_sent = 0; s.num_connected = 0; s.num_fin_sent = 0; s.num_close_wait = 0; for (socket_map_t::const_iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end; ++i) { int state = utp_socket_state(i->second); switch (state) { case 0: ++s.num_idle; break; case 1: ++s.num_syn_sent; break; case 2: ++s.num_connected; break; case 3: ++s.num_fin_sent; break; case 4: ++s.num_close_wait; break; case 5: ++s.num_close_wait; break; } } } void utp_socket_manager::tick(ptime now) { for (socket_map_t::iterator i = m_utp_sockets.begin() , end(m_utp_sockets.end()); i != end;) { if (should_delete(i->second)) { delete_utp_impl(i->second); if (m_last_socket == i->second) m_last_socket = 0; m_utp_sockets.erase(i++); continue; } tick_utp_impl(i->second, now); ++i; } } void utp_socket_manager::send_packet(udp::endpoint const& ep, char const* p , int len, error_code& ec, int flags) { if (!m_sock.is_open()) { ec = asio::error::operation_aborted; return; } #ifdef TORRENT_DEBUG_MTU // drop packets that exceed the debug MTU if ((flags & dont_fragment) && len > TORRENT_DEBUG_MTU) return; #endif #ifdef TORRENT_HAS_DONT_FRAGMENT error_code tmp; if (flags & utp_socket_manager::dont_fragment) m_sock.set_option(libtorrent::dont_fragment(true), tmp); #endif m_sock.send(ep, p, len, ec); #ifdef TORRENT_HAS_DONT_FRAGMENT if (flags & utp_socket_manager::dont_fragment) m_sock.set_option(libtorrent::dont_fragment(false), tmp); #endif } tcp::endpoint utp_socket_manager::local_endpoint(error_code& ec) const { return m_sock.local_endpoint(ec); } bool utp_socket_manager::incoming_packet(char const* p, int size, udp::endpoint const& ep) { // UTP_LOGV("incoming packet size:%d\n", size); if (size < sizeof(utp_header)) return false; utp_header const* ph = (utp_header*)p; // UTP_LOGV("incoming packet version:%d\n", int(ph->get_version())); if (ph->get_version() != 1) return false; const ptime receive_time = time_now_hires(); // parse out connection ID and look for existing // connections. If found, forward to the utp_stream. boost::uint16_t id = ph->connection_id; // first test to see if it's the same socket as last time // in most cases it is if (m_last_socket && utp_match(m_last_socket, ep, id)) { return utp_incoming_packet(m_last_socket, p, size, ep, receive_time); } socket_map_t::iterator i = m_utp_sockets.find(id); std::pair<socket_map_t::iterator, socket_map_t::iterator> r = m_utp_sockets.equal_range(id); for (; r.first != r.second; ++r.first) { if (!utp_match(r.first->second, ep, id)) continue; bool ret = utp_incoming_packet(r.first->second, p, size, ep, receive_time); if (ret) m_last_socket = r.first->second; return ret; } // UTP_LOGV("incoming packet id:%d source:%s\n", id, print_endpoint(ep).c_str()); if (!m_sett.enable_incoming_utp) return false; // if not found, see if it's a SYN packet, if it is, // create a new utp_stream if (ph->get_type() == ST_SYN) { // create the new socket with this ID m_new_connection = id; // UTP_LOGV("not found, new connection id:%d\n", m_new_connection); boost::shared_ptr<socket_type> c(new (std::nothrow) socket_type(m_sock.get_io_service())); if (!c) return false; instantiate_connection(m_sock.get_io_service(), proxy_settings(), *c, 0, this); utp_stream* str = c->get<utp_stream>(); TORRENT_ASSERT(str); bool ret = utp_incoming_packet(str->get_impl(), p, size, ep, receive_time); if (!ret) return false; m_cb(c); // the connection most likely changed its connection ID here // we need to move it to the correct ID return true; } // #error send reset return false; } void utp_socket_manager::remove_socket(boost::uint16_t id) { socket_map_t::iterator i = m_utp_sockets.find(id); if (i == m_utp_sockets.end()) return; delete_utp_impl(i->second); if (m_last_socket == i->second) m_last_socket = 0; m_utp_sockets.erase(i); } utp_socket_impl* utp_socket_manager::new_utp_socket(utp_stream* str) { boost::uint16_t send_id = 0; boost::uint16_t recv_id = 0; if (m_new_connection != -1) { send_id = m_new_connection; recv_id = m_new_connection + 1; m_new_connection = -1; } else { send_id = rand(); recv_id = send_id - 1; } utp_socket_impl* impl = construct_utp_impl(recv_id, send_id, str, this); m_utp_sockets.insert(std::make_pair(recv_id, impl)); return impl; } }
fix msvc build issue
fix msvc build issue git-svn-id: 4b20f32ac28c752316e0f948a8a743f4a1700c23@4980 a83610d8-ad2a-0410-a6ab-fc0612d85776
C++
bsd-3-clause
cit/libtorrent-peer-idol,kuro/libtorrent,cscheid/libtorrent,kuro/libtorrent,kuro/libtorrent,kuro/libtorrent,cit/libtorrent-peer-idol,cit/libtorrent-peer-idol,cscheid/libtorrent,cscheid/libtorrent,cit/libtorrent-peer-idol,cit/libtorrent-peer-idol,cscheid/libtorrent,cscheid/libtorrent,cit/libtorrent-peer-idol,cscheid/libtorrent
f79efd2b36cce46957d273360d933464e688b97b
server/src/file_system_windows.cpp
server/src/file_system_windows.cpp
#include "file_system.hpp" #include "safe_windows.h" namespace msrv { namespace { inline int64_t makeInt64(DWORD high, DWORD low) { return (static_cast<int64_t>(high) << 32) | static_cast<int64_t>(low); } inline FileType getFileType(DWORD attributes) { return attributes & FILE_ATTRIBUTE_DIRECTORY ? FileType::DIRECTORY : FileType::REGULAR; } inline int64_t getUnixTimestamp(FILETIME time) { return makeInt64(time.dwHighDateTime, time.dwLowDateTime) / INT64_C(10000000) - INT64_C(11644473600); } } Path getModulePath(void* symbol) { ::HMODULE module; auto ret = ::GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast<wchar_t*>(symbol), &module); throwIfFailed("GetModuleHandleExW", ret != 0); Path::string_type path; path.resize(1024); auto size = ::GetModuleFileNameW(module, &path[0], path.length()); throwIfFailed("GetModuleFileNameW", size > 0 && size < path.length()); path.resize(static_cast<size_t>(size)); return Path(std::move(path)); } FileHandle openFile(const Path& path) { return FileHandle(::CreateFileW( path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); } FileInfo queryFileInfo(FileHandle::Type handle) { ::BY_HANDLE_FILE_INFORMATION data; auto ret = ::GetFileInformationByHandle(handle, &data); throwIfFailed("GetFileInformationByHandle", ret != 0); FileInfo info; info.inode = -1; info.size = makeInt64(data.nFileSizeHigh, data.nFileIndexLow); info.type = getFileType(data.dwFileAttributes); info.timestamp = getUnixTimestamp(data.ftLastWriteTime); return info; } FileInfo queryFileInfo(const Path& path) { ::WIN32_FILE_ATTRIBUTE_DATA data; auto ret = ::GetFileAttributesExW(path.native().c_str(), GetFileExInfoStandard, &data); throwIfFailed("GetFileAttributesExW", ret != 0); FileInfo info; info.inode = -1; info.size = makeInt64(data.nFileSizeHigh, data.nFileSizeLow); info.type = getFileType(data.dwFileAttributes); info.timestamp = getUnixTimestamp(data.ftLastWriteTime); return info; } size_t readFile(FileHandle::Type handle, void* buffer, size_t bytes) { DWORD bytesRead; auto ret = ::ReadFile(handle, buffer, static_cast<DWORD>(bytes), &bytesRead, nullptr); throwIfFailed("ReadFile", ret != 0); return bytesRead; } }
#include "file_system.hpp" #include "safe_windows.h" namespace msrv { namespace { inline int64_t makeInt64(DWORD high, DWORD low) { return (static_cast<int64_t>(high) << 32) | static_cast<int64_t>(low); } inline FileType getFileType(DWORD attributes) { return attributes & FILE_ATTRIBUTE_DIRECTORY ? FileType::DIRECTORY : FileType::REGULAR; } inline int64_t getUnixTimestamp(FILETIME time) { return makeInt64(time.dwHighDateTime, time.dwLowDateTime) / INT64_C(10000000) - INT64_C(11644473600); } } Path getModulePath(void* symbol) { ::HMODULE module; auto ret = ::GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast<wchar_t*>(symbol), &module); throwIfFailed("GetModuleHandleExW", ret != 0); Path::string_type path; path.resize(1024); auto size = ::GetModuleFileNameW(module, &path[0], path.length()); throwIfFailed("GetModuleFileNameW", size > 0 && size < path.length()); path.resize(static_cast<size_t>(size)); return Path(std::move(path)); } FileHandle openFile(const Path& path) { return FileHandle(::CreateFileW( path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); } FileInfo queryFileInfo(FileHandle::Type handle) { ::BY_HANDLE_FILE_INFORMATION data; auto ret = ::GetFileInformationByHandle(handle, &data); throwIfFailed("GetFileInformationByHandle", ret != 0); FileInfo info; info.inode = -1; info.size = makeInt64(data.nFileSizeHigh, data.nFileSizeLow); info.type = getFileType(data.dwFileAttributes); info.timestamp = getUnixTimestamp(data.ftLastWriteTime); return info; } FileInfo queryFileInfo(const Path& path) { ::WIN32_FILE_ATTRIBUTE_DATA data; auto ret = ::GetFileAttributesExW(path.native().c_str(), GetFileExInfoStandard, &data); throwIfFailed("GetFileAttributesExW", ret != 0); FileInfo info; info.inode = -1; info.size = makeInt64(data.nFileSizeHigh, data.nFileSizeLow); info.type = getFileType(data.dwFileAttributes); info.timestamp = getUnixTimestamp(data.ftLastWriteTime); return info; } size_t readFile(FileHandle::Type handle, void* buffer, size_t bytes) { DWORD bytesRead; auto ret = ::ReadFile(handle, buffer, static_cast<DWORD>(bytes), &bytesRead, nullptr); throwIfFailed("ReadFile", ret != 0); return bytesRead; } }
fix typo
file_system_windows.cpp: fix typo
C++
mit
hyperblast/beefweb,hyperblast/beefweb,hyperblast/beefweb,hyperblast/beefweb,hyperblast/beefweb
a43f495e84606de1f2169483481a7f36f3cd22b5
tango_ros_common/tango_ros_native/src/tango_3d_reconstruction_helper.cpp
tango_ros_common/tango_ros_native/src/tango_3d_reconstruction_helper.cpp
// Copyright 2017 Intermodalics 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 "tango_ros_native/tango_3d_reconstruction_helper.h" #include "tango_ros_native/tango_ros_conversions_helper.h" #include <glog/logging.h> namespace tango_3d_reconstruction_helper { Tango3DR_Status TangoSetup3DRConfig( const ros::NodeHandle& node_handle, double* t3dr_resolution, Tango3DR_ReconstructionContext* t3dr_context, Tango3DR_CameraCalibration* t3dr_color_camera_intrinsics) { const char* function_name = "TangoRosNode::TangoSetup3DRConfig()"; Tango3DR_Config t3dr_config = Tango3DR_Config_create(TANGO_3DR_CONFIG_RECONSTRUCTION); Tango3DR_Status result; const char* resolution = "resolution"; double t3dr_resolution_param; node_handle.param(TANGO_3DR_RESOLUTION_PARAM_NAME, t3dr_resolution_param, TANGO_3DR_DEFAULT_RESOLUTION); *t3dr_resolution = t3dr_resolution_param; result = Tango3DR_Config_setDouble(t3dr_config, resolution, t3dr_resolution_param); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Tango3DR_Config_setDouble " << resolution << " error: " << result; return result; } const char* generate_color = "generate_color"; result = Tango3DR_Config_setBool(t3dr_config, generate_color, true); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Tango3DR_Config_setBool " << generate_color << " error: " << result; return result; } const char* use_floorplan = "use_floorplan"; result = Tango3DR_Config_setBool(t3dr_config, use_floorplan, true); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Tango3DR_Config_setBool " << use_floorplan << " error: " << result; return result; } const char* use_space_clearing = "use_space_clearing"; bool t3dr_use_space_clearing; node_handle.param(TANGO_3DR_USE_SPACE_CLEARING_PARAM_NAME, t3dr_use_space_clearing, TANGO_3DR_DEFAULT_USE_SPACE_CLEARING); result = Tango3DR_Config_setBool(t3dr_config, use_space_clearing, t3dr_use_space_clearing); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Tango3DR_Config_setBool " << use_space_clearing << " error: " << result; return result; } const char* min_num_vertices = "min_num_vertices"; int t3dr_min_num_vertices; node_handle.param(TANGO_3DR_MIN_NUM_VERTICES_PARAM_NAME, t3dr_min_num_vertices, TANGO_3DR_DEFAULT_MIN_NUM_VERTICES); result = Tango3DR_Config_setInt32(t3dr_config, min_num_vertices, t3dr_min_num_vertices); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Tango3DR_Config_setInt32 " << min_num_vertices << " error: " << result; return result; } const char* update_method = "update_method"; int t3dr_update_method; node_handle.param(TANGO_3DR_UPDATE_METHOD_PARAM_NAME, t3dr_update_method, TANGO_3DR_DEFAULT_UPDATE_METHOD); result = Tango3DR_Config_setInt32(t3dr_config, update_method, t3dr_update_method); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Tango3DR_Config_setInt32 " << update_method << " error: " << result; return result; } const char* max_voxel_weight = "max_voxel_weight"; int t3dr_max_voxel_weight; node_handle.param(TANGO_3DR_MAX_VOXEL_WEIGHT_PARAM_NAME, t3dr_max_voxel_weight, TANGO_3DR_DEFAULT_MAX_VOXEL_WEIGHT); result = Tango3DR_Config_setInt32(t3dr_config, max_voxel_weight, t3dr_max_voxel_weight); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Tango3DR_Config_setInt32 " << max_voxel_weight << " error: " << result; return result; } const char* floorplan_max_error = "floorplan_max_error"; double t3dr_floorplan_max_error; node_handle.param(TANGO_3DR_FLOORPLAN_MAX_ERROR_PARAM_NAME, t3dr_floorplan_max_error, TANGO_3DR_DEFAULT_FLOORPLAN_MAX_ERROR); result = Tango3DR_Config_setDouble(t3dr_config, floorplan_max_error, t3dr_floorplan_max_error); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Tango3DR_Config_setDouble " << floorplan_max_error << " error: " << result; return result; } *t3dr_context = Tango3DR_ReconstructionContext_create(t3dr_config); if (*t3dr_context == nullptr) { LOG(ERROR) << function_name << ", Tango3DR_ReconstructionContext_create error: " "Unable to create 3DR context."; return TANGO_3DR_ERROR; } // Configure the color camera intrinsics to be used with updates to the mesh. result = Tango3DR_ReconstructionContext_setColorCalibration( *t3dr_context, t3dr_color_camera_intrinsics); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Unable to set color calibration."; return TANGO_3DR_ERROR; } return Tango3DR_Config_destroy(t3dr_config); } void UpdateMesh(const Tango3DR_ReconstructionContext& t3dr_context, TangoSupport_PointCloudManager* point_cloud_manager, TangoSupport_ImageBufferManager* image_buffer_manager, Tango3DR_Pose* last_camera_depth_pose, Tango3DR_Pose* last_camera_color_pose, Tango3DR_GridIndexArray* t3dr_updated_indices) { // Get latest point cloud. TangoPointCloud* last_point_cloud; TangoSupport_getLatestPointCloud(point_cloud_manager, &last_point_cloud); Tango3DR_PointCloud t3dr_depth; t3dr_depth.timestamp = last_point_cloud->timestamp; t3dr_depth.num_points = last_point_cloud->num_points; t3dr_depth.points = reinterpret_cast<Tango3DR_Vector4*>( last_point_cloud->points); // Get latest image. TangoImageBuffer* last_color_image_buffer; if (image_buffer_manager != nullptr) { TangoSupport_getLatestImageBuffer(image_buffer_manager, &last_color_image_buffer); Tango3DR_ImageBuffer t3dr_image; t3dr_image.width = last_color_image_buffer->width; t3dr_image.height = last_color_image_buffer->height; t3dr_image.stride = last_color_image_buffer->stride; t3dr_image.timestamp = last_color_image_buffer->timestamp; t3dr_image.format = static_cast<Tango3DR_ImageFormatType>( last_color_image_buffer->format); t3dr_image.data = last_color_image_buffer->data; // Get updated mesh segment indices. Tango3DR_Status result = Tango3DR_updateFromPointCloud(t3dr_context, &t3dr_depth, last_camera_depth_pose, &t3dr_image, last_camera_color_pose, t3dr_updated_indices); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << "Tango3DR_update failed with error code " << result; } } } void ExtractMeshAndConvertToMarkerArray( const Tango3DR_ReconstructionContext& t3dr_context, const Tango3DR_GridIndexArray& t3dr_updated_indices, double time_offset, const std::string& base_frame_id, visualization_msgs::MarkerArray* mesh_marker_array) { for (size_t i = 0; i < t3dr_updated_indices.num_indices; ++i) { // Extract Tango mesh from updated index. Tango3DR_Mesh tango_mesh; Tango3DR_Status result = Tango3DR_extractMeshSegment( t3dr_context, t3dr_updated_indices.indices[i], &tango_mesh); if(result != TANGO_3DR_SUCCESS) { LOG(ERROR) << "Tango3DR_extractMeshSegment failed."; continue; } if (tango_mesh.num_faces == 0) { LOG(INFO) << "Empty mesh extracted."; continue; } // Make mesh marker from tango mesh. visualization_msgs::Marker mesh_marker; tango_ros_conversions_helper::toMeshMarker(t3dr_updated_indices.indices[i], tango_mesh, time_offset, base_frame_id, &mesh_marker); // Free tango mesh once we are finished with it. result = Tango3DR_Mesh_destroy(&tango_mesh); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << "Tango3DR_Mesh_destroy failed with error code: " << result; } if (mesh_marker.points.empty()) { LOG(INFO) << "Empty mesh marker."; continue; } mesh_marker_array->markers.push_back(mesh_marker); } } bool ExtractFloorPlanImageAndConvertToOccupancyGrid( const Tango3DR_ReconstructionContext& t3dr_context, double time_offset, const std::string& base_frame_id, double t3dr_resolution, uint8_t threshold, nav_msgs::OccupancyGrid* occupancy_grid) { Tango3DR_Status result = Tango3DR_updateFullFloorplan(t3dr_context); if (result == TANGO_3DR_SUCCESS) { Tango3DR_Vector2 origin; Tango3DR_ImageBuffer image_grid; result = Tango3DR_extractFullFloorplanImage( t3dr_context, TANGO_3DR_LAYER_SPACE, &origin, &image_grid); if (result == TANGO_3DR_SUCCESS) { tango_ros_conversions_helper::toOccupancyGrid(image_grid, origin, time_offset, base_frame_id, t3dr_resolution, threshold, occupancy_grid); } else { LOG(ERROR) << "Tango3DR_extractFullFloorplanImage failed with error" "code: " << result; return false; } result = Tango3DR_ImageBuffer_destroy(&image_grid); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << "Tango3DR_ImageBuffer_destroy failed with error " "code: " << result; return false; } } else { LOG(ERROR) << "Tango3DR_updateFullFloorplan failed with error " "code: " << result; return false; } return true; } } // namespace tango_3d_reconstruction_helper
// Copyright 2017 Intermodalics 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 "tango_ros_native/tango_3d_reconstruction_helper.h" #include "tango_ros_native/tango_ros_conversions_helper.h" #include <glog/logging.h> namespace tango_3d_reconstruction_helper { Tango3DR_Status TangoSetup3DRConfig( const ros::NodeHandle& node_handle, double* t3dr_resolution, Tango3DR_ReconstructionContext* t3dr_context, Tango3DR_CameraCalibration* t3dr_color_camera_intrinsics) { const char* function_name = "TangoRosNode::TangoSetup3DRConfig()"; Tango3DR_Config t3dr_config = Tango3DR_Config_create(TANGO_3DR_CONFIG_RECONSTRUCTION); Tango3DR_Status result; const char* resolution = "resolution"; double t3dr_resolution_param; node_handle.param(TANGO_3DR_RESOLUTION_PARAM_NAME, t3dr_resolution_param, TANGO_3DR_DEFAULT_RESOLUTION); *t3dr_resolution = t3dr_resolution_param; result = Tango3DR_Config_setDouble(t3dr_config, resolution, t3dr_resolution_param); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Tango3DR_Config_setDouble " << resolution << " error: " << result; return result; } const char* generate_color = "generate_color"; result = Tango3DR_Config_setBool(t3dr_config, generate_color, true); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Tango3DR_Config_setBool " << generate_color << " error: " << result; return result; } const char* use_floorplan = "use_floorplan"; result = Tango3DR_Config_setBool(t3dr_config, use_floorplan, true); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Tango3DR_Config_setBool " << use_floorplan << " error: " << result; return result; } const char* use_space_clearing = "use_space_clearing"; bool t3dr_use_space_clearing; node_handle.param(TANGO_3DR_USE_SPACE_CLEARING_PARAM_NAME, t3dr_use_space_clearing, TANGO_3DR_DEFAULT_USE_SPACE_CLEARING); result = Tango3DR_Config_setBool(t3dr_config, use_space_clearing, t3dr_use_space_clearing); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Tango3DR_Config_setBool " << use_space_clearing << " error: " << result; return result; } const char* min_num_vertices = "min_num_vertices"; int t3dr_min_num_vertices; node_handle.param(TANGO_3DR_MIN_NUM_VERTICES_PARAM_NAME, t3dr_min_num_vertices, TANGO_3DR_DEFAULT_MIN_NUM_VERTICES); result = Tango3DR_Config_setInt32(t3dr_config, min_num_vertices, t3dr_min_num_vertices); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Tango3DR_Config_setInt32 " << min_num_vertices << " error: " << result; return result; } const char* update_method = "update_method"; int t3dr_update_method; node_handle.param(TANGO_3DR_UPDATE_METHOD_PARAM_NAME, t3dr_update_method, TANGO_3DR_DEFAULT_UPDATE_METHOD); result = Tango3DR_Config_setInt32(t3dr_config, update_method, t3dr_update_method); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Tango3DR_Config_setInt32 " << update_method << " error: " << result; return result; } const char* max_voxel_weight = "max_voxel_weight"; int t3dr_max_voxel_weight; node_handle.param(TANGO_3DR_MAX_VOXEL_WEIGHT_PARAM_NAME, t3dr_max_voxel_weight, TANGO_3DR_DEFAULT_MAX_VOXEL_WEIGHT); result = Tango3DR_Config_setInt32(t3dr_config, max_voxel_weight, t3dr_max_voxel_weight); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Tango3DR_Config_setInt32 " << max_voxel_weight << " error: " << result; return result; } const char* floorplan_max_error = "floorplan_max_error"; double t3dr_floorplan_max_error; node_handle.param(TANGO_3DR_FLOORPLAN_MAX_ERROR_PARAM_NAME, t3dr_floorplan_max_error, TANGO_3DR_DEFAULT_FLOORPLAN_MAX_ERROR); result = Tango3DR_Config_setDouble(t3dr_config, floorplan_max_error, t3dr_floorplan_max_error); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Tango3DR_Config_setDouble " << floorplan_max_error << " error: " << result; return result; } *t3dr_context = Tango3DR_ReconstructionContext_create(t3dr_config); if (*t3dr_context == nullptr) { LOG(ERROR) << function_name << ", Tango3DR_ReconstructionContext_create error: " "Unable to create 3DR context."; return TANGO_3DR_ERROR; } // Configure the color camera intrinsics to be used with updates to the mesh. result = Tango3DR_ReconstructionContext_setColorCalibration( *t3dr_context, t3dr_color_camera_intrinsics); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << function_name << ", Unable to set color calibration."; return TANGO_3DR_ERROR; } return Tango3DR_Config_destroy(t3dr_config); } void UpdateMesh(const Tango3DR_ReconstructionContext& t3dr_context, TangoSupport_PointCloudManager* point_cloud_manager, TangoSupport_ImageBufferManager* image_buffer_manager, Tango3DR_Pose* last_camera_depth_pose, Tango3DR_Pose* last_camera_color_pose, Tango3DR_GridIndexArray* t3dr_updated_indices) { // Get latest point cloud. TangoPointCloud* last_point_cloud; TangoSupport_getLatestPointCloud(point_cloud_manager, &last_point_cloud); Tango3DR_PointCloud t3dr_depth; t3dr_depth.timestamp = last_point_cloud->timestamp; t3dr_depth.num_points = last_point_cloud->num_points; t3dr_depth.points = reinterpret_cast<Tango3DR_Vector4*>( last_point_cloud->points); // Get latest image. TangoImageBuffer* last_color_image_buffer; if (image_buffer_manager != nullptr) { TangoSupport_getLatestImageBuffer(image_buffer_manager, &last_color_image_buffer); Tango3DR_ImageBuffer t3dr_image; t3dr_image.width = last_color_image_buffer->width; t3dr_image.height = last_color_image_buffer->height; t3dr_image.stride = last_color_image_buffer->stride; t3dr_image.timestamp = last_color_image_buffer->timestamp; t3dr_image.format = static_cast<Tango3DR_ImageFormatType>( last_color_image_buffer->format); t3dr_image.data = last_color_image_buffer->data; // Get updated mesh segment indices. Tango3DR_Status result = Tango3DR_updateFromPointCloud(t3dr_context, &t3dr_depth, last_camera_depth_pose, &t3dr_image, last_camera_color_pose, t3dr_updated_indices); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << "Tango3DR_updateFromPointCloud failed with error code " << result; } } } void ExtractMeshAndConvertToMarkerArray( const Tango3DR_ReconstructionContext& t3dr_context, const Tango3DR_GridIndexArray& t3dr_updated_indices, double time_offset, const std::string& base_frame_id, visualization_msgs::MarkerArray* mesh_marker_array) { for (size_t i = 0; i < t3dr_updated_indices.num_indices; ++i) { // Extract Tango mesh from updated index. Tango3DR_Mesh tango_mesh; Tango3DR_Status result = Tango3DR_extractMeshSegment( t3dr_context, t3dr_updated_indices.indices[i], &tango_mesh); if(result != TANGO_3DR_SUCCESS) { LOG(ERROR) << "Tango3DR_extractMeshSegment failed."; continue; } if (tango_mesh.num_faces == 0) { LOG(INFO) << "Empty mesh extracted."; continue; } // Make mesh marker from tango mesh. visualization_msgs::Marker mesh_marker; tango_ros_conversions_helper::toMeshMarker(t3dr_updated_indices.indices[i], tango_mesh, time_offset, base_frame_id, &mesh_marker); // Free tango mesh once we are finished with it. result = Tango3DR_Mesh_destroy(&tango_mesh); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << "Tango3DR_Mesh_destroy failed with error code: " << result; } if (mesh_marker.points.empty()) { LOG(INFO) << "Empty mesh marker."; continue; } mesh_marker_array->markers.push_back(mesh_marker); } } bool ExtractFloorPlanImageAndConvertToOccupancyGrid( const Tango3DR_ReconstructionContext& t3dr_context, double time_offset, const std::string& base_frame_id, double t3dr_resolution, uint8_t threshold, nav_msgs::OccupancyGrid* occupancy_grid) { Tango3DR_Status result = Tango3DR_updateFullFloorplan(t3dr_context); if (result == TANGO_3DR_SUCCESS) { Tango3DR_Vector2 origin; Tango3DR_ImageBuffer image_grid; result = Tango3DR_extractFullFloorplanImage( t3dr_context, TANGO_3DR_LAYER_SPACE, &origin, &image_grid); if (result == TANGO_3DR_SUCCESS) { tango_ros_conversions_helper::toOccupancyGrid(image_grid, origin, time_offset, base_frame_id, t3dr_resolution, threshold, occupancy_grid); } else { LOG(ERROR) << "Tango3DR_extractFullFloorplanImage failed with error" "code: " << result; return false; } result = Tango3DR_ImageBuffer_destroy(&image_grid); if (result != TANGO_3DR_SUCCESS) { LOG(ERROR) << "Tango3DR_ImageBuffer_destroy failed with error " "code: " << result; return false; } } else { LOG(ERROR) << "Tango3DR_updateFullFloorplan failed with error " "code: " << result; return false; } return true; } } // namespace tango_3d_reconstruction_helper
Correct nits
Correct nits
C++
apache-2.0
Intermodalics/tango_ros,Intermodalics/tango_ros,Intermodalics/tango_ros,Intermodalics/tango_ros
c6089f795eb9d5e72f5db5c530d73bc901245e2a
src/vm/eventpipebuffer.cpp
src/vm/eventpipebuffer.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "common.h" #include "eventpipe.h" #include "eventpipeeventinstance.h" #include "eventpipebuffer.h" #ifdef FEATURE_PERFTRACING EventPipeBuffer::EventPipeBuffer(unsigned int bufferSize) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; m_pBuffer = new BYTE[bufferSize]; memset(m_pBuffer, 0, bufferSize); m_pLimit = m_pBuffer + bufferSize; m_pCurrent = GetNextAlignedAddress(m_pBuffer); m_mostRecentTimeStamp.QuadPart = 0; m_pLastPoppedEvent = NULL; m_pPrevBuffer = NULL; m_pNextBuffer = NULL; } EventPipeBuffer::~EventPipeBuffer() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; if(m_pBuffer != NULL) { delete[] m_pBuffer; } } bool EventPipeBuffer::WriteEvent(Thread *pThread, EventPipeSession &session, EventPipeEvent &event, EventPipeEventPayload &payload, LPCGUID pActivityId, LPCGUID pRelatedActivityId, StackContents *pStack) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; PRECONDITION(((size_t)m_pCurrent % AlignmentSize) == 0); } CONTRACTL_END; // Calculate the size of the event. unsigned int eventSize = sizeof(EventPipeEventInstance) + payload.GetSize(); // Make sure we have enough space to write the event. if(m_pCurrent + eventSize >= m_pLimit) { return false; } bool success = true; EX_TRY { // Calculate the location of the data payload. BYTE *pDataDest = payload.GetSize() == 0 ? NULL : m_pCurrent + sizeof(EventPipeEventInstance); // Placement-new the EventPipeEventInstance. // if pthread is NULL, it's likely we are running in something like a GC thread which is not a Thread object, so it can't have an activity ID set anyway EventPipeEventInstance *pInstance = new (m_pCurrent) EventPipeEventInstance( session, event, (pThread == NULL) ? ::GetCurrentThreadId() : pThread->GetOSThreadId(), pDataDest, payload.GetSize(), (pThread == NULL) ? NULL : pActivityId, pRelatedActivityId); pInstance->EnsureStack(session); // TODO: Perform the stackwalk before the constructor // Copy the stack if a separate stack trace was provided. if(pStack != NULL) { StackContents *pInstanceStack = pInstance->GetStack(); pStack->CopyTo(pInstanceStack); } // Write the event payload data to the buffer. if(payload.GetSize() > 0) { payload.CopyData(pDataDest); } // Save the most recent event timestamp. m_mostRecentTimeStamp = *pInstance->GetTimeStamp(); } EX_CATCH { // If a failure occurs, bail out and don't advance the pointer. success = false; } EX_END_CATCH(SwallowAllExceptions); if(success) { // Advance the current pointer past the event. m_pCurrent = GetNextAlignedAddress(m_pCurrent + eventSize); } return success; } LARGE_INTEGER EventPipeBuffer::GetMostRecentTimeStamp() const { LIMITED_METHOD_CONTRACT; return m_mostRecentTimeStamp; } void EventPipeBuffer::Clear() { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; memset(m_pBuffer, 0, (size_t)(m_pLimit - m_pBuffer)); m_pCurrent = GetNextAlignedAddress(m_pBuffer); m_mostRecentTimeStamp.QuadPart = 0; m_pLastPoppedEvent = NULL; } EventPipeEventInstance* EventPipeBuffer::GetNext(EventPipeEventInstance *pEvent, LARGE_INTEGER beforeTimeStamp) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; EventPipeEventInstance *pNextInstance = NULL; // If input is NULL, return the first event if there is one. if(pEvent == NULL) { // If this buffer contains an event, select it. BYTE *pFirstAlignedInstance = GetNextAlignedAddress(m_pBuffer); if(m_pCurrent > pFirstAlignedInstance) { pNextInstance = (EventPipeEventInstance*)pFirstAlignedInstance; } else { return NULL; } } else { // Confirm that pEvent is within the used range of the buffer. if(((BYTE*)pEvent < m_pBuffer) || ((BYTE*)pEvent >= m_pCurrent)) { _ASSERT(!"Input pointer is out of range."); return NULL; } if (pEvent->GetData()) { // We have a pointer within the bounds of the buffer. // Find the next event by skipping the current event with it's data payload immediately after the instance. pNextInstance = (EventPipeEventInstance *)GetNextAlignedAddress(const_cast<BYTE *>(pEvent->GetData() + pEvent->GetDataLength())); } else { // In case we do not have a payload, the next instance is right after the current instance pNextInstance = (EventPipeEventInstance*)GetNextAlignedAddress((BYTE*)(pEvent + 1)); } // Check to see if we've reached the end of the written portion of the buffer. if((BYTE*)pNextInstance >= m_pCurrent) { return NULL; } } // Ensure that the timestamp is valid. The buffer is zero'd before use, so a zero timestamp is invalid. LARGE_INTEGER nextTimeStamp = *pNextInstance->GetTimeStamp(); if(nextTimeStamp.QuadPart == 0) { return NULL; } // Ensure that the timestamp is earlier than the beforeTimeStamp. if(nextTimeStamp.QuadPart >= beforeTimeStamp.QuadPart) { return NULL; } return pNextInstance; } EventPipeEventInstance* EventPipeBuffer::PeekNext(LARGE_INTEGER beforeTimeStamp) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // Get the next event using the last popped event as a marker. return GetNext(m_pLastPoppedEvent, beforeTimeStamp); } EventPipeEventInstance* EventPipeBuffer::PopNext(LARGE_INTEGER beforeTimeStamp) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // Get the next event using the last popped event as a marker. EventPipeEventInstance *pNext = PeekNext(beforeTimeStamp); if(pNext != NULL) { m_pLastPoppedEvent = pNext; } return pNext; } #ifdef _DEBUG bool EventPipeBuffer::EnsureConsistency() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // Check to see if the buffer is empty. if(GetNextAlignedAddress(m_pBuffer) == m_pCurrent) { // Make sure that the buffer size is greater than zero. _ASSERTE(m_pBuffer != m_pLimit); } // Validate the contents of the filled portion of the buffer. BYTE *ptr = GetNextAlignedAddress(m_pBuffer); while(ptr < m_pCurrent) { // Validate the event. EventPipeEventInstance *pInstance = (EventPipeEventInstance*)ptr; _ASSERTE(pInstance->EnsureConsistency()); // Validate that payload and length match. _ASSERTE((pInstance->GetData() != NULL && pInstance->GetDataLength() > 0) || (pInstance->GetData() == NULL && pInstance->GetDataLength() == 0)); // Skip the event. ptr = GetNextAlignedAddress(ptr + sizeof(*pInstance) + pInstance->GetDataLength()); } // When we're done walking the filled portion of the buffer, // ptr should be the same as m_pCurrent. _ASSERTE(ptr == m_pCurrent); // Walk the rest of the buffer, making sure it is properly zeroed. while(ptr < m_pLimit) { _ASSERTE(*ptr++ == 0); } return true; } #endif // _DEBUG #endif // FEATURE_PERFTRACING
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "common.h" #include "eventpipe.h" #include "eventpipeeventinstance.h" #include "eventpipebuffer.h" #ifdef FEATURE_PERFTRACING EventPipeBuffer::EventPipeBuffer(unsigned int bufferSize) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; m_pBuffer = new BYTE[bufferSize]; memset(m_pBuffer, 0, bufferSize); m_pLimit = m_pBuffer + bufferSize; m_pCurrent = GetNextAlignedAddress(m_pBuffer); m_mostRecentTimeStamp.QuadPart = 0; m_pLastPoppedEvent = NULL; m_pPrevBuffer = NULL; m_pNextBuffer = NULL; } EventPipeBuffer::~EventPipeBuffer() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; if(m_pBuffer != NULL) { delete[] m_pBuffer; } } bool EventPipeBuffer::WriteEvent(Thread *pThread, EventPipeSession &session, EventPipeEvent &event, EventPipeEventPayload &payload, LPCGUID pActivityId, LPCGUID pRelatedActivityId, StackContents *pStack) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; PRECONDITION(((size_t)m_pCurrent % AlignmentSize) == 0); } CONTRACTL_END; // Calculate the size of the event. unsigned int eventSize = sizeof(EventPipeEventInstance) + payload.GetSize(); // Make sure we have enough space to write the event. if(m_pCurrent + eventSize >= m_pLimit) { return false; } bool success = true; EX_TRY { // Calculate the location of the data payload. BYTE *pDataDest = payload.GetSize() == 0 ? NULL : m_pCurrent + sizeof(EventPipeEventInstance); // Placement-new the EventPipeEventInstance. // if pthread is NULL, it's likely we are running in something like a GC thread which is not a Thread object, so it can't have an activity ID set anyway StackContents s; memset((void*)&s, 0, sizeof(s)); if (event.NeedStack() && !session.RundownEnabled() && pStack == NULL) { EventPipe::WalkManagedStackForCurrentThread(s); pStack = &s; } EventPipeEventInstance *pInstance = new (m_pCurrent) EventPipeEventInstance( session, event, (pThread == NULL) ? ::GetCurrentThreadId() : pThread->GetOSThreadId(), pDataDest, payload.GetSize(), (pThread == NULL) ? NULL : pActivityId, pRelatedActivityId); // Copy the stack if a separate stack trace was provided. if (pStack != NULL) { StackContents *pInstanceStack = pInstance->GetStack(); pStack->CopyTo(pInstanceStack); } // Write the event payload data to the buffer. if(payload.GetSize() > 0) { payload.CopyData(pDataDest); } // Save the most recent event timestamp. m_mostRecentTimeStamp = *pInstance->GetTimeStamp(); } EX_CATCH { // If a failure occurs, bail out and don't advance the pointer. success = false; } EX_END_CATCH(SwallowAllExceptions); if(success) { // Advance the current pointer past the event. m_pCurrent = GetNextAlignedAddress(m_pCurrent + eventSize); } return success; } LARGE_INTEGER EventPipeBuffer::GetMostRecentTimeStamp() const { LIMITED_METHOD_CONTRACT; return m_mostRecentTimeStamp; } void EventPipeBuffer::Clear() { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; memset(m_pBuffer, 0, (size_t)(m_pLimit - m_pBuffer)); m_pCurrent = GetNextAlignedAddress(m_pBuffer); m_mostRecentTimeStamp.QuadPart = 0; m_pLastPoppedEvent = NULL; } EventPipeEventInstance* EventPipeBuffer::GetNext(EventPipeEventInstance *pEvent, LARGE_INTEGER beforeTimeStamp) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; EventPipeEventInstance *pNextInstance = NULL; // If input is NULL, return the first event if there is one. if(pEvent == NULL) { // If this buffer contains an event, select it. BYTE *pFirstAlignedInstance = GetNextAlignedAddress(m_pBuffer); if(m_pCurrent > pFirstAlignedInstance) { pNextInstance = (EventPipeEventInstance*)pFirstAlignedInstance; } else { return NULL; } } else { // Confirm that pEvent is within the used range of the buffer. if(((BYTE*)pEvent < m_pBuffer) || ((BYTE*)pEvent >= m_pCurrent)) { _ASSERT(!"Input pointer is out of range."); return NULL; } if (pEvent->GetData()) { // We have a pointer within the bounds of the buffer. // Find the next event by skipping the current event with it's data payload immediately after the instance. pNextInstance = (EventPipeEventInstance *)GetNextAlignedAddress(const_cast<BYTE *>(pEvent->GetData() + pEvent->GetDataLength())); } else { // In case we do not have a payload, the next instance is right after the current instance pNextInstance = (EventPipeEventInstance*)GetNextAlignedAddress((BYTE*)(pEvent + 1)); } // Check to see if we've reached the end of the written portion of the buffer. if((BYTE*)pNextInstance >= m_pCurrent) { return NULL; } } // Ensure that the timestamp is valid. The buffer is zero'd before use, so a zero timestamp is invalid. LARGE_INTEGER nextTimeStamp = *pNextInstance->GetTimeStamp(); if(nextTimeStamp.QuadPart == 0) { return NULL; } // Ensure that the timestamp is earlier than the beforeTimeStamp. if(nextTimeStamp.QuadPart >= beforeTimeStamp.QuadPart) { return NULL; } return pNextInstance; } EventPipeEventInstance* EventPipeBuffer::PeekNext(LARGE_INTEGER beforeTimeStamp) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // Get the next event using the last popped event as a marker. return GetNext(m_pLastPoppedEvent, beforeTimeStamp); } EventPipeEventInstance* EventPipeBuffer::PopNext(LARGE_INTEGER beforeTimeStamp) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // Get the next event using the last popped event as a marker. EventPipeEventInstance *pNext = PeekNext(beforeTimeStamp); if(pNext != NULL) { m_pLastPoppedEvent = pNext; } return pNext; } #ifdef _DEBUG bool EventPipeBuffer::EnsureConsistency() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // Check to see if the buffer is empty. if(GetNextAlignedAddress(m_pBuffer) == m_pCurrent) { // Make sure that the buffer size is greater than zero. _ASSERTE(m_pBuffer != m_pLimit); } // Validate the contents of the filled portion of the buffer. BYTE *ptr = GetNextAlignedAddress(m_pBuffer); while(ptr < m_pCurrent) { // Validate the event. EventPipeEventInstance *pInstance = (EventPipeEventInstance*)ptr; _ASSERTE(pInstance->EnsureConsistency()); // Validate that payload and length match. _ASSERTE((pInstance->GetData() != NULL && pInstance->GetDataLength() > 0) || (pInstance->GetData() == NULL && pInstance->GetDataLength() == 0)); // Skip the event. ptr = GetNextAlignedAddress(ptr + sizeof(*pInstance) + pInstance->GetDataLength()); } // When we're done walking the filled portion of the buffer, // ptr should be the same as m_pCurrent. _ASSERTE(ptr == m_pCurrent); // Walk the rest of the buffer, making sure it is properly zeroed. while(ptr < m_pLimit) { _ASSERTE(*ptr++ == 0); } return true; } #endif // _DEBUG #endif // FEATURE_PERFTRACING
Fix issue 23151 (Cleanup TODO introduced by PR #23148)
Fix issue 23151 (Cleanup TODO introduced by PR #23148)
C++
mit
wtgodbe/coreclr,krk/coreclr,poizan42/coreclr,cshung/coreclr,wtgodbe/coreclr,krk/coreclr,poizan42/coreclr,krk/coreclr,krk/coreclr,poizan42/coreclr,poizan42/coreclr,krk/coreclr,krk/coreclr,poizan42/coreclr,cshung/coreclr,cshung/coreclr,wtgodbe/coreclr,wtgodbe/coreclr,cshung/coreclr,cshung/coreclr,poizan42/coreclr,cshung/coreclr,wtgodbe/coreclr,wtgodbe/coreclr
413beb552c3ff677db999984d5b78d1130e34a0e
ch06/ex6_10.cpp
ch06/ex6_10.cpp
//!@Yue wang //! //! Exercise 6.10: //! Using pointers, write a function to swap the values of two ints. //! Test the function by calling it and printing the swapped values. //! #include <iostream> #include <string> #include <stdexcept> void swap(int* lhs, int* rhs) { int tmp; tmp = *lhs; *lhs = *rhs; *rhs = tmp; } int main() { for (int lft, rht; std::cout << "Please Enter:\n", std::cin >> lft >> rht;) { swap(&lft, &rht); std::cout << lft << " " << rht << std::endl; } return 0; }
//!@Yue wang //! //! Exercise 6.10: //! Using pointers, write a function to swap the values of two ints. //! Test the function by calling it and printing the swapped values. //! #include <iostream> void swap(int* lhs, int* rhs) { int tmp; tmp = *lhs; *lhs = *rhs; *rhs = tmp; } int main() { for (int lft, rht; std::cout << "Please Enter:\n", std::cin >> lft >> rht;) { swap(&lft, &rht); std::cout << lft << " " << rht << std::endl; } return 0; }
Update ex6_10.cpp
Update ex6_10.cpp
C++
cc0-1.0
zhangzhizhongz3/CppPrimer,zhangzhizhongz3/CppPrimer
9f8b874964e5c83b25865a94dede8681dc625a66
gripper_action_controller/src/gripper_action_controller.cpp
gripper_action_controller/src/gripper_action_controller.cpp
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2014, SRI International // // 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 SRI International 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 Sachin Chitta // Pluginlib #include <pluginlib/class_list_macros.h> // Project #include <gripper_action_controller/gripper_action_controller.h> namespace position_controllers { /** * \brief Gripper action controller that sends * commands to a \b position interface. */ typedef gripper_action_controller::GripperActionController<hardware_interface::PositionJointInterface> GripperActionController; } namespace effort_controllers { /** * \brief Gripper action controller that sends * commands to a \b position interface. */ typedef gripper_action_controller::GripperActionController<hardware_interface::EffortJointInterface> GripperActionController; } PLUGINLIB_EXPORT_CLASS(position_controllers::GripperActionController, controller_interface::ControllerBase) PLUGINLIB_EXPORT_CLASS(effort_controllers::GripperActionController, controller_interface::ControllerBase)
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2014, SRI International // // 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 SRI International 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 Sachin Chitta // Pluginlib #include <pluginlib/class_list_macros.h> // Project #include <gripper_action_controller/gripper_action_controller.h> namespace position_controllers { /** * \brief Gripper action controller that sends * commands to a \b position interface. */ typedef gripper_action_controller::GripperActionController<hardware_interface::PositionJointInterface> GripperActionController; } namespace effort_controllers { /** * \brief Gripper action controller that sends * commands to a \b effort interface. */ typedef gripper_action_controller::GripperActionController<hardware_interface::EffortJointInterface> GripperActionController; } PLUGINLIB_EXPORT_CLASS(position_controllers::GripperActionController, controller_interface::ControllerBase) PLUGINLIB_EXPORT_CLASS(effort_controllers::GripperActionController, controller_interface::ControllerBase)
Update gripper_action_controller.cpp
Update gripper_action_controller.cpp
C++
bsd-3-clause
ros-controls/ros_controllers,ros-controls/ros_controllers
f53ca04b0a71fe6d21f2ea24f57d46e2ef4a81ed
Rpr/WrapObject/Materials/ImageMaterialObject.cpp
Rpr/WrapObject/Materials/ImageMaterialObject.cpp
/********************************************************************** Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. 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 <OpenImageIO/imageio.h> #include <map> #include <memory> #include "math/int2.h" #include "SceneGraph/texture.h" #include "SceneGraph/material.h" #include "SceneGraph/IO/image_io.h" #include "SceneGraph/iterator.h" #include "ImageMaterialObject.h" #include "WrapObject/Exception.h" using namespace RadeonRays; using namespace Baikal; ImageMaterialObject::ImageMaterialObject(rpr_image_format const in_format, rpr_image_desc const * in_image_desc, void const * in_data) : MaterialObject(Type::kImage) { //tex size int2 tex_size(in_image_desc->image_width, in_image_desc->image_height); //texture takes ownership of its data array //so need to copy input data int pixels_count = tex_size.x * tex_size.y; //bytes per pixel int pixel_bytes = in_format.num_components; int component_bytes = 1; Texture::Format data_format = Texture::Format::kRgba8; switch (in_format.type) { case RPR_COMPONENT_TYPE_UINT8: break; case RPR_COMPONENT_TYPE_FLOAT16: component_bytes = 2; data_format = Texture::Format::kRgba16; break; case RPR_COMPONENT_TYPE_FLOAT32: component_bytes = 4; data_format = Texture::Format::kRgba32; break; default: throw Exception(RPR_ERROR_INVALID_PARAMETER, "TextureObject: invalid format type."); } pixel_bytes *= component_bytes; int data_size = 4 * component_bytes * pixels_count;//4 component baikal texture char* data = new char[data_size]; if (in_format.num_components == 4) { //copy data memcpy(data, in_data, data_size); } else { //copy to 4component texture const char* in_data_cast = static_cast<const char*>(in_data); for (int i = 0; i < pixels_count; ++i) { //copy for (unsigned int comp_ind = 0; comp_ind < in_format.num_components; ++comp_ind) { int index = comp_ind * component_bytes; memcpy(&data[i * 4 * component_bytes + index], &in_data_cast[i * in_format.num_components * component_bytes + index], component_bytes); } //clean other colors for (unsigned int comp_ind = in_format.num_components; comp_ind < 4; ++comp_ind) { memset(&data[i * 4 + comp_ind], 0, component_bytes); } } } m_tex = Texture::Create(data, tex_size, data_format); } ImageMaterialObject::ImageMaterialObject(const std::string& in_path) : MaterialObject(Type::kImage) { //load texture using oiio std::unique_ptr<ImageIo> oiio = ImageIo::CreateImageIo(); Texture::Ptr texture = nullptr; try { texture = oiio->LoadImage(in_path); } catch (...) { throw Exception(RPR_ERROR_IO_ERROR, "TextureObject: failed to load image."); } m_tex = texture; } Baikal::Texture::Ptr ImageMaterialObject::GetTexture() { return m_tex; }
/********************************************************************** Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. 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 <OpenImageIO/imageio.h> #include <map> #include <memory> #include "math/int2.h" #include "SceneGraph/texture.h" #include "SceneGraph/material.h" #include "SceneGraph/IO/image_io.h" #include "SceneGraph/iterator.h" #include "ImageMaterialObject.h" #include "WrapObject/Exception.h" using namespace RadeonRays; using namespace Baikal; ImageMaterialObject::ImageMaterialObject(rpr_image_format const in_format, rpr_image_desc const * in_image_desc, void const * in_data) : MaterialObject(Type::kImage) { //tex size int2 tex_size(in_image_desc->image_width, in_image_desc->image_height); //texture takes ownership of its data array //so need to copy input data int pixels_count = tex_size.x * tex_size.y; //bytes per pixel int pixel_bytes = in_format.num_components; int component_bytes = 1; Texture::Format data_format = Texture::Format::kRgba8; switch (in_format.type) { case RPR_COMPONENT_TYPE_UINT8: break; case RPR_COMPONENT_TYPE_FLOAT16: component_bytes = 2; data_format = Texture::Format::kRgba16; break; case RPR_COMPONENT_TYPE_FLOAT32: component_bytes = 4; data_format = Texture::Format::kRgba32; break; default: throw Exception(RPR_ERROR_INVALID_PARAMETER, "TextureObject: invalid format type."); } pixel_bytes *= component_bytes; int data_size = 4 * component_bytes * pixels_count;//4 component baikal texture char* data = new char[data_size]; if (in_format.num_components == 4) { //copy data memcpy(data, in_data, data_size); } else { //copy to 4component texture const char* in_data_cast = static_cast<const char*>(in_data); for (int i = 0; i < pixels_count; ++i) { //copy for (unsigned int comp_ind = 0; comp_ind < in_format.num_components; ++comp_ind) { int index = comp_ind * component_bytes; memcpy(&data[i * 4 * component_bytes + index], &in_data_cast[i * in_format.num_components * component_bytes + index], component_bytes); } //clean other colors for (unsigned int comp_ind = in_format.num_components; comp_ind < 4; ++comp_ind) { int index = comp_ind * component_bytes; memset(&data[i * 4 + index], 0, component_bytes); } } } m_tex = Texture::Create(data, tex_size, data_format); } ImageMaterialObject::ImageMaterialObject(const std::string& in_path) : MaterialObject(Type::kImage) { //load texture using oiio std::unique_ptr<ImageIo> oiio = ImageIo::CreateImageIo(); Texture::Ptr texture = nullptr; try { texture = oiio->LoadImage(in_path); } catch (...) { throw Exception(RPR_ERROR_IO_ERROR, "TextureObject: failed to load image."); } m_tex = texture; } Baikal::Texture::Ptr ImageMaterialObject::GetTexture() { return m_tex; }
fix invalid texture copying.
fix invalid texture copying.
C++
mit
fo-fo/RadeonProRender-Baikal,GPUOpen-LibrariesAndSDKs/RadeonProRender-Baikal,GPUOpen-LibrariesAndSDKs/RadeonProRender-Baikal,fo-fo/RadeonProRender-Baikal,fo-fo/RadeonProRender-Baikal,GPUOpen-LibrariesAndSDKs/RadeonProRender-Baikal
6f72538207f292588172eee42e42933af3df440d
include/alloutil/al_ControlNav.hpp
include/alloutil/al_ControlNav.hpp
#ifndef INC_AL_CONTROL_NAV_HPP #define INC_AL_CONTROL_NAV_HPP #include "allocore/io/al_Window.hpp" #include "allocore/spatial/al_Pose.hpp" namespace al { /// Mapping from keyboard and mouse controls to a Nav object struct NavInputControl : public InputEventHandler { NavInputControl(Nav& nav, double vscale = 0.125, double tscale = 2.) : mNav(&nav), mVScale(vscale), mTScale(tscale) {} virtual ~NavInputControl() {} void nav(Nav * v){ mNav=v; } virtual bool onKeyDown(const Keyboard& k){ if(k.ctrl()) return true; double vs = nav().velScale(); double a = mTScale * vs * M_DEG2RAD; // rotational speed: degrees per update double v = mVScale * vs; // speed: units per update if(k.alt()) v *= 10; if(k.shift()) v *= 0.1; switch(k.key()){ case '`': nav().halt().home(); return false; case 's': nav().halt(); return false; case Key::Up: nav().spinR( a); return false; case Key::Down: nav().spinR(-a); return false; case Key::Right: nav().spinU(-a); return false; case Key::Left: nav().spinU( a); return false; case 'q': nav().spinF( a); return false; case 'z': nav().spinF(-a); return false; case 'a': nav().moveR(-v); return false; case 'd': nav().moveR( v); return false; case 'e': nav().moveU( v); return false; case 'c': nav().moveU(-v); return false; case 'x': nav().moveF(-v); return false; case 'w': nav().moveF( v); return false; default:; } return true; } virtual bool onKeyUp(const Keyboard& k) { switch (k.key()) { case Key::Up: case Key::Down: nav().spinR(0); return false; case Key::Right: case Key::Left: nav().spinU(0); return false; case 'q': case 'z': nav().spinF(0); return false; case 'a': case 'd': nav().moveR(0); return false; case 'e': case 'c': nav().moveU(0); return false; case 'x': case 'w': nav().moveF(0); return false; default:; } return true; } virtual bool onMouseDrag(const Mouse& m){ if(m.left()){ nav().turnU(-m.dx() * 0.2 * M_DEG2RAD); nav().turnR(-m.dy() * 0.2 * M_DEG2RAD); } else if(m.right()){ nav().turnF( m.dx() * 0.2 * M_DEG2RAD); //incBehind(m.dy()*0.005); } return false; } Nav& nav(){ return *mNav; } double vscale() { return mVScale; } NavInputControl& vscale(double v) { mVScale=v; return *this; } double tscale() { return mTScale; } NavInputControl& tscale(double v) { mTScale=v; return *this; } protected: Nav * mNav; double mVScale, mTScale; }; struct NavInputControlCosm : public NavInputControl { NavInputControlCosm(Nav& nav, double vscale = 0.125, double tscale = 2.): NavInputControl(nav, vscale, tscale){} virtual ~NavInputControlCosm() {} virtual bool onKeyDown(const Keyboard& k){ double vs = nav().velScale(); double a = mTScale * vs * M_DEG2RAD; // rotational speed: degrees per update double v = mVScale * vs; // speed: units per update if(k.ctrl()) v *= 0.1; if(k.alt()) v *= 10; switch(k.key()){ case '`': nav().halt().home(); return false; case 'w': nav().spinR( a); return false; case 'x': nav().spinR(-a); return false; // case Key::Right: nav().spinU( a); return false; // case Key::Left: nav().spinU(-a); return false; case Key::Right: nav().spinU( -a); return false; case Key::Left: nav().spinU( a); return false; case 'a': nav().spinF( a); return false; case 'd': nav().spinF(-a); return false; case ',': nav().moveR(-v); return false; case '.': nav().moveR( v); return false; case '\'': nav().moveU( v); return false; case '/': nav().moveU(-v); return false; case Key::Up: nav().moveF( v); return false; case Key::Down: nav().moveF(-v); return false; default:; } return true; } virtual bool onKeyUp(const Keyboard& k) { switch (k.key()) { case 'w': case 'x': nav().spinR(0); return false; case Key::Right: case Key::Left: nav().spinU(0); return false; case 'a': case 'd': nav().spinF(0); return false; case ',': case '.': nav().moveR(0); return false; case '\'': case '/': nav().moveU(0); return false; case Key::Up: case Key::Down: nav().moveF(0); return false; default:; } return true; } virtual bool onMouseDrag(const Mouse& m){ return true; } }; } // al:: #endif
#ifndef INC_AL_CONTROL_NAV_HPP #define INC_AL_CONTROL_NAV_HPP #include "allocore/io/al_Window.hpp" #include "allocore/spatial/al_Pose.hpp" namespace al { /// Mapping from keyboard and mouse controls to a Nav object struct NavInputControl : public InputEventHandler { NavInputControl(const NavInputControl& v) : mNav(v.mNav), mVScale(v.vscale()), mTScale(v.tscale()) {} NavInputControl(Nav& nav, double vscale = 0.125, double tscale = 2.) : mNav(&nav), mVScale(vscale), mTScale(tscale) {} virtual ~NavInputControl(){} virtual bool onKeyDown(const Keyboard& k){ if(k.ctrl()) return true; double vs = nav().velScale(); double a = mTScale * vs * M_DEG2RAD; // rotational speed: degrees per update double v = mVScale * vs; // speed: units per update if(k.alt()) v *= 10; if(k.shift()) v *= 0.1; switch(k.key()){ case '`': nav().halt().home(); return false; case 's': nav().halt(); return false; case Key::Up: nav().spinR( a); return false; case Key::Down: nav().spinR(-a); return false; case Key::Right: nav().spinU(-a); return false; case Key::Left: nav().spinU( a); return false; case 'q': nav().spinF( a); return false; case 'z': nav().spinF(-a); return false; case 'a': nav().moveR(-v); return false; case 'd': nav().moveR( v); return false; case 'e': nav().moveU( v); return false; case 'c': nav().moveU(-v); return false; case 'x': nav().moveF(-v); return false; case 'w': nav().moveF( v); return false; default:; } return true; } virtual bool onKeyUp(const Keyboard& k) { switch (k.key()) { case Key::Up: case Key::Down: nav().spinR(0); return false; case Key::Right: case Key::Left: nav().spinU(0); return false; case 'q': case 'z': nav().spinF(0); return false; case 'a': case 'd': nav().moveR(0); return false; case 'e': case 'c': nav().moveU(0); return false; case 'x': case 'w': nav().moveF(0); return false; default:; } return true; } virtual bool onMouseDrag(const Mouse& m){ if(m.left()){ nav().turnU(-m.dx() * 0.2 * M_DEG2RAD); nav().turnR(-m.dy() * 0.2 * M_DEG2RAD); } else if(m.right()){ nav().turnF( m.dx() * 0.2 * M_DEG2RAD); //incBehind(m.dy()*0.005); } return false; } Nav& nav(){ return *mNav; } const Nav& nav() const { return *mNav; } NavInputControl& nav(Nav& v){ mNav=&v; return *this; } double vscale() const { return mVScale; } NavInputControl& vscale(double v) { mVScale=v; return *this; } double tscale() const { return mTScale; } NavInputControl& tscale(double v) { mTScale=v; return *this; } protected: Nav * mNav; double mVScale, mTScale; }; struct NavInputControlCosm : public NavInputControl { NavInputControlCosm(Nav& nav, double vscale = 0.125, double tscale = 2.): NavInputControl(nav, vscale, tscale){} virtual ~NavInputControlCosm() {} virtual bool onKeyDown(const Keyboard& k){ double vs = nav().velScale(); double a = mTScale * vs * M_DEG2RAD; // rotational speed: degrees per update double v = mVScale * vs; // speed: units per update if(k.ctrl()) v *= 0.1; if(k.alt()) v *= 10; switch(k.key()){ case '`': nav().halt().home(); return false; case 'w': nav().spinR( a); return false; case 'x': nav().spinR(-a); return false; // case Key::Right: nav().spinU( a); return false; // case Key::Left: nav().spinU(-a); return false; case Key::Right: nav().spinU( -a); return false; case Key::Left: nav().spinU( a); return false; case 'a': nav().spinF( a); return false; case 'd': nav().spinF(-a); return false; case ',': nav().moveR(-v); return false; case '.': nav().moveR( v); return false; case '\'': nav().moveU( v); return false; case '/': nav().moveU(-v); return false; case Key::Up: nav().moveF( v); return false; case Key::Down: nav().moveF(-v); return false; default:; } return true; } virtual bool onKeyUp(const Keyboard& k) { switch (k.key()) { case 'w': case 'x': nav().spinR(0); return false; case Key::Right: case Key::Left: nav().spinU(0); return false; case 'a': case 'd': nav().spinF(0); return false; case ',': case '.': nav().moveR(0); return false; case '\'': case '/': nav().moveU(0); return false; case Key::Up: case Key::Down: nav().moveF(0); return false; default:; } return true; } virtual bool onMouseDrag(const Mouse& m){ return true; } }; } // al:: #endif
copy ctor
NavControl: copy ctor
C++
bsd-3-clause
AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem
3bfcd3a727af9fa021a4309dba891ed47bff8e41
include/bredis/impl/connection.ipp
include/bredis/impl/connection.ipp
// // // Copyright (c) 2017 Ivan Baidakou (basiliscos) (the dot dmol at gmail dot com) // // Distributed under the MIT Software License // #pragma once #include <algorithm> #include <cassert> #include <type_traits> #include "common.ipp" namespace bredis { template <typename NextLayer> template <typename WriteCallback> void Connection<NextLayer>::async_write(const command_wrapper_t &command, WriteCallback write_callback) { namespace asio = boost::asio; namespace sys = boost::system; auto str = std::make_shared<std::string>( boost::apply_visitor(command_serializer_visitor(), command)); auto str_ptr = str.get(); BREDIS_LOG_DEBUG("async_write >> " << str_ptr->c_str()); auto const output_buf = asio::buffer(str_ptr->c_str(), str_ptr->size()); asio::async_write(stream_, output_buf, [str, write_callback](const sys::error_code &error_code, std::size_t bytes_transferred) { write_callback(error_code); }); } template <typename NextLayer> template <typename ReadCallback, typename DynamicBuffer> void Connection<NextLayer>::async_read(DynamicBuffer &rx_buff, ReadCallback read_callback, std::size_t replies_count) { namespace asio = boost::asio; namespace sys = boost::system; BREDIS_LOG_DEBUG("async_read"); asio::async_read_until( stream_, rx_buff, MatchResult(replies_count), [read_callback, &rx_buff, replies_count]( const sys::error_code &error_code, std::size_t bytes_transferred) { if (error_code) { read_callback(error_code, {}, 0); return; } auto const_buff = rx_buff.data(); const char *char_ptr = boost::asio::buffer_cast<const char *>(const_buff); auto size = rx_buff.size(); BREDIS_LOG_DEBUG("incoming data(" << size << ") : " << char_ptr << ", tx bytes: " << bytes_transferred); array_holder_t results; results.elements.reserve(replies_count); size_t cumulative_consumption = 0; boost::system::error_code ec; do { string_t data(char_ptr + cumulative_consumption, size - cumulative_consumption); BREDIS_LOG_DEBUG("trying to get response # " << results.elements.size()); BREDIS_LOG_DEBUG("trying to get response from " << data); auto parse_result = Protocol::parse(data); auto *parse_error = boost::get<protocol_error_t>(&parse_result); if (parse_error) { /* might happen only in case of protocol error */ BREDIS_LOG_DEBUG("protocol error: " << parse_error->what); auto parse_error_code = Error::make_error_code(bredis_errors::protocol_error); read_callback(parse_error_code, {}, 0); return; } auto &positive_result = boost::get<positive_parse_result_t>(parse_result); results.elements.emplace_back(positive_result.result); cumulative_consumption += positive_result.consumed; } while (results.elements.size() < replies_count); if (replies_count == 1) { read_callback(ec, std::move(results.elements[0]), cumulative_consumption); } else { read_callback(ec, std::move(results), cumulative_consumption); } }); } template <typename NextLayer> void Connection<NextLayer>::write(const command_wrapper_t &command) { namespace asio = boost::asio; namespace sys = boost::system; auto str = boost::apply_visitor(command_serializer_visitor(), command); BREDIS_LOG_DEBUG("async_write >> " << str); auto const output_buf = asio::buffer(str.c_str(), str.size()); asio::write(stream_, output_buf); } template <typename NextLayer> void Connection<NextLayer>::write(const command_wrapper_t &command, boost::system::error_code &ec) { namespace asio = boost::asio; namespace sys = boost::system; auto str = boost::apply_visitor(command_serializer_visitor(), command); BREDIS_LOG_DEBUG("async_write >> " << str); auto const output_buf = asio::buffer(str.c_str(), str.size()); asio::write(stream_, output_buf, ec); } template <typename NextLayer> template <typename DynamicBuffer> positive_parse_result_t Connection<NextLayer>::read(DynamicBuffer &rx_buff, boost::system::error_code &ec) { namespace asio = boost::asio; namespace sys = boost::system; auto rx_bytes = asio::read_until(stream_, rx_buff, MatchResult(1), ec); if (ec) { return positive_parse_result_t{{}, 0}; } const auto char_ptr = boost::asio::buffer_cast<const char *>(rx_buff.data()); auto size = rx_buff.size(); string_t data(char_ptr, size); BREDIS_LOG_DEBUG("incoming data(" << size << ") : " << char_ptr); auto parse_result = Protocol::parse(data); auto *parse_error = boost::get<protocol_error_t>(&parse_result); if (parse_error) { BREDIS_LOG_DEBUG("protocol error: " << parse_error->what); ec = Error::make_error_code(bredis_errors::protocol_error); return positive_parse_result_t{{}, 0}; } return boost::get<positive_parse_result_t>(parse_result); } template <typename NextLayer> template <typename DynamicBuffer> inline positive_parse_result_t Connection<NextLayer>::read(DynamicBuffer &rx_buff) { namespace asio = boost::asio; namespace sys = boost::system; boost::system::error_code ec; auto result = read(rx_buff, ec); if (ec) { throw boost::system::system_error{ec}; } return result; } } // namespace bredis
// // // Copyright (c) 2017 Ivan Baidakou (basiliscos) (the dot dmol at gmail dot com) // // Distributed under the MIT Software License // #pragma once #include <algorithm> #include <cassert> #include <type_traits> #include "common.ipp" namespace bredis { template <typename NextLayer> template <typename WriteCallback> void Connection<NextLayer>::async_write(const command_wrapper_t &command, WriteCallback write_callback) { namespace asio = boost::asio; namespace sys = boost::system; using boost::asio::async_write; auto str = std::make_shared<std::string>( boost::apply_visitor(command_serializer_visitor(), command)); auto str_ptr = str.get(); BREDIS_LOG_DEBUG("async_write >> " << str_ptr->c_str()); auto const output_buf = asio::buffer(str_ptr->c_str(), str_ptr->size()); async_write(stream_, output_buf, [str, write_callback](const sys::error_code &error_code, std::size_t bytes_transferred) { write_callback(error_code); }); } template <typename NextLayer> template <typename ReadCallback, typename DynamicBuffer> void Connection<NextLayer>::async_read(DynamicBuffer &rx_buff, ReadCallback read_callback, std::size_t replies_count) { namespace asio = boost::asio; namespace sys = boost::system; using boost::asio::async_read_until; BREDIS_LOG_DEBUG("async_read"); async_read_until( stream_, rx_buff, MatchResult(replies_count), [read_callback, &rx_buff, replies_count]( const sys::error_code &error_code, std::size_t bytes_transferred) { if (error_code) { read_callback(error_code, {}, 0); return; } auto const_buff = rx_buff.data(); const char *char_ptr = boost::asio::buffer_cast<const char *>(const_buff); auto size = rx_buff.size(); BREDIS_LOG_DEBUG("incoming data(" << size << ") : " << char_ptr << ", tx bytes: " << bytes_transferred); array_holder_t results; results.elements.reserve(replies_count); size_t cumulative_consumption = 0; boost::system::error_code ec; do { string_t data(char_ptr + cumulative_consumption, size - cumulative_consumption); BREDIS_LOG_DEBUG("trying to get response # " << results.elements.size()); BREDIS_LOG_DEBUG("trying to get response from " << data); auto parse_result = Protocol::parse(data); auto *parse_error = boost::get<protocol_error_t>(&parse_result); if (parse_error) { /* might happen only in case of protocol error */ BREDIS_LOG_DEBUG("protocol error: " << parse_error->what); auto parse_error_code = Error::make_error_code(bredis_errors::protocol_error); read_callback(parse_error_code, {}, 0); return; } auto &positive_result = boost::get<positive_parse_result_t>(parse_result); results.elements.emplace_back(positive_result.result); cumulative_consumption += positive_result.consumed; } while (results.elements.size() < replies_count); if (replies_count == 1) { read_callback(ec, std::move(results.elements[0]), cumulative_consumption); } else { read_callback(ec, std::move(results), cumulative_consumption); } }); } template <typename NextLayer> void Connection<NextLayer>::write(const command_wrapper_t &command) { namespace asio = boost::asio; namespace sys = boost::system; using boost::asio::write; auto str = boost::apply_visitor(command_serializer_visitor(), command); BREDIS_LOG_DEBUG("async_write >> " << str); auto const output_buf = asio::buffer(str.c_str(), str.size()); write(stream_, output_buf); } template <typename NextLayer> void Connection<NextLayer>::write(const command_wrapper_t &command, boost::system::error_code &ec) { namespace asio = boost::asio; namespace sys = boost::system; auto str = boost::apply_visitor(command_serializer_visitor(), command); BREDIS_LOG_DEBUG("async_write >> " << str); auto const output_buf = asio::buffer(str.c_str(), str.size()); asio::write(stream_, output_buf, ec); } template <typename NextLayer> template <typename DynamicBuffer> positive_parse_result_t Connection<NextLayer>::read(DynamicBuffer &rx_buff, boost::system::error_code &ec) { namespace asio = boost::asio; namespace sys = boost::system; using boost::asio::read_until; auto rx_bytes = read_until(stream_, rx_buff, MatchResult(1), ec); if (ec) { return positive_parse_result_t{{}, 0}; } const auto char_ptr = boost::asio::buffer_cast<const char *>(rx_buff.data()); auto size = rx_buff.size(); string_t data(char_ptr, size); BREDIS_LOG_DEBUG("incoming data(" << size << ") : " << char_ptr); auto parse_result = Protocol::parse(data); auto *parse_error = boost::get<protocol_error_t>(&parse_result); if (parse_error) { BREDIS_LOG_DEBUG("protocol error: " << parse_error->what); ec = Error::make_error_code(bredis_errors::protocol_error); return positive_parse_result_t{{}, 0}; } return boost::get<positive_parse_result_t>(parse_result); } template <typename NextLayer> template <typename DynamicBuffer> inline positive_parse_result_t Connection<NextLayer>::read(DynamicBuffer &rx_buff) { namespace asio = boost::asio; namespace sys = boost::system; boost::system::error_code ec; auto result = read(rx_buff, ec); if (ec) { throw boost::system::system_error{ec}; } return result; } } // namespace bredis
Make it ADL-friendly
Make it ADL-friendly
C++
mit
basiliscos/cpp-bredis
0b3a918860944878b5fc4cf87883889bc467a052
avmedia/source/framework/modeltools.cxx
avmedia/source/framework/modeltools.cxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <avmedia/modeltools.hxx> #include <avmedia/mediaitem.hxx> #include "mediamisc.hxx" #include <com/sun/star/embed/ElementModes.hpp> #include <com/sun/star/embed/XTransactedObject.hpp> #include <com/sun/star/document/XStorageBasedDocument.hpp> #include <com/sun/star/embed/XStorage.hpp> #include <com/sun/star/packages/zip/ZipFileAccess.hpp> #include <osl/file.hxx> #include <comphelper/processfactory.hxx> #include <tools/urlobj.hxx> #include <ucbhelper/content.hxx> #include <unotools/localfilehelper.hxx> #include <unotools/tempfile.hxx> #include <unotools/ucbstreamhelper.hxx> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/foreach.hpp> #include <boost/optional.hpp> #ifdef ENABLE_COLLADA2GLTF #include <COLLADA2GLTFWriter.h> #include <GLTFAsset.h> #endif #include <string> #include <vector> using namespace ::com::sun::star; using namespace boost::property_tree; namespace avmedia { #ifdef ENABLE_COLLADA2GLTF static void lcl_UnzipKmz(const OUString& rSourceURL, const OUString& rOutputFolderURL, OUString& o_rDaeFileURL) { o_rDaeFileURL = OUString(); uno::Reference<packages::zip::XZipFileAccess2> xNameAccess = packages::zip::ZipFileAccess::createWithURL(comphelper::getProcessComponentContext(), rSourceURL); uno::Sequence< OUString > aNames = xNameAccess->getElementNames(); for( sal_Int32 i = 0; i < aNames.getLength(); ++i ) { const OUString sCopy = rOutputFolderURL + "/" + aNames[i]; if( aNames[i].endsWithIgnoreAsciiCase(".dae") ) o_rDaeFileURL = sCopy; uno::Reference<io::XInputStream> xInputStream(xNameAccess->getByName(aNames[i]), uno::UNO_QUERY); ::ucbhelper::Content aCopyContent(sCopy, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); aCopyContent.writeStream(xInputStream, true); } } bool KmzDae2Gltf(const OUString& rSourceURL, OUString& o_rOutput) { o_rOutput = OUString(); const bool bIsDAE = rSourceURL.endsWithIgnoreAsciiCase(".dae"); const bool bIsKMZ = rSourceURL.endsWithIgnoreAsciiCase(".kmz"); if( !bIsDAE && !bIsKMZ ) { SAL_WARN("avmedia.opengl", "KmzDae2Gltf converter got a file with wrong extension\n" << rSourceURL); return false; } // Create a temporary folder for conversion OUString sOutput; ::utl::LocalFileHelper::ConvertPhysicalNameToURL(::utl::TempFile::CreateTempName(), sOutput); // remove .tmp extension sOutput = sOutput.copy(0, sOutput.getLength()-4); std::shared_ptr <GLTF::GLTFAsset> asset(new GLTF::GLTFAsset()); asset->setBundleOutputPath(OUStringToOString( sOutput, RTL_TEXTENCODING_UTF8 ).getStr()); // If *.dae file is not in the local file system, then copy it to a temp folder for the conversion // KMZ covnerter need a temp folder in all case, because it creates temp files next to the source file OUString sInput = rSourceURL; const INetURLObject aSourceURLObj(rSourceURL); if( aSourceURLObj.GetProtocol() != INET_PROT_FILE ) { try { ::ucbhelper::Content aSourceContent(rSourceURL, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); const OUString sTarget = sOutput + "/" + GetFilename(rSourceURL); ::ucbhelper::Content aTempContent(sTarget, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); aTempContent.writeStream(aSourceContent.openStream(), true); sInput = sTarget; } catch (const uno::Exception&) { SAL_WARN("avmedia.opengl", "Exception while trying to copy source file to the temp folder for conversion:\n" << sInput); return false; } } asset->setInputFilePath(OUStringToOString( sInput, RTL_TEXTENCODING_UTF8 ).getStr()); if (bIsKMZ) { OUString sDaeFilePath; lcl_UnzipKmz(sInput, sOutput, sDaeFilePath); if ( sDaeFilePath.isEmpty() ) { SAL_WARN("avmedia.opengl", "Cannot find dae file in kmz:\n" << rSourceURL); return false; } asset->setInputFilePath(OUStringToOString( sDaeFilePath, RTL_TEXTENCODING_UTF8 ).getStr()); } GLTF::COLLADA2GLTFWriter writer(asset); writer.write(); // Path to the .json file created by COLLADA2GLTFWriter o_rOutput = sOutput + "/" + GetFilename(sOutput) + ".json"; return true; } #endif static void lcl_EmbedExternals(const OUString& rSourceURL, uno::Reference<embed::XStorage> xSubStorage, ::ucbhelper::Content& rContent) { // Create a temp file with which json parser can work. OUString sTempFileURL; const ::osl::FileBase::RC aErr = ::osl::FileBase::createTempFile(0, 0, &sTempFileURL); if (::osl::FileBase::E_None != aErr) { SAL_WARN("avmedia.opengl", "Cannot create temp file"); return; } try { // Write json content to the temp file ::ucbhelper::Content aTempContent(sTempFileURL, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); aTempContent.writeStream(rContent.openStream(), true); } catch (uno::Exception const& e) { SAL_WARN("avmedia.opengl", "Exception: '" << e.Message << "'"); return; } // Convert URL to a file path for loading const INetURLObject aURLObj(sTempFileURL); std::string sUrl = OUStringToOString( aURLObj.getFSysPath(INetURLObject::FSYS_DETECT), RTL_TEXTENCODING_UTF8 ).getStr(); // Parse json, read externals' URI and modify this relative URI's so they remain valid in the new context. std::vector<std::string> vExternals; ptree aTree; try { json_parser::read_json( sUrl, aTree ); // Buffers for geometry and animations BOOST_FOREACH(ptree::value_type &rVal,aTree.get_child("buffers")) { const std::string sBufferUri(rVal.second.get<std::string>("path")); vExternals.push_back(sBufferUri); // Change path: make it contain only a file name aTree.put("buffers." + rVal.first + ".path.",sBufferUri.substr(sBufferUri.find_last_of('/')+1)); } // Images for textures boost::optional< ptree& > aImages = aTree.get_child_optional("images"); if( aImages ) { BOOST_FOREACH(ptree::value_type &rVal,aImages.get()) { const std::string sImageUri(rVal.second.get<std::string>("path")); if( !sImageUri.empty() ) { vExternals.push_back(sImageUri); // Change path: make it contain only a file name aTree.put("images." + rVal.first + ".path.",sImageUri.substr(sImageUri.find_last_of('/')+1)); } } } // Shaders (contains names only) BOOST_FOREACH(ptree::value_type &rVal,aTree.get_child("programs")) { vExternals.push_back(rVal.second.get<std::string>("fragmentShader") + ".glsl"); vExternals.push_back(rVal.second.get<std::string>("vertexShader") + ".glsl"); } // Write out modified json json_parser::write_json( sUrl, aTree ); } catch ( boost::exception const& ) { SAL_WARN("avmedia.opengl", "Exception while parsing *.json file"); return; } // Reload json with modified path to external resources rContent = ::ucbhelper::Content(sTempFileURL, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); // Store all external files next to the json file for( std::vector<std::string>::iterator aCIter = vExternals.begin(); aCIter != vExternals.end(); ++aCIter ) { const OUString sAbsURL = INetURLObject::GetAbsURL(rSourceURL,OUString::createFromAscii(aCIter->c_str())); ::ucbhelper::Content aContent(sAbsURL, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); uno::Reference<io::XStream> const xStream( CreateStream(xSubStorage, GetFilename(sAbsURL)), uno::UNO_SET_THROW); uno::Reference<io::XOutputStream> const xOutStream( xStream->getOutputStream(), uno::UNO_SET_THROW); if (!aContent.openStream(xOutStream)) { SAL_WARN("avmedia.opengl", "openStream to storage failed"); return; } } } bool Embed3DModel( const uno::Reference<frame::XModel>& xModel, const OUString& rSourceURL, OUString& o_rEmbeddedURL) { OUString sSource = rSourceURL; #ifdef ENABLE_COLLADA2GLTF if( !rSourceURL.endsWithIgnoreAsciiCase(".json") ) KmzDae2Gltf(rSourceURL, sSource); #endif try { ::ucbhelper::Content aSourceContent(sSource, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); // Base storage uno::Reference<document::XStorageBasedDocument> const xSBD(xModel, uno::UNO_QUERY_THROW); uno::Reference<embed::XStorage> const xStorage( xSBD->getDocumentStorage(), uno::UNO_QUERY_THROW); // Model storage const OUString sModel("Models"); uno::Reference<embed::XStorage> const xModelStorage( xStorage->openStorageElement(sModel, embed::ElementModes::WRITE)); // Own storage of the corresponding model const OUString sFilename(GetFilename(sSource)); const OUString sGLTFDir(sFilename.copy(0,sFilename.lastIndexOf('.'))); uno::Reference<embed::XStorage> const xSubStorage( xModelStorage->openStorageElement(sGLTFDir, embed::ElementModes::WRITE)); // Embed external resources lcl_EmbedExternals(sSource, xSubStorage, aSourceContent); // Save model file (.json) uno::Reference<io::XStream> const xStream( CreateStream(xSubStorage, sFilename), uno::UNO_SET_THROW); uno::Reference<io::XOutputStream> const xOutStream( xStream->getOutputStream(), uno::UNO_SET_THROW); if (!aSourceContent.openStream(xOutStream)) { SAL_WARN("avmedia.opengl", "openStream to storage failed"); return false; } const uno::Reference<embed::XTransactedObject> xSubTransaction(xSubStorage, uno::UNO_QUERY); if (xSubTransaction.is()) { xSubTransaction->commit(); } const uno::Reference<embed::XTransactedObject> xModelTransaction(xModelStorage, uno::UNO_QUERY); if (xModelTransaction.is()) { xModelTransaction->commit(); } const uno::Reference<embed::XTransactedObject> xTransaction(xStorage, uno::UNO_QUERY); if (xTransaction.is()) { xTransaction->commit(); } o_rEmbeddedURL = "vnd.sun.star.Package:" + sModel + "/" + sGLTFDir + "/" + sFilename; return true; } catch (uno::Exception const&) { SAL_WARN("avmedia.opengl", "Exception while trying to embed model"); } return false; } bool IsModel(const OUString& rMimeType) { return rMimeType == AVMEDIA_MIMETYPE_JSON; } } // namespace avemdia /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <avmedia/modeltools.hxx> #include <avmedia/mediaitem.hxx> #include "mediamisc.hxx" #include <com/sun/star/embed/ElementModes.hpp> #include <com/sun/star/embed/XTransactedObject.hpp> #include <com/sun/star/document/XStorageBasedDocument.hpp> #include <com/sun/star/embed/XStorage.hpp> #include <com/sun/star/packages/zip/ZipFileAccess.hpp> #include <osl/file.hxx> #include <comphelper/processfactory.hxx> #include <tools/urlobj.hxx> #include <ucbhelper/content.hxx> #include <unotools/localfilehelper.hxx> #include <unotools/tempfile.hxx> #include <unotools/ucbstreamhelper.hxx> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/foreach.hpp> #include <boost/optional.hpp> #ifdef ENABLE_COLLADA2GLTF #include <COLLADA2GLTFWriter.h> #include <GLTFAsset.h> #endif #include <string> #include <vector> using namespace ::com::sun::star; using namespace boost::property_tree; namespace avmedia { #ifdef ENABLE_COLLADA2GLTF static void lcl_UnzipKmz(const OUString& rSourceURL, const OUString& rOutputFolderURL, OUString& o_rDaeFileURL) { o_rDaeFileURL = OUString(); uno::Reference<packages::zip::XZipFileAccess2> xNameAccess = packages::zip::ZipFileAccess::createWithURL(comphelper::getProcessComponentContext(), rSourceURL); uno::Sequence< OUString > aNames = xNameAccess->getElementNames(); for( sal_Int32 i = 0; i < aNames.getLength(); ++i ) { const OUString sCopy = rOutputFolderURL + "/" + aNames[i]; if( aNames[i].endsWithIgnoreAsciiCase(".dae") ) o_rDaeFileURL = sCopy; uno::Reference<io::XInputStream> xInputStream(xNameAccess->getByName(aNames[i]), uno::UNO_QUERY); ::ucbhelper::Content aCopyContent(sCopy, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); aCopyContent.writeStream(xInputStream, true); } } bool KmzDae2Gltf(const OUString& rSourceURL, OUString& o_rOutput) { o_rOutput = OUString(); const bool bIsDAE = rSourceURL.endsWithIgnoreAsciiCase(".dae"); const bool bIsKMZ = rSourceURL.endsWithIgnoreAsciiCase(".kmz"); if( !bIsDAE && !bIsKMZ ) { SAL_WARN("avmedia.opengl", "KmzDae2Gltf converter got a file with wrong extension\n" << rSourceURL); return false; } // Create a temporary folder for conversion OUString sOutput; ::utl::LocalFileHelper::ConvertPhysicalNameToURL(::utl::TempFile::CreateTempName(), sOutput); // remove .tmp extension sOutput = sOutput.copy(0, sOutput.getLength()-4); std::shared_ptr <GLTF::GLTFAsset> asset(new GLTF::GLTFAsset()); asset->setBundleOutputPath(OUStringToOString( sOutput, RTL_TEXTENCODING_UTF8 ).getStr()); // If *.dae file is not in the local file system, then copy it to a temp folder for the conversion OUString sInput = rSourceURL; const INetURLObject aSourceURLObj(rSourceURL); if( aSourceURLObj.GetProtocol() != INET_PROT_FILE ) { try { ::ucbhelper::Content aSourceContent(rSourceURL, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); const OUString sTarget = sOutput + "/" + GetFilename(rSourceURL); ::ucbhelper::Content aTempContent(sTarget, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); aTempContent.writeStream(aSourceContent.openStream(), true); sInput = sTarget; } catch (const uno::Exception&) { SAL_WARN("avmedia.opengl", "Exception while trying to copy source file to the temp folder for conversion:\n" << sInput); return false; } } asset->setInputFilePath(OUStringToOString( sInput, RTL_TEXTENCODING_UTF8 ).getStr()); if (bIsKMZ) { OUString sDaeFilePath; lcl_UnzipKmz(sInput, sOutput, sDaeFilePath); if ( sDaeFilePath.isEmpty() ) { SAL_WARN("avmedia.opengl", "Cannot find dae file in kmz:\n" << rSourceURL); return false; } asset->setInputFilePath(OUStringToOString( sDaeFilePath, RTL_TEXTENCODING_UTF8 ).getStr()); } GLTF::COLLADA2GLTFWriter writer(asset); writer.write(); // Path to the .json file created by COLLADA2GLTFWriter o_rOutput = sOutput + "/" + GetFilename(sOutput) + ".json"; return true; } #endif static void lcl_EmbedExternals(const OUString& rSourceURL, uno::Reference<embed::XStorage> xSubStorage, ::ucbhelper::Content& rContent) { // Create a temp file with which json parser can work. OUString sTempFileURL; const ::osl::FileBase::RC aErr = ::osl::FileBase::createTempFile(0, 0, &sTempFileURL); if (::osl::FileBase::E_None != aErr) { SAL_WARN("avmedia.opengl", "Cannot create temp file"); return; } try { // Write json content to the temp file ::ucbhelper::Content aTempContent(sTempFileURL, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); aTempContent.writeStream(rContent.openStream(), true); } catch (uno::Exception const& e) { SAL_WARN("avmedia.opengl", "Exception: '" << e.Message << "'"); return; } // Convert URL to a file path for loading const INetURLObject aURLObj(sTempFileURL); std::string sUrl = OUStringToOString( aURLObj.getFSysPath(INetURLObject::FSYS_DETECT), RTL_TEXTENCODING_UTF8 ).getStr(); // Parse json, read externals' URI and modify this relative URI's so they remain valid in the new context. std::vector<std::string> vExternals; ptree aTree; try { json_parser::read_json( sUrl, aTree ); // Buffers for geometry and animations BOOST_FOREACH(ptree::value_type &rVal,aTree.get_child("buffers")) { const std::string sBufferUri(rVal.second.get<std::string>("path")); vExternals.push_back(sBufferUri); // Change path: make it contain only a file name aTree.put("buffers." + rVal.first + ".path.",sBufferUri.substr(sBufferUri.find_last_of('/')+1)); } // Images for textures boost::optional< ptree& > aImages = aTree.get_child_optional("images"); if( aImages ) { BOOST_FOREACH(ptree::value_type &rVal,aImages.get()) { const std::string sImageUri(rVal.second.get<std::string>("path")); if( !sImageUri.empty() ) { vExternals.push_back(sImageUri); // Change path: make it contain only a file name aTree.put("images." + rVal.first + ".path.",sImageUri.substr(sImageUri.find_last_of('/')+1)); } } } // Shaders (contains names only) BOOST_FOREACH(ptree::value_type &rVal,aTree.get_child("programs")) { vExternals.push_back(rVal.second.get<std::string>("fragmentShader") + ".glsl"); vExternals.push_back(rVal.second.get<std::string>("vertexShader") + ".glsl"); } // Write out modified json json_parser::write_json( sUrl, aTree ); } catch ( boost::exception const& ) { SAL_WARN("avmedia.opengl", "Exception while parsing *.json file"); return; } // Reload json with modified path to external resources rContent = ::ucbhelper::Content(sTempFileURL, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); // Store all external files next to the json file for( std::vector<std::string>::iterator aCIter = vExternals.begin(); aCIter != vExternals.end(); ++aCIter ) { const OUString sAbsURL = INetURLObject::GetAbsURL(rSourceURL,OUString::createFromAscii(aCIter->c_str())); ::ucbhelper::Content aContent(sAbsURL, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); uno::Reference<io::XStream> const xStream( CreateStream(xSubStorage, GetFilename(sAbsURL)), uno::UNO_SET_THROW); uno::Reference<io::XOutputStream> const xOutStream( xStream->getOutputStream(), uno::UNO_SET_THROW); if (!aContent.openStream(xOutStream)) { SAL_WARN("avmedia.opengl", "openStream to storage failed"); return; } } } bool Embed3DModel( const uno::Reference<frame::XModel>& xModel, const OUString& rSourceURL, OUString& o_rEmbeddedURL) { OUString sSource = rSourceURL; #ifdef ENABLE_COLLADA2GLTF if( !rSourceURL.endsWithIgnoreAsciiCase(".json") ) KmzDae2Gltf(rSourceURL, sSource); #endif try { ::ucbhelper::Content aSourceContent(sSource, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); // Base storage uno::Reference<document::XStorageBasedDocument> const xSBD(xModel, uno::UNO_QUERY_THROW); uno::Reference<embed::XStorage> const xStorage( xSBD->getDocumentStorage(), uno::UNO_QUERY_THROW); // Model storage const OUString sModel("Models"); uno::Reference<embed::XStorage> const xModelStorage( xStorage->openStorageElement(sModel, embed::ElementModes::WRITE)); // Own storage of the corresponding model const OUString sFilename(GetFilename(sSource)); const OUString sGLTFDir(sFilename.copy(0,sFilename.lastIndexOf('.'))); uno::Reference<embed::XStorage> const xSubStorage( xModelStorage->openStorageElement(sGLTFDir, embed::ElementModes::WRITE)); // Embed external resources lcl_EmbedExternals(sSource, xSubStorage, aSourceContent); // Save model file (.json) uno::Reference<io::XStream> const xStream( CreateStream(xSubStorage, sFilename), uno::UNO_SET_THROW); uno::Reference<io::XOutputStream> const xOutStream( xStream->getOutputStream(), uno::UNO_SET_THROW); if (!aSourceContent.openStream(xOutStream)) { SAL_WARN("avmedia.opengl", "openStream to storage failed"); return false; } const uno::Reference<embed::XTransactedObject> xSubTransaction(xSubStorage, uno::UNO_QUERY); if (xSubTransaction.is()) { xSubTransaction->commit(); } const uno::Reference<embed::XTransactedObject> xModelTransaction(xModelStorage, uno::UNO_QUERY); if (xModelTransaction.is()) { xModelTransaction->commit(); } const uno::Reference<embed::XTransactedObject> xTransaction(xStorage, uno::UNO_QUERY); if (xTransaction.is()) { xTransaction->commit(); } o_rEmbeddedURL = "vnd.sun.star.Package:" + sModel + "/" + sGLTFDir + "/" + sFilename; return true; } catch (uno::Exception const&) { SAL_WARN("avmedia.opengl", "Exception while trying to embed model"); } return false; } bool IsModel(const OUString& rMimeType) { return rMimeType == AVMEDIA_MIMETYPE_JSON; } } // namespace avemdia /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
Remove obsolete comment
Remove obsolete comment Change-Id: I0cc592b245871187dd41e85be8c86e6e7878181b
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
9e7af0532c18197d3a7f3883f8d064d5698a5d2d
IO/GeoJSON/vtkGeoJSONReader.cxx
IO/GeoJSON/vtkGeoJSONReader.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkGeoJSONReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkGeoJSONReader.h" #include "vtkGeoJSONFeature.h" // VTK Includes #include "vtkAbstractArray.h" #include "vtkBitArray.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkDoubleArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkIntArray.h" #include "vtkNew.h" #include "vtkObjectFactory.h" #include "vtkPolyData.h" #include "vtkStringArray.h" #include "vtkTriangleFilter.h" // C++ includes #include <fstream> #include <iostream> vtkStandardNewMacro(vtkGeoJSONReader); //---------------------------------------------------------------------------- class vtkGeoJSONReader::GeoJSONReaderInternals { public: // List of property names to read. Property value is used the default std::vector<vtkGeoJSONProperty> PropertySpecs; }; //---------------------------------------------------------------------------- vtkGeoJSONReader::vtkGeoJSONReader() { this->FileName = NULL; this->StringInput = NULL; this->StringInputMode = false; this->TriangulatePolygons = false; this->OutlinePolygons = false; this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); this->Internals = new GeoJSONReaderInternals; } //---------------------------------------------------------------------------- vtkGeoJSONReader::~vtkGeoJSONReader() { delete[] FileName; delete[] StringInput; delete Internals; } //---------------------------------------------------------------------------- void vtkGeoJSONReader:: AddFeatureProperty(char *name, vtkVariant& typeAndDefaultValue) { vtkGeoJSONProperty property; // Traverse internal list checking if name already used std::vector<vtkGeoJSONProperty>::iterator iter = this->Internals->PropertySpecs.begin(); for (; iter != this->Internals->PropertySpecs.end(); iter++) { if (iter->Name == name) { vtkWarningMacro(<< "Overwriting property spec for name " << name); property.Name = name; property.Value = typeAndDefaultValue; *iter = property; break; } } // If not found, add to list if (iter == this->Internals->PropertySpecs.end()) { property.Name = name; property.Value = typeAndDefaultValue; this->Internals->PropertySpecs.push_back(property); vtkDebugMacro(<< "Added feature property " << property.Name); } } //---------------------------------------------------------------------------- int vtkGeoJSONReader::CanParseFile(const char *filename, Json::Value &root) { if (!filename) { vtkErrorMacro(<< "Input filename not specified"); return VTK_ERROR; } ifstream file; file.open( filename ); if ( ! file.is_open() ) { vtkErrorMacro(<< "Unable to Open File " << this->FileName); return VTK_ERROR; } Json::Reader reader; //parse the entire geoJSON data into the Json::Value root bool parsedSuccess = reader.parse(file, root, false); if ( ! parsedSuccess ) { // Report failures and their locations in the document vtkErrorMacro(<<"Failed to parse JSON" << endl << reader.getFormatedErrorMessages()); return VTK_ERROR; } return VTK_OK; } //---------------------------------------------------------------------------- int vtkGeoJSONReader::CanParseString(char *input, Json::Value &root) { if (!input) { vtkErrorMacro(<< "Input string is empty"); return VTK_ERROR; } Json::Reader reader; //parse the entire geoJSON data into the Json::Value root bool parsedSuccess = reader.parse(input, root, false); if ( ! parsedSuccess ) { // Report failures and their locations in the document vtkErrorMacro(<<"Failed to parse JSON" << endl << reader.getFormatedErrorMessages()); return VTK_ERROR; } return VTK_OK; } //---------------------------------------------------------------------------- int vtkGeoJSONReader::RequestData(vtkInformation* vtkNotUsed(request), vtkInformationVector** vtkNotUsed(request), vtkInformationVector* outputVector) { // Get the info object vtkInformation* outInfo = outputVector->GetInformationObject(0); // Get the ouptut vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); // Parse either string input of file, depeding on mode Json::Value root; int parseResult = 0; if (this->StringInputMode) { parseResult = this->CanParseString(this->StringInput, root); } else { parseResult = this->CanParseFile(this->FileName, root); } if (parseResult != VTK_OK) { return VTK_ERROR; } // If parsed successfully into Json, then convert it // into appropriate vtkPolyData if (root.isObject()) { this->ParseRoot(root, output); // Convert Concave Polygons to convex polygons using triangulation if (output->GetNumberOfPolys() && this->TriangulatePolygons) { vtkNew<vtkTriangleFilter> filter; filter->SetInputData(output); filter->Update(); output->ShallowCopy(filter->GetOutput()); } } return VTK_OK; } //---------------------------------------------------------------------------- void vtkGeoJSONReader::ParseRoot(const Json::Value& root, vtkPolyData *output) { // Initialize geometry containers vtkNew<vtkPoints> points; output->SetPoints(points.GetPointer()); vtkNew<vtkCellArray> verts; output->SetVerts(verts.GetPointer()); vtkNew<vtkCellArray> lines; output->SetLines(lines.GetPointer()); vtkNew<vtkCellArray> polys; output->SetPolys(polys.GetPointer()); // Initialize feature-id array vtkStringArray *featureIdArray = vtkStringArray::New(); featureIdArray->SetName("feature-id"); output->GetCellData()->AddArray(featureIdArray); featureIdArray->Delete(); // Initialize properties arrays vtkAbstractArray *array; std::vector<vtkGeoJSONProperty>::iterator iter = this->Internals->PropertySpecs.begin(); for (; iter != this->Internals->PropertySpecs.end(); iter++) { array = NULL; switch (iter->Value.GetType()) { case VTK_BIT: array = vtkBitArray::New(); break; case VTK_INT: array = vtkIntArray::New(); break; case VTK_DOUBLE: array = vtkDoubleArray::New(); break; case VTK_STRING: array = vtkStringArray::New(); break; default: vtkWarningMacro("unexpected data type " << iter->Value.GetType()); break; } // Skip if array not created for some reason if (!array) { continue; } array->SetName(iter->Name.c_str()); output->GetCellData()->AddArray(array); array->Delete(); } // Check type Json::Value rootType = root["type"]; if (rootType.isNull()) { vtkErrorMacro(<<"ParseRoot: Missing type node"); return; } // Parse features Json::Value rootFeatures; std::string strRootType = rootType.asString(); std::vector<vtkGeoJSONProperty> properties; if ("FeatureCollection" == strRootType) { rootFeatures = root["features"]; if (rootFeatures.isNull()) { vtkErrorMacro(<<"ParseRoot: Missing \"features\" node"); return; } if (!rootFeatures.isArray()) { vtkErrorMacro(<< "ParseRoot: features node is not an array"); return; } vtkGeoJSONProperty property; for (int i = 0; i < rootFeatures.size(); i++) { // Append extracted geometry to existing outputData Json::Value featureNode = rootFeatures[i]; Json::Value propertiesNode = featureNode["properties"]; this->ParseFeatureProperties(propertiesNode, properties); vtkNew<vtkGeoJSONFeature> feature; feature->SetOutlinePolygons(this->OutlinePolygons); feature->SetFeatureProperties(properties); feature->ExtractGeoJSONFeature(featureNode, output); } } else if ("Feature" == strRootType) { // Process single feature this->ParseFeatureProperties(root, properties); vtkNew<vtkGeoJSONFeature> feature; feature->SetOutlinePolygons(this->OutlinePolygons); feature->SetFeatureProperties(properties); feature->ExtractGeoJSONFeature(root, output); } else { vtkErrorMacro(<< "ParseRoot: do not support root type \"" << strRootType << "\""); } } //---------------------------------------------------------------------------- void vtkGeoJSONReader::ParseFeatureProperties(const Json::Value& propertiesNode, std::vector<vtkGeoJSONProperty>& featureProperties) { featureProperties.clear(); vtkGeoJSONProperty spec; vtkGeoJSONProperty property; std::vector<vtkGeoJSONProperty>::iterator iter = this->Internals->PropertySpecs.begin(); for (; iter != this->Internals->PropertySpecs.end(); iter++) { spec = *iter; property.Name = spec.Name; Json::Value propertyNode = propertiesNode[spec.Name]; if (propertyNode.isNull()) { property.Value = spec.Value; featureProperties.push_back(property); continue; } // (else) switch (spec.Value.GetType()) { case VTK_BIT: property.Value = vtkVariant(propertyNode.asBool()); break; case VTK_DOUBLE: property.Value = vtkVariant(propertyNode.asDouble()); break; case VTK_INT: property.Value = vtkVariant(propertyNode.asInt()); break; case VTK_STRING: property.Value = vtkVariant(propertyNode.asString()); break; } featureProperties.push_back(property); } } //---------------------------------------------------------------------------- void vtkGeoJSONReader::PrintSelf(ostream &os, vtkIndent indent) { Superclass::PrintSelf(os, indent); os << "vtkGeoJSONReader" << std::endl; os << "Filename: " << this->FileName << std::endl; }
/*========================================================================= Program: Visualization Toolkit Module: vtkGeoJSONReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkGeoJSONReader.h" #include "vtkGeoJSONFeature.h" // VTK Includes #include "vtkAbstractArray.h" #include "vtkBitArray.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkDoubleArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkIntArray.h" #include "vtkNew.h" #include "vtkObjectFactory.h" #include "vtkPolyData.h" #include "vtkStringArray.h" #include "vtkTriangleFilter.h" // C++ includes #include <fstream> #include <iostream> vtkStandardNewMacro(vtkGeoJSONReader); //---------------------------------------------------------------------------- class vtkGeoJSONReader::GeoJSONReaderInternals { public: // List of property names to read. Property value is used the default std::vector<vtkGeoJSONProperty> PropertySpecs; }; //---------------------------------------------------------------------------- vtkGeoJSONReader::vtkGeoJSONReader() { this->FileName = NULL; this->StringInput = NULL; this->StringInputMode = false; this->TriangulatePolygons = false; this->OutlinePolygons = false; this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); this->Internals = new GeoJSONReaderInternals; } //---------------------------------------------------------------------------- vtkGeoJSONReader::~vtkGeoJSONReader() { delete[] FileName; delete[] StringInput; delete Internals; } //---------------------------------------------------------------------------- void vtkGeoJSONReader:: AddFeatureProperty(char *name, vtkVariant& typeAndDefaultValue) { vtkGeoJSONProperty property; // Traverse internal list checking if name already used std::vector<vtkGeoJSONProperty>::iterator iter = this->Internals->PropertySpecs.begin(); for (; iter != this->Internals->PropertySpecs.end(); iter++) { if (iter->Name == name) { vtkWarningMacro(<< "Overwriting property spec for name " << name); property.Name = name; property.Value = typeAndDefaultValue; *iter = property; break; } } // If not found, add to list if (iter == this->Internals->PropertySpecs.end()) { property.Name = name; property.Value = typeAndDefaultValue; this->Internals->PropertySpecs.push_back(property); vtkDebugMacro(<< "Added feature property " << property.Name); } } //---------------------------------------------------------------------------- int vtkGeoJSONReader::CanParseFile(const char *filename, Json::Value &root) { if (!filename) { vtkErrorMacro(<< "Input filename not specified"); return VTK_ERROR; } ifstream file; file.open( filename ); if ( ! file.is_open() ) { vtkErrorMacro(<< "Unable to Open File " << this->FileName); return VTK_ERROR; } Json::Reader reader; //parse the entire geoJSON data into the Json::Value root bool parsedSuccess = reader.parse(file, root, false); if ( ! parsedSuccess ) { // Report failures and their locations in the document vtkErrorMacro(<<"Failed to parse JSON" << endl << reader.getFormatedErrorMessages()); return VTK_ERROR; } return VTK_OK; } //---------------------------------------------------------------------------- int vtkGeoJSONReader::CanParseString(char *input, Json::Value &root) { if (!input) { vtkErrorMacro(<< "Input string is empty"); return VTK_ERROR; } Json::Reader reader; //parse the entire geoJSON data into the Json::Value root bool parsedSuccess = reader.parse(input, root, false); if ( ! parsedSuccess ) { // Report failures and their locations in the document vtkErrorMacro(<<"Failed to parse JSON" << endl << reader.getFormatedErrorMessages()); return VTK_ERROR; } return VTK_OK; } //---------------------------------------------------------------------------- int vtkGeoJSONReader::RequestData(vtkInformation* vtkNotUsed(request), vtkInformationVector** vtkNotUsed(request), vtkInformationVector* outputVector) { // Get the info object vtkInformation* outInfo = outputVector->GetInformationObject(0); // Get the ouptut vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); // Parse either string input of file, depeding on mode Json::Value root; int parseResult = 0; if (this->StringInputMode) { parseResult = this->CanParseString(this->StringInput, root); } else { parseResult = this->CanParseFile(this->FileName, root); } if (parseResult != VTK_OK) { return VTK_ERROR; } // If parsed successfully into Json, then convert it // into appropriate vtkPolyData if (root.isObject()) { this->ParseRoot(root, output); // Convert Concave Polygons to convex polygons using triangulation if (output->GetNumberOfPolys() && this->TriangulatePolygons) { vtkNew<vtkTriangleFilter> filter; filter->SetInputData(output); filter->Update(); output->ShallowCopy(filter->GetOutput()); } } return VTK_OK; } //---------------------------------------------------------------------------- void vtkGeoJSONReader::ParseRoot(const Json::Value& root, vtkPolyData *output) { // Initialize geometry containers vtkNew<vtkPoints> points; points->SetDataTypeToDouble(); output->SetPoints(points.GetPointer()); vtkNew<vtkCellArray> verts; output->SetVerts(verts.GetPointer()); vtkNew<vtkCellArray> lines; output->SetLines(lines.GetPointer()); vtkNew<vtkCellArray> polys; output->SetPolys(polys.GetPointer()); // Initialize feature-id array vtkStringArray *featureIdArray = vtkStringArray::New(); featureIdArray->SetName("feature-id"); output->GetCellData()->AddArray(featureIdArray); featureIdArray->Delete(); // Initialize properties arrays vtkAbstractArray *array; std::vector<vtkGeoJSONProperty>::iterator iter = this->Internals->PropertySpecs.begin(); for (; iter != this->Internals->PropertySpecs.end(); iter++) { array = NULL; switch (iter->Value.GetType()) { case VTK_BIT: array = vtkBitArray::New(); break; case VTK_INT: array = vtkIntArray::New(); break; case VTK_DOUBLE: array = vtkDoubleArray::New(); break; case VTK_STRING: array = vtkStringArray::New(); break; default: vtkWarningMacro("unexpected data type " << iter->Value.GetType()); break; } // Skip if array not created for some reason if (!array) { continue; } array->SetName(iter->Name.c_str()); output->GetCellData()->AddArray(array); array->Delete(); } // Check type Json::Value rootType = root["type"]; if (rootType.isNull()) { vtkErrorMacro(<<"ParseRoot: Missing type node"); return; } // Parse features Json::Value rootFeatures; std::string strRootType = rootType.asString(); std::vector<vtkGeoJSONProperty> properties; if ("FeatureCollection" == strRootType) { rootFeatures = root["features"]; if (rootFeatures.isNull()) { vtkErrorMacro(<<"ParseRoot: Missing \"features\" node"); return; } if (!rootFeatures.isArray()) { vtkErrorMacro(<< "ParseRoot: features node is not an array"); return; } vtkGeoJSONProperty property; for (int i = 0; i < rootFeatures.size(); i++) { // Append extracted geometry to existing outputData Json::Value featureNode = rootFeatures[i]; Json::Value propertiesNode = featureNode["properties"]; this->ParseFeatureProperties(propertiesNode, properties); vtkNew<vtkGeoJSONFeature> feature; feature->SetOutlinePolygons(this->OutlinePolygons); feature->SetFeatureProperties(properties); feature->ExtractGeoJSONFeature(featureNode, output); } } else if ("Feature" == strRootType) { // Process single feature this->ParseFeatureProperties(root, properties); vtkNew<vtkGeoJSONFeature> feature; feature->SetOutlinePolygons(this->OutlinePolygons); feature->SetFeatureProperties(properties); feature->ExtractGeoJSONFeature(root, output); } else { vtkErrorMacro(<< "ParseRoot: do not support root type \"" << strRootType << "\""); } } //---------------------------------------------------------------------------- void vtkGeoJSONReader::ParseFeatureProperties(const Json::Value& propertiesNode, std::vector<vtkGeoJSONProperty>& featureProperties) { featureProperties.clear(); vtkGeoJSONProperty spec; vtkGeoJSONProperty property; std::vector<vtkGeoJSONProperty>::iterator iter = this->Internals->PropertySpecs.begin(); for (; iter != this->Internals->PropertySpecs.end(); iter++) { spec = *iter; property.Name = spec.Name; Json::Value propertyNode = propertiesNode[spec.Name]; if (propertyNode.isNull()) { property.Value = spec.Value; featureProperties.push_back(property); continue; } // (else) switch (spec.Value.GetType()) { case VTK_BIT: property.Value = vtkVariant(propertyNode.asBool()); break; case VTK_DOUBLE: property.Value = vtkVariant(propertyNode.asDouble()); break; case VTK_INT: property.Value = vtkVariant(propertyNode.asInt()); break; case VTK_STRING: property.Value = vtkVariant(propertyNode.asString()); break; } featureProperties.push_back(property); } } //---------------------------------------------------------------------------- void vtkGeoJSONReader::PrintSelf(ostream &os, vtkIndent indent) { Superclass::PrintSelf(os, indent); os << "vtkGeoJSONReader" << std::endl; os << "Filename: " << this->FileName << std::endl; }
Use double precision for point coordinates
Use double precision for point coordinates
C++
bsd-3-clause
sumedhasingla/VTK,SimVascular/VTK,SimVascular/VTK,gram526/VTK,sankhesh/VTK,sankhesh/VTK,sumedhasingla/VTK,sumedhasingla/VTK,gram526/VTK,sankhesh/VTK,mspark93/VTK,gram526/VTK,keithroe/vtkoptix,jmerkow/VTK,jmerkow/VTK,sankhesh/VTK,mspark93/VTK,gram526/VTK,gram526/VTK,SimVascular/VTK,gram526/VTK,mspark93/VTK,sankhesh/VTK,sankhesh/VTK,keithroe/vtkoptix,gram526/VTK,SimVascular/VTK,sumedhasingla/VTK,keithroe/vtkoptix,sumedhasingla/VTK,keithroe/vtkoptix,sankhesh/VTK,keithroe/vtkoptix,SimVascular/VTK,sumedhasingla/VTK,keithroe/vtkoptix,sumedhasingla/VTK,sumedhasingla/VTK,SimVascular/VTK,jmerkow/VTK,keithroe/vtkoptix,jmerkow/VTK,mspark93/VTK,jmerkow/VTK,jmerkow/VTK,SimVascular/VTK,jmerkow/VTK,mspark93/VTK,mspark93/VTK,keithroe/vtkoptix,mspark93/VTK,sankhesh/VTK,mspark93/VTK,gram526/VTK,SimVascular/VTK,jmerkow/VTK
ae06300c17428a1f49446c333a637a81ec6d8278
include/contractor/crc32_processor.hpp
include/contractor/crc32_processor.hpp
#ifndef ITERATOR_BASED_CRC32_H #define ITERATOR_BASED_CRC32_H #if defined(__x86_64__) && !defined(__MINGW64__) #include <cpuid.h> #endif #include <boost/crc.hpp> // for boost::crc_32_type #include <iterator> namespace osrm { namespace contractor { class IteratorbasedCRC32 { public: bool UsingHardware() const { return use_hardware_implementation; } IteratorbasedCRC32() : crc(0) { use_hardware_implementation = DetectHardwareSupport(); } template <class Iterator> unsigned operator()(Iterator iter, const Iterator end) { unsigned crc = 0; while (iter != end) { using value_type = typename std::iterator_traits<Iterator>::value_type; const char *data = reinterpret_cast<const char *>(&(*iter)); if (use_hardware_implementation) { crc = ComputeInHardware(data, sizeof(value_type)); } else { crc = ComputeInSoftware(data, sizeof(value_type)); } ++iter; } return crc; } private: bool DetectHardwareSupport() const { static const int sse42_bit = 0x00100000; const unsigned ecx = cpuid(); const bool sse42_found = (ecx & sse42_bit) != 0; return sse42_found; } unsigned ComputeInSoftware(const char *str, unsigned len) { crc_processor.process_bytes(str, len); return crc_processor.checksum(); } // adapted from http://byteworm.com/2010/10/13/crc32/ unsigned ComputeInHardware(const char *str, unsigned len) { #if defined(__x86_64__) unsigned q = len / sizeof(unsigned); unsigned r = len % sizeof(unsigned); unsigned *p = (unsigned *)str; // crc=0; while (q--) { __asm__ __volatile__(".byte 0xf2, 0xf, 0x38, 0xf1, 0xf1;" : "=S"(crc) : "0"(crc), "c"(*p)); ++p; } str = reinterpret_cast<char *>(p); while (r--) { __asm__ __volatile__(".byte 0xf2, 0xf, 0x38, 0xf1, 0xf1;" : "=S"(crc) : "0"(crc), "c"(*str)); ++str; } #endif return crc; } inline unsigned cpuid() const { unsigned eax = 0, ebx = 0, ecx = 0, edx = 0; // on X64 this calls hardware cpuid(.) instr. otherwise a dummy impl. __get_cpuid(1, &eax, &ebx, &ecx, &edx); return ecx; } #if defined(__MINGW64__) || defined(_MSC_VER) || !defined(__x86_64__) inline void __get_cpuid(int param, unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx) const { *ecx = 0; } #endif boost::crc_optimal<32, 0x1EDC6F41, 0x0, 0x0, true, true> crc_processor; unsigned crc; bool use_hardware_implementation; }; struct RangebasedCRC32 { template <typename Iteratable> unsigned operator()(const Iteratable &iterable) { return crc32(std::begin(iterable), std::end(iterable)); } bool UsingHardware() const { return crc32.UsingHardware(); } private: IteratorbasedCRC32 crc32; }; } } #endif /* ITERATOR_BASED_CRC32_H */
#ifndef ITERATOR_BASED_CRC32_H #define ITERATOR_BASED_CRC32_H #if defined(__x86_64__) && !defined(__MINGW64__) #include <cpuid.h> #endif #include <boost/crc.hpp> // for boost::crc_32_type #include <iterator> namespace osrm { namespace contractor { class IteratorbasedCRC32 { public: bool UsingHardware() const { return use_hardware_implementation; } IteratorbasedCRC32() : crc(0) { use_hardware_implementation = DetectHardwareSupport(); } template <class Iterator> unsigned operator()(Iterator iter, const Iterator end) { unsigned crc = 0; while (iter != end) { using value_type = typename std::iterator_traits<Iterator>::value_type; const char *data = reinterpret_cast<const char *>(&(*iter)); if (use_hardware_implementation) { crc = ComputeInHardware(data, sizeof(value_type)); } else { crc = ComputeInSoftware(data, sizeof(value_type)); } ++iter; } return crc; } private: bool DetectHardwareSupport() const { static const int sse42_bit = 0x00100000; const unsigned ecx = cpuid(); const bool sse42_found = (ecx & sse42_bit) != 0; return sse42_found; } unsigned ComputeInSoftware(const char *str, unsigned len) { crc_processor.process_bytes(str, len); return crc_processor.checksum(); } // adapted from http://byteworm.com/2010/10/13/crc32/ unsigned ComputeInHardware(const char *str, unsigned len) { #if defined(__x86_64__) unsigned q = len / sizeof(unsigned); unsigned r = len % sizeof(unsigned); unsigned *p = (unsigned *)str; // crc=0; while (q--) { __asm__ __volatile__(".byte 0xf2, 0xf, 0x38, 0xf1, 0xf1;" : "=S"(crc) : "0"(crc), "c"(*p)); ++p; } str = reinterpret_cast<char *>(p); while (r--) { __asm__ __volatile__(".byte 0xf2, 0xf, 0x38, 0xf1, 0xf1;" : "=S"(crc) : "0"(crc), "c"(*str)); ++str; } #else (void)str; (void)len; #endif return crc; } inline unsigned cpuid() const { unsigned eax = 0, ebx = 0, ecx = 0, edx = 0; // on X64 this calls hardware cpuid(.) instr. otherwise a dummy impl. __get_cpuid(1, &eax, &ebx, &ecx, &edx); return ecx; } #if defined(__MINGW64__) || defined(_MSC_VER) || !defined(__x86_64__) inline void __get_cpuid(int /*param*/, unsigned * /*eax*/, unsigned * /*ebx*/, unsigned *ecx, unsigned * /*edx*/) const { *ecx = 0; } #endif boost::crc_optimal<32, 0x1EDC6F41, 0x0, 0x0, true, true> crc_processor; unsigned crc; bool use_hardware_implementation; }; struct RangebasedCRC32 { template <typename Iteratable> unsigned operator()(const Iteratable &iterable) { return crc32(std::begin(iterable), std::end(iterable)); } bool UsingHardware() const { return crc32.UsingHardware(); } private: IteratorbasedCRC32 crc32; }; } } #endif /* ITERATOR_BASED_CRC32_H */
Fix unused variables warnings in crc32
Fix unused variables warnings in crc32
C++
bsd-2-clause
oxidase/osrm-backend,oxidase/osrm-backend,deniskoronchik/osrm-backend,felixguendling/osrm-backend,deniskoronchik/osrm-backend,yuryleb/osrm-backend,Project-OSRM/osrm-backend,bjtaylor1/osrm-backend,beemogmbh/osrm-backend,duizendnegen/osrm-backend,raymond0/osrm-backend,raymond0/osrm-backend,KnockSoftware/osrm-backend,frodrigo/osrm-backend,hydrays/osrm-backend,duizendnegen/osrm-backend,hydrays/osrm-backend,bjtaylor1/osrm-backend,KnockSoftware/osrm-backend,Project-OSRM/osrm-backend,deniskoronchik/osrm-backend,duizendnegen/osrm-backend,Project-OSRM/osrm-backend,deniskoronchik/osrm-backend,neilbu/osrm-backend,hydrays/osrm-backend,bjtaylor1/osrm-backend,beemogmbh/osrm-backend,oxidase/osrm-backend,oxidase/osrm-backend,raymond0/osrm-backend,felixguendling/osrm-backend,felixguendling/osrm-backend,duizendnegen/osrm-backend,hydrays/osrm-backend,frodrigo/osrm-backend,Project-OSRM/osrm-backend,beemogmbh/osrm-backend,frodrigo/osrm-backend,neilbu/osrm-backend,yuryleb/osrm-backend,bjtaylor1/osrm-backend,yuryleb/osrm-backend,KnockSoftware/osrm-backend,raymond0/osrm-backend,beemogmbh/osrm-backend,KnockSoftware/osrm-backend,frodrigo/osrm-backend,yuryleb/osrm-backend,neilbu/osrm-backend,neilbu/osrm-backend
645f2c3a1d65bf4e6022d09a49a7dda29ed15c48
src/mesh2d.cpp
src/mesh2d.cpp
/* * Copyright (c) 2012, Dylan Sarber <[email protected]> * * See LICENSE for licensing information. */ #include "mesh2d.h" #include "logog/logog.hpp" #include "SDL/SDL.h" #include "SDL/SDL_image.h" /* Constructors & Destructor ------------------------------------------------------------------------------*/ Mesh2D::Mesh2D(std::string path) { filepath = path; data = IMG_Load(path.c_str()); if (data == NULL) ERR("Failed to initialize mesh at: %s", path.c_str()); } Mesh2D::~Mesh2D() { if (data != NULL) SDL_FreeSurface(data); } /* Public Interface ------------------------------------------------------------------------------*/ std::string Mesh2D::getFilePath() { return filepath; }
/* * Copyright (c) 2012, Dylan Sarber <[email protected]> * * See LICENSE for licensing information. */ #include "mesh2d.h" #include "logog/logog.hpp" #include "SDL/SDL.h" #include "SDL/SDL_image.h" /* Constructors & Destructor ------------------------------------------------------------------------------*/ Mesh2D::Mesh2D(std::string path) : filepath(path) { data = IMG_Load(path.c_str()); if (data == NULL) ERR("Failed to initialize mesh at: %s", path.c_str()); } Mesh2D::~Mesh2D() { if (data != NULL) SDL_FreeSurface(data); } /* Public Interface ------------------------------------------------------------------------------*/ std::string Mesh2D::getFilePath() { return filepath; }
Initialize in Mesh2D
Initialize in Mesh2D Move the filepath assignment to an initializer list.
C++
mit
dwsarber/flock,dwsarber/flock
6e072d1a61ff10f8b689c7d60f41753b14bb9fce
src/ncurses.cc
src/ncurses.cc
#include "ncurses.hh" #include "window.hh" #include "register_manager.hh" #include <ncurses.h> #include <map> #define CTRL(x) x - 'a' + 1 namespace Kakoune { NCursesClient::NCursesClient() { // setlocale(LC_ALL, ""); initscr(); cbreak(); noecho(); nonl(); intrflush(stdscr, false); keypad(stdscr, true); curs_set(0); start_color(); use_default_colors(); ESCDELAY=25; } NCursesClient::~NCursesClient() { endwin(); } static void set_attribute(int attribute, bool on) { if (on) attron(attribute); else attroff(attribute); } static int nc_color(Color color) { switch (color) { case Color::Black: return COLOR_BLACK; case Color::Red: return COLOR_RED; case Color::Green: return COLOR_GREEN; case Color::Yellow: return COLOR_YELLOW; case Color::Blue: return COLOR_BLUE; case Color::Magenta: return COLOR_MAGENTA; case Color::Cyan: return COLOR_CYAN; case Color::White: return COLOR_WHITE; case Color::Default: default: return -1; } } static void set_color(Color fg_color, Color bg_color) { static std::map<std::pair<Color, Color>, int> colorpairs; static int current_pair = -1; static int next_pair = 1; if (current_pair != -1) attroff(COLOR_PAIR(current_pair)); if (fg_color == Color::Default and bg_color == Color::Default) return; std::pair<Color, Color> colorpair(fg_color, bg_color); auto it = colorpairs.find(colorpair); if (it != colorpairs.end()) { current_pair = it->second; attron(COLOR_PAIR(it->second)); } else { init_pair(next_pair, nc_color(fg_color), nc_color(bg_color)); colorpairs[colorpair] = next_pair; current_pair = next_pair; attron(COLOR_PAIR(next_pair)); ++next_pair; } } void NCursesClient::draw_window(Window& window) { int max_x,max_y; getmaxyx(stdscr, max_y, max_x); max_y -= 1; window.set_dimensions(DisplayCoord(max_y, max_x)); window.update_display_buffer(); int line_index = 0; for (const DisplayLine& line : window.display_buffer().lines()) { move(line_index, 0); clrtoeol(); for (const DisplayAtom& atom : line) { set_attribute(A_UNDERLINE, atom.attribute & Underline); set_attribute(A_REVERSE, atom.attribute & Reverse); set_attribute(A_BLINK, atom.attribute & Blink); set_attribute(A_BOLD, atom.attribute & Bold); set_color(atom.fg_color, atom.bg_color); String content = atom.content.content(); if (content[content.length()-1] == '\n') { addnstr(content.c_str(), content.length() - 1); addch(' '); } else addstr(content.c_str()); } ++line_index; } set_attribute(A_UNDERLINE, 0); set_attribute(A_REVERSE, 0); set_attribute(A_BLINK, 0); set_attribute(A_BOLD, 0); set_color(Color::Blue, Color::Black); while (++line_index < max_y) { move(line_index, 0); clrtoeol(); addch('~'); } set_color(Color::Cyan, Color::Black); String status_line = window.status_line(); static int last_status_length = 0; move(max_y, max_x - last_status_length); clrtoeol(); move(max_y, max_x - status_line.length()); addstr(status_line.c_str()); last_status_length = status_line.length(); } Key NCursesClient::get_key() { char c = getch(); Key::Modifiers modifiers = Key::Modifiers::None; if (c > 0 and c < 27) { modifiers = Key::Modifiers::Control; c = c - 1 + 'a'; } else if (c == 27) { timeout(0); char new_c = getch(); timeout(-1); if (new_c != ERR) { c = new_c; modifiers = Key::Modifiers::Alt; } } return Key(modifiers, c); } String NCursesClient::prompt(const String& text, Completer completer) { curs_set(2); auto restore_cursor = on_scope_end([]() { curs_set(0); }); int max_x, max_y; getmaxyx(stdscr, max_y, max_x); move(max_y-1, 0); addstr(text.c_str()); clrtoeol(); size_t cursor_pos = 0; Completions completions; int current_completion = -1; String text_before_completion; String result; String saved_result; static std::unordered_map<String, std::vector<String>> history_per_prompt; std::vector<String>& history = history_per_prompt[text]; auto history_it = history.end(); while (true) { int c = getch(); switch (c) { case '\r': { std::vector<String>::iterator it; while ((it = find(history, result)) != history.end()) history.erase(it); history.push_back(result); return result; } case KEY_UP: if (history_it != history.begin()) { if (history_it == history.end()) saved_result = result; --history_it; result = *history_it; cursor_pos = result.length(); } break; case KEY_DOWN: if (history_it != history.end()) { ++history_it; if (history_it != history.end()) result = *history_it; else result = saved_result; cursor_pos = result.length(); } break; case KEY_LEFT: if (cursor_pos > 0) --cursor_pos; break; case KEY_RIGHT: if (cursor_pos < result.length()) ++cursor_pos; break; case KEY_BACKSPACE: if (cursor_pos != 0) { result = result.substr(0, cursor_pos - 1) + result.substr(cursor_pos, String::npos); --cursor_pos; } current_completion = -1; break; case CTRL('r'): { c = getch(); String reg = RegisterManager::instance()[c][0]; current_completion = -1; result = result.substr(0, cursor_pos) + reg + result.substr(cursor_pos, String::npos); cursor_pos += reg.length(); } break; case 27: throw prompt_aborted(); case '\t': { if (current_completion == -1) { completions = completer(result, cursor_pos); if (completions.candidates.empty()) break; text_before_completion = result.substr(completions.start, completions.end - completions.start); } ++current_completion; String completion; if (current_completion >= completions.candidates.size()) { if (current_completion == completions.candidates.size() and std::find(completions.candidates.begin(), completions.candidates.end(), text_before_completion) == completions.candidates.end()) completion = text_before_completion; else { current_completion = 0; completion = completions.candidates[0]; } } else completion = completions.candidates[current_completion]; move(max_y-1, text.length()); result = result.substr(0, completions.start) + completion; cursor_pos = completions.start + completion.length(); break; } default: current_completion = -1; result = result.substr(0, cursor_pos) + (char)c + result.substr(cursor_pos, String::npos); ++cursor_pos; } move(max_y - 1, text.length()); clrtoeol(); addstr(result.c_str()); move(max_y - 1, text.length() + cursor_pos); refresh(); } return result; } void NCursesClient::print_status(const String& status) { int x,y; getmaxyx(stdscr, y, x); move(y-1, 0); clrtoeol(); addstr(status.c_str()); } }
#include "ncurses.hh" #include "window.hh" #include "register_manager.hh" #include <ncurses.h> #include <map> #define CTRL(x) x - 'a' + 1 namespace Kakoune { NCursesClient::NCursesClient() { // setlocale(LC_ALL, ""); initscr(); cbreak(); noecho(); nonl(); intrflush(stdscr, false); keypad(stdscr, true); curs_set(0); start_color(); use_default_colors(); ESCDELAY=25; } NCursesClient::~NCursesClient() { endwin(); } static void set_attribute(int attribute, bool on) { if (on) attron(attribute); else attroff(attribute); } static int nc_color(Color color) { switch (color) { case Color::Black: return COLOR_BLACK; case Color::Red: return COLOR_RED; case Color::Green: return COLOR_GREEN; case Color::Yellow: return COLOR_YELLOW; case Color::Blue: return COLOR_BLUE; case Color::Magenta: return COLOR_MAGENTA; case Color::Cyan: return COLOR_CYAN; case Color::White: return COLOR_WHITE; case Color::Default: default: return -1; } } static void set_color(Color fg_color, Color bg_color) { static std::map<std::pair<Color, Color>, int> colorpairs; static int current_pair = -1; static int next_pair = 1; if (current_pair != -1) attroff(COLOR_PAIR(current_pair)); if (fg_color == Color::Default and bg_color == Color::Default) return; std::pair<Color, Color> colorpair(fg_color, bg_color); auto it = colorpairs.find(colorpair); if (it != colorpairs.end()) { current_pair = it->second; attron(COLOR_PAIR(it->second)); } else { init_pair(next_pair, nc_color(fg_color), nc_color(bg_color)); colorpairs[colorpair] = next_pair; current_pair = next_pair; attron(COLOR_PAIR(next_pair)); ++next_pair; } } void NCursesClient::draw_window(Window& window) { int max_x,max_y; getmaxyx(stdscr, max_y, max_x); max_y -= 1; window.set_dimensions(DisplayCoord(max_y, max_x)); window.update_display_buffer(); int line_index = 0; for (const DisplayLine& line : window.display_buffer().lines()) { move(line_index, 0); clrtoeol(); for (const DisplayAtom& atom : line) { set_attribute(A_UNDERLINE, atom.attribute & Underline); set_attribute(A_REVERSE, atom.attribute & Reverse); set_attribute(A_BLINK, atom.attribute & Blink); set_attribute(A_BOLD, atom.attribute & Bold); set_color(atom.fg_color, atom.bg_color); String content = atom.content.content(); if (content[content.length()-1] == '\n') { addnstr(content.c_str(), content.length() - 1); addch(' '); } else addstr(content.c_str()); } ++line_index; } set_attribute(A_UNDERLINE, 0); set_attribute(A_REVERSE, 0); set_attribute(A_BLINK, 0); set_attribute(A_BOLD, 0); set_color(Color::Blue, Color::Black); for (;line_index < max_y; ++line_index) { move(line_index, 0); clrtoeol(); addch('~'); } set_color(Color::Cyan, Color::Black); String status_line = window.status_line(); static int last_status_length = 0; move(max_y, max_x - last_status_length); clrtoeol(); move(max_y, max_x - status_line.length()); addstr(status_line.c_str()); last_status_length = status_line.length(); } Key NCursesClient::get_key() { char c = getch(); Key::Modifiers modifiers = Key::Modifiers::None; if (c > 0 and c < 27) { modifiers = Key::Modifiers::Control; c = c - 1 + 'a'; } else if (c == 27) { timeout(0); char new_c = getch(); timeout(-1); if (new_c != ERR) { c = new_c; modifiers = Key::Modifiers::Alt; } } return Key(modifiers, c); } String NCursesClient::prompt(const String& text, Completer completer) { curs_set(2); auto restore_cursor = on_scope_end([]() { curs_set(0); }); int max_x, max_y; getmaxyx(stdscr, max_y, max_x); move(max_y-1, 0); addstr(text.c_str()); clrtoeol(); size_t cursor_pos = 0; Completions completions; int current_completion = -1; String text_before_completion; String result; String saved_result; static std::unordered_map<String, std::vector<String>> history_per_prompt; std::vector<String>& history = history_per_prompt[text]; auto history_it = history.end(); while (true) { int c = getch(); switch (c) { case '\r': { std::vector<String>::iterator it; while ((it = find(history, result)) != history.end()) history.erase(it); history.push_back(result); return result; } case KEY_UP: if (history_it != history.begin()) { if (history_it == history.end()) saved_result = result; --history_it; result = *history_it; cursor_pos = result.length(); } break; case KEY_DOWN: if (history_it != history.end()) { ++history_it; if (history_it != history.end()) result = *history_it; else result = saved_result; cursor_pos = result.length(); } break; case KEY_LEFT: if (cursor_pos > 0) --cursor_pos; break; case KEY_RIGHT: if (cursor_pos < result.length()) ++cursor_pos; break; case KEY_BACKSPACE: if (cursor_pos != 0) { result = result.substr(0, cursor_pos - 1) + result.substr(cursor_pos, String::npos); --cursor_pos; } current_completion = -1; break; case CTRL('r'): { c = getch(); String reg = RegisterManager::instance()[c][0]; current_completion = -1; result = result.substr(0, cursor_pos) + reg + result.substr(cursor_pos, String::npos); cursor_pos += reg.length(); } break; case 27: throw prompt_aborted(); case '\t': { if (current_completion == -1) { completions = completer(result, cursor_pos); if (completions.candidates.empty()) break; text_before_completion = result.substr(completions.start, completions.end - completions.start); } ++current_completion; String completion; if (current_completion >= completions.candidates.size()) { if (current_completion == completions.candidates.size() and std::find(completions.candidates.begin(), completions.candidates.end(), text_before_completion) == completions.candidates.end()) completion = text_before_completion; else { current_completion = 0; completion = completions.candidates[0]; } } else completion = completions.candidates[current_completion]; move(max_y-1, text.length()); result = result.substr(0, completions.start) + completion; cursor_pos = completions.start + completion.length(); break; } default: current_completion = -1; result = result.substr(0, cursor_pos) + (char)c + result.substr(cursor_pos, String::npos); ++cursor_pos; } move(max_y - 1, text.length()); clrtoeol(); addstr(result.c_str()); move(max_y - 1, text.length() + cursor_pos); refresh(); } return result; } void NCursesClient::print_status(const String& status) { int x,y; getmaxyx(stdscr, y, x); move(y-1, 0); clrtoeol(); addstr(status.c_str()); } }
fix first ~ line drawing
ncurses: fix first ~ line drawing
C++
unlicense
alpha123/kakoune,jkonecny12/kakoune,occivink/kakoune,jjthrash/kakoune,alpha123/kakoune,alexherbo2/kakoune,flavius/kakoune,jkonecny12/kakoune,Asenar/kakoune,rstacruz/kakoune,alpha123/kakoune,rstacruz/kakoune,ekie/kakoune,flavius/kakoune,lenormf/kakoune,jjthrash/kakoune,elegios/kakoune,danielma/kakoune,jkonecny12/kakoune,danr/kakoune,zakgreant/kakoune,Asenar/kakoune,elegios/kakoune,alexherbo2/kakoune,jjthrash/kakoune,alpha123/kakoune,ekie/kakoune,casimir/kakoune,danielma/kakoune,mawww/kakoune,Asenar/kakoune,jkonecny12/kakoune,Asenar/kakoune,flavius/kakoune,rstacruz/kakoune,Somasis/kakoune,xificurC/kakoune,zakgreant/kakoune,mawww/kakoune,Somasis/kakoune,danielma/kakoune,lenormf/kakoune,danielma/kakoune,Somasis/kakoune,ekie/kakoune,danr/kakoune,xificurC/kakoune,casimir/kakoune,occivink/kakoune,elegios/kakoune,flavius/kakoune,zakgreant/kakoune,xificurC/kakoune,mawww/kakoune,occivink/kakoune,lenormf/kakoune,occivink/kakoune,xificurC/kakoune,casimir/kakoune,mawww/kakoune,danr/kakoune,elegios/kakoune,danr/kakoune,Somasis/kakoune,alexherbo2/kakoune,lenormf/kakoune,ekie/kakoune,alexherbo2/kakoune,casimir/kakoune,rstacruz/kakoune,zakgreant/kakoune,jjthrash/kakoune
85db73411ac1065c80200d13e8795dec2ad11c8e
include/laplus/internal/array_impl.hpp
include/laplus/internal/array_impl.hpp
/****************************************************************************** * * laplus/internal/array_impl.hpp * * MIT License * * Copyright (c) 2016 Kotone Itaya * * 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. * *****************************************************************************/ namespace laplus { namespace internal { namespace { template<typename T> std::size_t align(const std::size_t size) { return size + (size % (256 / (sizeof(T) * 8))); } } // unnamed namespace template<typename T> Array<T>::Array() : buffer(nullptr), length(0) {} template<typename T> Array<T>::Array(T* const ptr, std::size_t size) : buffer(ptr), length(size) {} template<typename T> Array<T>::Array(const Array<T>& other) : buffer(other.buffer), length(other.length) {} template<typename T> Array<T>::Array(Array<T>&& other) noexcept : buffer(other.buffer), length(other.length) { other.buffer = nullptr; other.length = 0; } template<typename T> Array<T>::~Array() {} template<typename T> Array<T>& Array<T>::operator=(const Array<T>& other) { Array another(other); *this = std::move(another); return *this; } template<typename T> Array<T>& Array<T>::operator=(Array<T>&& other) noexcept { using std::swap; swap(*this, other); return *this; } template<typename T> T& Array<T>::operator[](std::size_t index) const { assert(index < align(this->length)); return *(this->buffer + index); } template<typename T> void swap(Array<T>& a, Array<T>& b) { using std::swap; swap(a.buffer, b.buffer); swap(a.length, b.length); } template<typename T> T* const Array<T>::get() const { return buffer; } template<typename T> void Array<T>::set(T* const ptr, const std::size_t size) { this->buffer = ptr; this->length = size; } template<typename T> const std::size_t Array<T>::size() const { return length; } template<typename T> const bool Array<T>::empty() const { return buffer == nullptr; } } // namespace internal } // namespace laplus
/****************************************************************************** * * laplus/internal/array_impl.hpp * * MIT License * * Copyright (c) 2016 Kotone Itaya * * 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. * *****************************************************************************/ namespace laplus { namespace internal { namespace { template<typename T> std::size_t align(const std::size_t size) { return size + (size % (256 / (sizeof(T) * 8))); } } // unnamed namespace template<typename T> Array<T>::Array() : buffer(nullptr), length(0) {} template<typename T> Array<T>::Array(T* const ptr, std::size_t size) : buffer(ptr), length(size) {} template<typename T> Array<T>::Array(const Array<T>& other) : buffer(other.buffer), length(other.length) {} template<typename T> Array<T>::Array(Array<T>&& other) noexcept : buffer(other.buffer), length(other.length) { other.buffer = nullptr; other.length = 0; } template<typename T> Array<T>::~Array() {} template<typename T> Array<T>& Array<T>::operator=(const Array<T>& other) { Array another(other); *this = std::move(another); return *this; } template<typename T> Array<T>& Array<T>::operator=(Array<T>&& other) noexcept { using std::swap; swap(*this, other); return *this; } template<typename T> T& Array<T>::operator[](std::size_t index) const { assert(index < align<T>(this->length)); return *(this->buffer + index); } template<typename T> void swap(Array<T>& a, Array<T>& b) { using std::swap; swap(a.buffer, b.buffer); swap(a.length, b.length); } template<typename T> T* const Array<T>::get() const { return buffer; } template<typename T> void Array<T>::set(T* const ptr, const std::size_t size) { this->buffer = ptr; this->length = size; } template<typename T> const std::size_t Array<T>::size() const { return length; } template<typename T> const bool Array<T>::empty() const { return buffer == nullptr; } } // namespace internal } // namespace laplus
Fix align template
Fix align template
C++
mit
ktnyt/LAPlus
38d8f4b54531354a99592a355364e6fa185cdc4e
JPetScopeTask/JPetScopeTask.cpp
JPetScopeTask/JPetScopeTask.cpp
/** * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetScopeTask.cpp * @brief Module for oscilloscope data * Reads oscilloscope ASCII files and produces JPetRecoSignal objects. */ #include "JPetScopeTask.h" #include "../JPetParamManager/JPetParamManager.h" #include <iostream> #include "JPetScopeTaskUtils.h" #include "../JPetCommonTools/JPetCommonTools.h" #include <boost/filesystem.hpp> using namespace boost::filesystem; JPetScopeTask::JPetScopeTask(const char * name, const char * description): JPetTask(name, description), fWriter(0) { } int JPetScopeTask::getTimeWindowIndex(const std::string& pathAndFileName) { DEBUG("JPetScopeTask"); int time_window_index = -1; if (!boost::filesystem::exists(pathAndFileName)) { ERROR("File does not exist "); } int res = sscanf(JPetCommonTools::extractFileNameFromFullPath(pathAndFileName).c_str(), "%*3s %d", &time_window_index); if (res <= 0) { ERROR("scanf failed"); return -1; } else { return time_window_index; } } void JPetScopeTask::exec() { DEBUG("JPetScopeTask getParamBank() called"); assert(fParamManager); auto& bank = fParamManager->getParamBank(); if (bank.isDummy()) { ERROR("bank is Dummy"); } else { auto inputFilesInTimeWindowOrder = getFilesInTimeWindowOrder(fInputFiles); for(const auto & file : inputFilesInTimeWindowOrder){ DEBUG(std::string("file to open:")+file.first); JPetRecoSignal sig = RecoSignalUtils::generateSignal(file.first.c_str()); sig.setTimeWindowIndex(getTimeWindowIndex(file.first)); DEBUG("before setPM"); const JPetPM & pm = bank.getPM(file.second); sig.setPM(pm); DEBUG("after setPM"); assert(fWriter); fWriter->write(sig); } } } std::multimap<std::string, int, cmpByTimeWindowIndex> JPetScopeTask::getFilesInTimeWindowOrder(const std::map<std::string, int>& inputFiles) const { std::multimap<std::string, int, cmpByTimeWindowIndex> orderedMap(inputFiles.begin(), inputFiles.end()); return orderedMap; }
/** * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetScopeTask.cpp * @brief Module for oscilloscope data * Reads oscilloscope ASCII files and produces JPetRecoSignal objects. */ #include "JPetScopeTask.h" #include "../JPetParamManager/JPetParamManager.h" #include <iostream> #include "JPetScopeTaskUtils.h" #include "../JPetCommonTools/JPetCommonTools.h" #include <boost/filesystem.hpp> using namespace boost::filesystem; JPetScopeTask::JPetScopeTask(const char * name, const char * description): JPetTask(name, description), fWriter(0) { } int JPetScopeTask::getTimeWindowIndex(const std::string& pathAndFileName) { DEBUG("JPetScopeTask"); int time_window_index = -1; if (!boost::filesystem::exists(pathAndFileName)) { ERROR("File does not exist "); } int res = sscanf(JPetCommonTools::extractFileNameFromFullPath(pathAndFileName).c_str(), "%*3s %d", &time_window_index); if (res <= 0) { ERROR("scanf failed"); return -1; } else { return time_window_index; } } void JPetScopeTask::exec() { DEBUG("JPetScopeTask getParamBank() called"); assert(fParamManager); auto& bank = fParamManager->getParamBank(); if (bank.isDummy()) { ERROR("bank is Dummy"); } else { auto inputFilesInTimeWindowOrder = getFilesInTimeWindowOrder(fInputFiles); for(const auto & file : inputFilesInTimeWindowOrder){ DEBUG(std::string("file to open:")+file.first); JPetRecoSignal sig = RecoSignalUtils::generateSignal(file.first.c_str()); sig.setTimeWindowIndex(getTimeWindowIndex(file.first)); DEBUG("before setPM"); const JPetPM & pm = bank.getPM(file.second); const JPetBarrelSlot & bs = pm.getBarrelSlot(); sig.setPM(pm); sig.setBarrelSlot(bs); DEBUG("after setPM"); assert(fWriter); fWriter->write(sig); } } } std::multimap<std::string, int, cmpByTimeWindowIndex> JPetScopeTask::getFilesInTimeWindowOrder(const std::map<std::string, int>& inputFiles) const { std::multimap<std::string, int, cmpByTimeWindowIndex> orderedMap(inputFiles.begin(), inputFiles.end()); return orderedMap; }
Fix setting of missing TRef-s
Fix setting of missing TRef-s
C++
apache-2.0
wkrzemien/j-pet-framework,alexkernphysiker/j-pet-framework,JPETTomography/j-pet-framework,wkrzemien/j-pet-framework,JPETTomography/j-pet-framework,alexkernphysiker/j-pet-framework,alexkernphysiker/j-pet-framework,alexkernphysiker/j-pet-framework,wkrzemien/j-pet-framework,alexkernphysiker/j-pet-framework,wkrzemien/j-pet-framework,JPETTomography/j-pet-framework,wkrzemien/j-pet-framework
785bd024b9452c2d6d7fb7c42d62f07637964f52
include/scene/universalgravitation.hpp
include/scene/universalgravitation.hpp
#ifndef UNIVERSALGRAVITATION_HPP #define UNIVERSALGRAVITATION_HPP #include <vector> #include <algorithm> #include "scene/gravitationalobject.hpp" namespace scene { class UniversalGravitation { private: static constexpr double G = 0.0000000000667384; std::vector<GravitationalObject*> gravityObjects; inline void addObject(GravitationalObject* gravObject); inline void delObject(GravitationalObject* gravObject); void update(); }; void UniversalGravitation::addObject(GravitationalObject* gravObject) { gravityObjects.push_back(gravObject); } void UniversalGravitation::delObject(GravitationalObject* gravObject) { std::remove(gravityObjects.begin(), gravityObjects.end(), gravObject); } } #endif // UNIVERSALGRAVITATION_HPP
#ifndef UNIVERSALGRAVITATION_HPP #define UNIVERSALGRAVITATION_HPP #include <vector> #include <algorithm> #include "scene/gravitationalobject.hpp" namespace scene { class UniversalGravitation { private: static constexpr double G = 0.0000000000667384; std::vector<GravitationalObject*> gravityObjects; public: inline void addObject(GravitationalObject* gravObject); inline void delObject(GravitationalObject* gravObject); void update(); }; void UniversalGravitation::addObject(GravitationalObject* gravObject) { gravityObjects.push_back(gravObject); } void UniversalGravitation::delObject(GravitationalObject* gravObject) { std::remove(gravityObjects.begin(), gravityObjects.end(), gravObject); } } #endif // UNIVERSALGRAVITATION_HPP
Mark public intended methods in UniversalGravitation.
Mark public intended methods in UniversalGravitation.
C++
apache-2.0
maruno/collisionsdemo,maruno/collisionsdemo
d086f73a8f7da2741083588768648b9ca5fbe605
include/tao/pegtl/analysis/generic.hpp
include/tao/pegtl/analysis/generic.hpp
// Copyright (c) 2014-2019 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_ANALYSIS_GENERIC_HPP #define TAO_PEGTL_ANALYSIS_GENERIC_HPP #include "../config.hpp" #include "grammar_info.hpp" #include "insert_rules.hpp" #include "rule_type.hpp" namespace TAO_PEGTL_NAMESPACE::analysis { template< rule_type Type, typename... Rules > struct generic { template< typename Name > static std::string insert( grammar_info& g ) { const auto r = g.insert< Name >( Type ); if( r.second ) { insert_rules< Rules... >::insert( g, r.first->second ); } return r.first->first; } }; } // namespace TAO_PEGTL_NAMESPACE::analysis #endif
// Copyright (c) 2014-2019 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_ANALYSIS_GENERIC_HPP #define TAO_PEGTL_ANALYSIS_GENERIC_HPP #include "../config.hpp" #include "grammar_info.hpp" #include "insert_rules.hpp" #include "rule_type.hpp" namespace TAO_PEGTL_NAMESPACE::analysis { template< rule_type Type, typename... Rules > struct generic { template< typename Name > static std::string insert( grammar_info& g ) { const auto [ it, success ] = g.insert< Name >( Type ); if( success ) { insert_rules< Rules... >::insert( g, it->second ); } return it->first; } }; } // namespace TAO_PEGTL_NAMESPACE::analysis #endif
Use structured binding
Use structured binding
C++
mit
ColinH/PEGTL,ColinH/PEGTL
b248013448ed40ae9f75bcb54f8282ad870575bb
include/utxx/concurrent_mpsc_queue.hpp
include/utxx/concurrent_mpsc_queue.hpp
//---------------------------------------------------------------------------- /// \file concurrent_mpsc_queue.hpp /// \author Serge Aleynikov //---------------------------------------------------------------------------- /// \brief Producer/consumer queue. /// /// Based on code from: /// https://github.com/facebook/folly/blob/master/folly/concurrent_spsc_queue.h /// Original public domain version authored by Facebook /// Modifications by Serge Aleynikov //---------------------------------------------------------------------------- // Created: 2014-06-10 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2014 Serge Aleynikov <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #pragma once #include <atomic> #include <cassert> #include <cstdlib> #include <stdexcept> #include <type_traits> #include <utility> #include <boost/noncopyable.hpp> #include <boost/type_traits.hpp> #include <utxx/math.hpp> namespace utxx { #if __cplusplus >= 201103L /** * A lock-free implementation of the multi-producer-single-consumer queue. * All elements are equally sized of type T. */ template <class T, class Allocator = std::allocator<char>> struct concurrent_mpsc_queue { class node { node* m_next; mutable T m_data; public: node(T&& d) : m_next(nullptr), m_data(std::forward<T>(d)) {} node(const T& d) : m_next(nullptr), m_data(d) {} template<typename... Args> node(Args&&... args) : m_next(nullptr), m_data(std::forward<Args>(args)...) {} const T& data() const { return m_data; } T& data() { return m_data; } constexpr unsigned size() const { return sizeof(T); } node* next() { return m_next; } void next(node* a_node) { m_next = a_node; } }; typedef typename Allocator::template rebind<node>::other Alloc; explicit concurrent_mpsc_queue(const Alloc& a_alloc = Alloc()) : m_head (nullptr) , m_allocator(a_alloc) {} bool empty() const { return m_head.load(std::memory_order_relaxed) == nullptr; } template <typename... Args> node* allocate(Args&&... args) { try { node* n = m_allocator.allocate(1); new (n) node(std::forward<Args>(args)...); return n; } catch (std::bad_alloc const&) { return nullptr; } } /// Insert an element's copy into the queue. bool push(const T& data) { try { node* n = m_allocator.allocate(1); new (n) node(data); push (n); return true; } catch (std::bad_alloc const&) { return false; } } /// Insert an element into the queue. /// The element must have been previously allocated using allocate() function. void push(node* a_node) { node* h; do { h = m_head.load(std::memory_order_relaxed); a_node->next(h); } while (!m_head.compare_exchange_weak(h, a_node, std::memory_order_release)); } /// Emplace an element into the queue by constructing the data with given arguments. template <typename... Args> bool emplace(Args&&... args) { try { node* n = allocate(std::forward<Args>(args)...); push(n); return true; } catch (std::bad_alloc const&) { return false; } } /// Pop all queued elements in the order of insertion /// /// Use concurrent_mpsc_queue::free() to deallocate each node node* pop_all() { node* first = nullptr; for (node* tmp, *last = pop_all_reverse(); last; first = tmp) { tmp = last; last = last->next(); tmp->next(first); } return first; } /// Pop all queued elements in the reverse order /// /// Use concurrent_mpsc_queue::free() to deallocate each node node* pop_all_reverse() { return m_head.exchange(nullptr, std::memory_order_acquire); } /// Deallocate a node created by a call to pop_all() or pop_all_reverse() void free(node* a_node) { a_node->~node(); m_allocator.deallocate(a_node, a_node->size()); } /// Clear the queue void clear() { for (node* tmp, *last = pop_all_reverse(); last; last = tmp) { tmp = last->next(); free(last); } } private: std::atomic<node*> m_head; Alloc m_allocator; }; template <class Allocator> struct concurrent_mpsc_queue<char, Allocator> { static_assert(std::is_same<char, typename Allocator::value_type>::value, "Allocator must have char as its value_type!"); class node { node* m_next; const unsigned m_size; char m_data[0]; friend struct concurrent_mpsc_queue<char, Allocator>; public: node(unsigned a_sz) : m_next(nullptr), m_size(a_sz) {} char* data() { return m_data; } unsigned size() const { return m_size; } node* next() { return m_next; } void next(node* a){ m_next = a; } template <class T> T& to() { assert(sizeof(T) == m_size); return *reinterpret_cast<T*>(m_data); } template <class T> const T& to() const { assert(sizeof(T) == m_size); return *reinterpret_cast<const T*>(m_data); } }; explicit concurrent_mpsc_queue(const Allocator& a_alloc = Allocator()) : m_head (nullptr) , m_allocator(a_alloc) {} bool empty() const { return m_head.load(std::memory_order_relaxed) == nullptr; } node* allocate(size_t a_size) { try { node* n = m_allocator.allocate(sizeof(node) + a_size); new (n) node(a_size); return n; } catch(std::bad_alloc const&) { return nullptr; } } /// Push an element of type T on the queue by dynamically allocating it and /// calling its constructor. template <typename T, typename... Args> bool emplace(Args&&... args) { try { node* n = reinterpret_cast<node*>(m_allocator.allocate(sizeof(node) + sizeof(T))); new (n) node(sizeof(T)); T* data = reinterpret_cast<T*>(n->data()); new (data) T(std::forward<Args>(args)...); push (n); return true; } catch(std::bad_alloc const&) { return false; } } template <typename InitLambda> bool push(size_t a_size, InitLambda a_fun) { try { node* n = reinterpret_cast<node*>(m_allocator.allocate(sizeof(node) + a_size)); new (n) node(a_size); a_fun(n->data(), a_size); push (n); return true; } catch(std::bad_alloc const&) { return false; } } template <int N> bool push(const char (&a_value)[N]) { try { node* n = reinterpret_cast<node*>(m_allocator.allocate(sizeof(node) + N)); new (n) node(N); memcpy(n->data(), a_value, N); push (n); return true; } catch(std::bad_alloc const&) { return false; } } template <typename Ch> bool push(const std::basic_string<Ch>& a_value) { try { size_t sz = a_value.size()+1; node* n = reinterpret_cast<node*>(m_allocator.allocate(sizeof(node) + sz)); new (n) node(sz); memcpy(n->data(), a_value.c_str(), sz); push (n); return true; } catch(std::bad_alloc const&) { return false; } } /// Insert an element into the queue. /// The element must have been previously allocated using allocate() function. void push(node* a_node) { node* h; do { h = m_head.load(std::memory_order_relaxed); a_node->next(h); } while (!m_head.compare_exchange_weak(h, a_node, std::memory_order_release)); } /// Pop all queued elements in the order of insertion /// /// Use concurrent_mpsc_queue::free() to deallocate each node node* pop_all(void) { node* first = nullptr; for (node* tmp, *last = pop_all_reverse(); last; first = tmp) { tmp = last; last = last->m_next; tmp->m_next = first; } return first; } /// Pop all queued elements in the reverse order /// /// Use concurrent_mpsc_queue::free() to deallocate each node node* pop_all_reverse() { return m_head.exchange(nullptr, std::memory_order_acquire); } /// Deallocate a node created by a call to pop_all() or pop_all_reverse() void free(node* a_node) { a_node->~node(); m_allocator.deallocate(reinterpret_cast<char*>(a_node), sizeof(node) + a_node->size()); } /// Clear the queue void clear() { for (node* tmp, *last = pop_all_reverse(); last; last = tmp) { tmp = last->next(); free(last); } } public: std::atomic<node*> m_head; Allocator m_allocator; }; #endif // __cplusplus > 201103L } // namespace utxx
//---------------------------------------------------------------------------- /// \file concurrent_mpsc_queue.hpp /// \author Serge Aleynikov //---------------------------------------------------------------------------- /// \brief Producer/consumer queue. //---------------------------------------------------------------------------- // Created: 2014-06-10 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2014 Serge Aleynikov <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #pragma once #include <atomic> #include <cassert> #include <cstdlib> #include <stdexcept> #include <type_traits> #include <utility> #include <boost/noncopyable.hpp> #include <boost/type_traits.hpp> #include <utxx/math.hpp> namespace utxx { #if __cplusplus >= 201103L /** * A lock-free implementation of the multi-producer-single-consumer queue. * All elements are equally sized of type T. */ template <class T, class Allocator = std::allocator<char>> struct concurrent_mpsc_queue { class node { node* m_next; mutable T m_data; public: node(T&& d) : m_next(nullptr), m_data(std::forward<T>(d)) {} node(const T& d) : m_next(nullptr), m_data(d) {} template<typename... Args> node(Args&&... args) : m_next(nullptr), m_data(std::forward<Args>(args)...) {} const T& data() const { return m_data; } T& data() { return m_data; } constexpr unsigned size() const { return sizeof(T); } node* next() { return m_next; } void next(node* a_node) { m_next = a_node; } }; typedef typename Allocator::template rebind<node>::other Alloc; explicit concurrent_mpsc_queue(const Alloc& a_alloc = Alloc()) : m_head (nullptr) , m_allocator(a_alloc) {} bool empty() const { return m_head.load(std::memory_order_relaxed) == nullptr; } template <typename... Args> node* allocate(Args&&... args) { try { node* n = m_allocator.allocate(1); new (n) node(std::forward<Args>(args)...); return n; } catch (std::bad_alloc const&) { return nullptr; } } /// Insert an element's copy into the queue. bool push(const T& data) { try { node* n = m_allocator.allocate(1); new (n) node(data); push (n); return true; } catch (std::bad_alloc const&) { return false; } } /// Insert an element into the queue. /// The element must have been previously allocated using allocate() function. void push(node* a_node) { node* h; do { h = m_head.load(std::memory_order_relaxed); a_node->next(h); } while (!m_head.compare_exchange_weak(h, a_node, std::memory_order_release)); } /// Emplace an element into the queue by constructing the data with given arguments. template <typename... Args> bool emplace(Args&&... args) { try { node* n = allocate(std::forward<Args>(args)...); push(n); return true; } catch (std::bad_alloc const&) { return false; } } /// Pop all queued elements in the order of insertion /// /// Use concurrent_mpsc_queue::free() to deallocate each node node* pop_all() { node* first = nullptr; for (node* tmp, *last = pop_all_reverse(); last; first = tmp) { tmp = last; last = last->next(); tmp->next(first); } return first; } /// Pop all queued elements in the reverse order /// /// Use concurrent_mpsc_queue::free() to deallocate each node node* pop_all_reverse() { return m_head.exchange(nullptr, std::memory_order_acquire); } /// Deallocate a node created by a call to pop_all() or pop_all_reverse() void free(node* a_node) { a_node->~node(); m_allocator.deallocate(a_node, a_node->size()); } /// Clear the queue void clear() { for (node* tmp, *last = pop_all_reverse(); last; last = tmp) { tmp = last->next(); free(last); } } private: std::atomic<node*> m_head; Alloc m_allocator; }; template <class Allocator> struct concurrent_mpsc_queue<char, Allocator> { static_assert(std::is_same<char, typename Allocator::value_type>::value, "Allocator must have char as its value_type!"); class node { node* m_next; const unsigned m_size; char m_data[0]; friend struct concurrent_mpsc_queue<char, Allocator>; public: node(unsigned a_sz) : m_next(nullptr), m_size(a_sz) {} char* data() { return m_data; } unsigned size() const { return m_size; } node* next() { return m_next; } void next(node* a){ m_next = a; } template <class T> T& to() { assert(sizeof(T) == m_size); return *reinterpret_cast<T*>(m_data); } template <class T> const T& to() const { assert(sizeof(T) == m_size); return *reinterpret_cast<const T*>(m_data); } }; explicit concurrent_mpsc_queue(const Allocator& a_alloc = Allocator()) : m_head (nullptr) , m_allocator(a_alloc) {} bool empty() const { return m_head.load(std::memory_order_relaxed) == nullptr; } node* allocate(size_t a_size) { try { node* n = m_allocator.allocate(sizeof(node) + a_size); new (n) node(a_size); return n; } catch(std::bad_alloc const&) { return nullptr; } } /// Push an element of type T on the queue by dynamically allocating it and /// calling its constructor. template <typename T, typename... Args> bool emplace(Args&&... args) { try { node* n = reinterpret_cast<node*>(m_allocator.allocate(sizeof(node) + sizeof(T))); new (n) node(sizeof(T)); T* data = reinterpret_cast<T*>(n->data()); new (data) T(std::forward<Args>(args)...); push (n); return true; } catch(std::bad_alloc const&) { return false; } } template <typename InitLambda> bool push(size_t a_size, InitLambda a_fun) { try { node* n = reinterpret_cast<node*>(m_allocator.allocate(sizeof(node) + a_size)); new (n) node(a_size); a_fun(n->data(), a_size); push (n); return true; } catch(std::bad_alloc const&) { return false; } } template <int N> bool push(const char (&a_value)[N]) { try { node* n = reinterpret_cast<node*>(m_allocator.allocate(sizeof(node) + N)); new (n) node(N); memcpy(n->data(), a_value, N); push (n); return true; } catch(std::bad_alloc const&) { return false; } } template <typename Ch> bool push(const std::basic_string<Ch>& a_value) { try { size_t sz = a_value.size()+1; node* n = reinterpret_cast<node*>(m_allocator.allocate(sizeof(node) + sz)); new (n) node(sz); memcpy(n->data(), a_value.c_str(), sz); push (n); return true; } catch(std::bad_alloc const&) { return false; } } /// Insert an element into the queue. /// The element must have been previously allocated using allocate() function. void push(node* a_node) { node* h; do { h = m_head.load(std::memory_order_relaxed); a_node->next(h); } while (!m_head.compare_exchange_weak(h, a_node, std::memory_order_release)); } /// Pop all queued elements in the order of insertion /// /// Use concurrent_mpsc_queue::free() to deallocate each node node* pop_all(void) { node* first = nullptr; for (node* tmp, *last = pop_all_reverse(); last; first = tmp) { tmp = last; last = last->m_next; tmp->m_next = first; } return first; } /// Pop all queued elements in the reverse order /// /// Use concurrent_mpsc_queue::free() to deallocate each node node* pop_all_reverse() { return m_head.exchange(nullptr, std::memory_order_acquire); } /// Deallocate a node created by a call to pop_all() or pop_all_reverse() void free(node* a_node) { a_node->~node(); m_allocator.deallocate(reinterpret_cast<char*>(a_node), sizeof(node) + a_node->size()); } /// Clear the queue void clear() { for (node* tmp, *last = pop_all_reverse(); last; last = tmp) { tmp = last->next(); free(last); } } public: std::atomic<node*> m_head; Allocator m_allocator; }; #endif // __cplusplus > 201103L } // namespace utxx
Remove erroneous comment
Remove erroneous comment
C++
lgpl-2.1
saleyn/utxx,saleyn/utxx,saleyn/utxx,saleyn/utxx,saleyn/utxx
83b83771a62d81e0d4d27d540d816a9e102ffa9f
src/scrypt.cpp
src/scrypt.cpp
/*- * Copyright 2009 Colin Percival, 2011 ArtForz, 2011 pooler, 2013 Balthazar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * * This file was originally written by Colin Percival as part of the Tarsnap * online backup system. */ #include <stdlib.h> #include <stdint.h> #include "scrypt.h" #include "pbkdf2.h" #include "util.h" #include "net.h" #define SCRYPT_BUFFER_SIZE (131072 + 63) #if defined (__x86_64__) || defined (__i386__) extern "C" void scrypt_core(uint32_t *X, uint32_t *V); #else // TODO: Add cross-platform scrypt_core implementation #endif /* cpu and memory intensive function to transform a 80 byte buffer into a 32 byte output scratchpad size needs to be at least 63 + (128 * r * p) + (256 * r + 64) + (128 * r * N) bytes r = 1, p = 1, N = 1024 */ uint256 scrypt_nosalt(const void* input, size_t inputlen, void *scratchpad) { uint32_t *V; uint32_t X[32]; uint256 result = 0; V = (uint32_t *)(((uintptr_t)(scratchpad) + 63) & ~ (uintptr_t)(63)); PBKDF2_SHA256((const uint8_t*)input, inputlen, (const uint8_t*)input, inputlen, 1, (uint8_t *)X, 128); scrypt_core(X, V); PBKDF2_SHA256((const uint8_t*)input, inputlen, (uint8_t *)X, 128, 1, (uint8_t*)&result, 32); return result; } uint256 scrypt(const void* data, size_t datalen, const void* salt, size_t saltlen, void *scratchpad) { uint32_t *V; uint32_t X[32]; uint256 result = 0; V = (uint32_t *)(((uintptr_t)(scratchpad) + 63) & ~ (uintptr_t)(63)); PBKDF2_SHA256((const uint8_t*)data, datalen, (const uint8_t*)salt, saltlen, 1, (uint8_t *)X, 128); scrypt_core(X, V); PBKDF2_SHA256((const uint8_t*)data, datalen, (uint8_t *)X, 128, 1, (uint8_t*)&result, 32); return result; } uint256 scrypt_hash(const void* input, size_t inputlen) { unsigned char scratchpad[SCRYPT_BUFFER_SIZE]; return scrypt_nosalt(input, inputlen, scratchpad); } uint256 scrypt_salted_hash(const void* input, size_t inputlen, const void* salt, size_t saltlen) { unsigned char scratchpad[SCRYPT_BUFFER_SIZE]; return scrypt(input, inputlen, salt, saltlen, scratchpad); } uint256 scrypt_salted_multiround_hash(const void* input, size_t inputlen, const void* salt, size_t saltlen, const unsigned int nRounds) { uint256 resultHash = scrypt_salted_hash(input, inputlen, salt, saltlen); uint256 transitionalHash = resultHash; for(unsigned int i = 1; i < nRounds; i++) { resultHash = scrypt_salted_hash(input, inputlen, (const void*)&transitionalHash, 32); transitionalHash = resultHash; } return resultHash; } uint256 scrypt_blockhash(const void* input) { unsigned char scratchpad[SCRYPT_BUFFER_SIZE]; return scrypt_nosalt(input, 80, scratchpad); }
/*- * Copyright 2009 Colin Percival, 2011 ArtForz, 2011 pooler, 2013 Balthazar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * * This file was originally written by Colin Percival as part of the Tarsnap * online backup system. */ #include <stdlib.h> #include <stdint.h> #include "scrypt.h" #include "pbkdf2.h" #include "util.h" #include "net.h" #define SCRYPT_BUFFER_SIZE (131072 + 63) #if defined (__x86_64__) || defined (__i386__) || defined(__arm__) extern "C" void scrypt_core(uint32_t *X, uint32_t *V); #else // TODO: Add cross-platform scrypt_core implementation #endif /* cpu and memory intensive function to transform a 80 byte buffer into a 32 byte output scratchpad size needs to be at least 63 + (128 * r * p) + (256 * r + 64) + (128 * r * N) bytes r = 1, p = 1, N = 1024 */ uint256 scrypt_nosalt(const void* input, size_t inputlen, void *scratchpad) { uint32_t *V; uint32_t X[32]; uint256 result = 0; V = (uint32_t *)(((uintptr_t)(scratchpad) + 63) & ~ (uintptr_t)(63)); PBKDF2_SHA256((const uint8_t*)input, inputlen, (const uint8_t*)input, inputlen, 1, (uint8_t *)X, 128); scrypt_core(X, V); PBKDF2_SHA256((const uint8_t*)input, inputlen, (uint8_t *)X, 128, 1, (uint8_t*)&result, 32); return result; } uint256 scrypt(const void* data, size_t datalen, const void* salt, size_t saltlen, void *scratchpad) { uint32_t *V; uint32_t X[32]; uint256 result = 0; V = (uint32_t *)(((uintptr_t)(scratchpad) + 63) & ~ (uintptr_t)(63)); PBKDF2_SHA256((const uint8_t*)data, datalen, (const uint8_t*)salt, saltlen, 1, (uint8_t *)X, 128); scrypt_core(X, V); PBKDF2_SHA256((const uint8_t*)data, datalen, (uint8_t *)X, 128, 1, (uint8_t*)&result, 32); return result; } uint256 scrypt_hash(const void* input, size_t inputlen) { unsigned char scratchpad[SCRYPT_BUFFER_SIZE]; return scrypt_nosalt(input, inputlen, scratchpad); } uint256 scrypt_salted_hash(const void* input, size_t inputlen, const void* salt, size_t saltlen) { unsigned char scratchpad[SCRYPT_BUFFER_SIZE]; return scrypt(input, inputlen, salt, saltlen, scratchpad); } uint256 scrypt_salted_multiround_hash(const void* input, size_t inputlen, const void* salt, size_t saltlen, const unsigned int nRounds) { uint256 resultHash = scrypt_salted_hash(input, inputlen, salt, saltlen); uint256 transitionalHash = resultHash; for(unsigned int i = 1; i < nRounds; i++) { resultHash = scrypt_salted_hash(input, inputlen, (const void*)&transitionalHash, 32); transitionalHash = resultHash; } return resultHash; } uint256 scrypt_blockhash(const void* input) { unsigned char scratchpad[SCRYPT_BUFFER_SIZE]; return scrypt_nosalt(input, 80, scratchpad); }
Add ARM to architectures list
Add ARM to architectures list
C++
mit
som4paul/BolieC,Rimbit/Wallets,fsb4000/novacoin,Whitecoin-org/Whitecoin,elambert2014/novacoin,MOIN/moin,LanaCoin/lanacoin,byncoin-project/byncoin,ALEXIUMCOIN/alexium,byncoin-project/byncoin,shadowproject/shadow,ghostlander/Orbitcoin,MOIN/moin,Rimbit/Wallets,okcashpro/okcash,CoinBlack/bitcoin,AquariusNetwork/ARCO,CoinBlack/bitcoin,rat4/blackcoin,shadowproject/shadow,gades/novacoin,nochowderforyou/clams,iadix/iadixcoin,IOCoin/DIONS,penek/novacoin,lateminer/DopeCoinGold,dopecoin-dev/DopeCoinGold,valorbit/valorbit,stamhe/novacoin,novacoin-project/novacoin,Kefkius/clams,valorbit/valorbit-oss,vectorcoindev/Vector,penek/novacoin,effectsToCause/vericoin,MOIN/moin,IOCoin/DIONS,valorbit/valorbit-oss,elambert2014/novacoin,fsb4000/novacoin,vectorcoindev/Vector,VsyncCrypto/Vsync,robvanmieghem/clams,iadix/iadixcoin,okcashpro/okcash,novacoin-project/novacoin,shadowproject/shadow,som4paul/BolieC,CoinBlack/blackcoin,robvanmieghem/clams,okcashpro/okcash,iadix/iadixcoin,GeopaymeEE/e-goldcoin,thunderrabbit/clams,MOIN/moin,GeopaymeEE/e-goldcoin,ALEXIUMCOIN/alexium,CoinBlack/blackcoin,TheoremCrypto/TheoremCoin,IOCoin/DIONS,gades/novacoin,lateminer/DopeCoinGold,prodigal-son/blackcoin,novacoin-project/novacoin,robvanmieghem/clams,MOIN/moin,CoinBlack/bitcoin,dooglus/clams,valorbit/valorbit,TheoremCrypto/TheoremCoin,pinkmagicdev/SwagBucks,AquariusNetwork/ARCOv2,jyap808/jumbucks,elambert2014/novacoin,fsb4000/novacoin,rat4/blackcoin,penek/novacoin,stamhe/novacoin,stamhe/novacoin,greencoin-dev/GreenCoinV2,gades/novacoin,GeopaymeEE/e-goldcoin,vectorcoindev/Vector,ghostlander/Orbitcoin,GeopaymeEE/e-goldcoin,okcashpro/okcash,AquariusNetwork/ARCOv2,Jheguy2/Mercury,pinkmagicdev/SwagBucks,Kefkius/clams,byncoin-project/byncoin,ALEXIUMCOIN/alexium,ghostlander/Orbitcoin,IOCoin/iocoin,effectsToCause/vericoin,Jheguy2/Mercury,AquariusNetwork/ARCO,IOCoin/iocoin,Rimbit/Wallets,vectorcoindev/Vector,gades/novacoin,jyap808/jumbucks,elambert2014/cbx2,fsb4000/novacoin,benzhi888/renminbi,prodigal-son/blackcoin,novacoin-project/novacoin,AquariusNetwork/ARCOv2,valorbit/valorbit-oss,CoinBlack/bitcoin,ghostlander/Orbitcoin,ALEXIUMCOIN/alexium,Kefkius/clams,Whitecoin-org/Whitecoin,shadowproject/shadow,byncoin-project/byncoin,TheoremCrypto/TheoremCoin,novacoin-project/novacoin,valorbit/valorbit-oss,nochowderforyou/clams,shadowproject/shadow,fsb4000/novacoin,vectorcoindev/Vector,blackcoinhelp/blackcoin,Jheguy2/Mercury,Rimbit/Wallets,gades/novacoin,landcoin-ldc/landcoin,VsyncCrypto/Vsync,fsb4000/novacoin,robvanmieghem/clams,landcoin-ldc/landcoin,jyap808/jumbucks,blackcoinhelp/blackcoin,benzhi888/renminbi,IOCoin/iocoin,IOCoin/DIONS,blackcoinhelp/blackcoin,valorbit/valorbit-oss,thunderrabbit/clams,dooglus/clams,ALEXIUMCOIN/alexium,prodigal-son/blackcoin,nochowderforyou/clams,iadix/iadixcoin,xranby/blackcoin,GeopaymeEE/e-goldcoin,VsyncCrypto/Vsync,thunderrabbit/clams,blackcoinhelp/blackcoin,thunderrabbit/clams,xranby/blackcoin,som4paul/BolieC,CoinBlack/blackcoin,effectsToCause/vericoin,elambert2014/novacoin,stamhe/novacoin,dopecoin-dev/DopeCoinGold,CoinBlack/blackcoin,dopecoin-dev/DopeCoinGold,greencoin-dev/GreenCoinV2,iadix/iadixcoin,penek/novacoin,Kefkius/clams,AquariusNetwork/ARCOv2,benzhi888/renminbi,stamhe/novacoin,rat4/blackcoin,byncoin-project/byncoin,dopecoin-dev/DopeCoinGold,Whitecoin-org/Whitecoin,VsyncCrypto/Vsync,IOCoin/iocoin,Whitecoin-org/Whitecoin,elambert2014/cbx2,penek/novacoin,lateminer/DopeCoinGold,xranby/blackcoin,AquariusNetwork/ARCO,rat4/blackcoin,landcoin-ldc/landcoin,dooglus/clams,iadix/iadixcoin,nochowderforyou/clams,VsyncCrypto/Vsync,iadix/iadixcoin,ghostlander/Orbitcoin,pinkmagicdev/SwagBucks,novacoin-project/novacoin,som4paul/BolieC,TheoremCrypto/TheoremCoin,iadix/iadixcoin,MOIN/moin,Kefkius/clams,LanaCoin/lanacoin,IOCoin/DIONS,IOCoin/iocoin,landcoin-ldc/landcoin,blackcoinhelp/blackcoin,jyap808/jumbucks,robvanmieghem/clams,dopecoin-dev/DopeCoinGold,byncoin-project/byncoin,AquariusNetwork/ARCO,effectsToCause/vericoin,jyap808/jumbucks,nochowderforyou/clams,CoinBlack/bitcoin,elambert2014/cbx2,LanaCoin/lanacoin,elambert2014/novacoin,som4paul/BolieC,Jheguy2/Mercury,TheoremCrypto/TheoremCoin,AquariusNetwork/ARCO,iadix/iadixcoin,gades/novacoin,dooglus/clams,lateminer/DopeCoinGold,dooglus/clams,Jheguy2/Mercury,LanaCoin/lanacoin,effectsToCause/vericoin,elambert2014/cbx2,iadix/iadixcoin,pinkmagicdev/SwagBucks,AquariusNetwork/ARCOv2,LanaCoin/lanacoin,IOCoin/DIONS,CoinBlack/bitcoin,CoinBlack/blackcoin,elambert2014/novacoin,greencoin-dev/GreenCoinV2,prodigal-son/blackcoin,thunderrabbit/clams,IOCoin/DIONS,IOCoin/DIONS,elambert2014/cbx2,iadix/iadixcoin,landcoin-ldc/landcoin,greencoin-dev/GreenCoinV2,valorbit/valorbit,valorbit/valorbit,shadowproject/shadow,rat4/blackcoin,Whitecoin-org/Whitecoin,Rimbit/Wallets,okcashpro/okcash,valorbit/valorbit,lateminer/DopeCoinGold,greencoin-dev/GreenCoinV2,okcashpro/okcash,benzhi888/renminbi,benzhi888/renminbi,xranby/blackcoin,penek/novacoin,prodigal-son/blackcoin,pinkmagicdev/SwagBucks
d7d823bdeda69ce8de8a33b90a6ec116c36ecdab
brave/common/extensions/url_bindings.cc
brave/common/extensions/url_bindings.cc
// Copyright (c) 2017 The Brave 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 <memory> #include <string> #include "brave/common/extensions/url_bindings.h" #include "brave/common/converters/gurl_converter.h" #include "brave/common/converters/string16_converter.h" #include "components/url_formatter/url_formatter.h" #include "extensions/renderer/script_context.h" #include "gin/arguments.h" #include "gin/converter.h" #include "gin/dictionary.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "url/gurl.h" #include "v8/include/v8.h" namespace brave { namespace { class WrappableGURL : public GURL, public gin::Wrappable<WrappableGURL> { public: explicit WrappableGURL(const GURL& other) : GURL(other) {} explicit WrappableGURL(base::StringPiece url_string) : GURL(url_string) {} explicit WrappableGURL(base::StringPiece16 url_string) : GURL(url_string) {} bool is_valid() const { return GURL::is_valid(); } bool is_empty() const { return GURL::is_empty(); } const std::string& spec() const { return GURL::spec(); } const std::string& possibly_invalid_spec() const { return GURL::possibly_invalid_spec(); } WrappableGURL* GetWithEmptyPath() const { return new WrappableGURL(GURL::GetWithEmptyPath()); } WrappableGURL* GetOrigin() const { return new WrappableGURL(GURL::GetOrigin()); } WrappableGURL* GetAsReferrer() const { return new WrappableGURL(GURL::GetAsReferrer()); } bool IsStandard() const { return GURL::IsStandard(); } bool SchemeIsHTTPOrHTTPS() const { return GURL::SchemeIsHTTPOrHTTPS(); } bool SchemeIsValidForReferrer() const { return GURL::SchemeIsValidForReferrer(); } bool SchemeIsWSOrWSS() const { return GURL::SchemeIsWSOrWSS(); } bool SchemeIsFile() const { return GURL::SchemeIsFile(); } bool SchemeIsFileSystem() const { return GURL::SchemeIsFileSystem(); } bool SchemeIsCryptographic() const { return GURL::SchemeIsCryptographic(); } bool SchemeIsBlob() const { return GURL::SchemeIsBlob(); } bool SchemeIsSuborigin() const { return GURL::SchemeIsSuborigin(); } std::string GetContent() const { return GURL::GetContent(); } bool HostIsIPAddress() const { return GURL::HostIsIPAddress(); } bool has_scheme() const { return GURL::has_scheme(); } std::string scheme() const { return GURL::scheme(); } bool has_host() const { return GURL::has_host(); } std::string host() const { return GURL::host(); } bool has_username() const { return GURL::has_username(); } std::string username() const { return GURL::username(); } bool has_password() const { return GURL::has_password(); } std::string password() const { return GURL::password(); } bool has_port() const { return GURL::has_port(); } std::string port() const { return GURL::port(); } bool has_path() const { return GURL::has_path(); } std::string path() const { return GURL::path(); } bool has_query() const { return GURL::has_query(); } std::string query() const { return GURL::query(); } bool has_ref() const { return GURL::has_ref(); } std::string ref() const { return GURL::ref(); } int EffectiveIntPort() const { return GURL::EffectiveIntPort(); } int IntPort() const { return GURL::IntPort(); } std::string ExtractFileName() const { return GURL::ExtractFileName(); } std::string PathForRequest() const { return GURL::PathForRequest(); } std::string HostNoBrackets() const { return GURL::HostNoBrackets(); } WrappableGURL* inner_url() const { return new WrappableGURL(*GURL::inner_url()); } bool DomainIs(std::string lower_ascii_domain) const { return GURL::DomainIs(lower_ascii_domain); } WrappableGURL* Resolve(const std::string& relative) const { return new WrappableGURL(GURL::Resolve(relative)); } gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override { return gin::Wrappable<WrappableGURL>::GetObjectTemplateBuilder(isolate) .SetMethod("isValid", &WrappableGURL::is_valid) .SetMethod("isEmpty", &WrappableGURL::is_empty) .SetMethod("spec", &WrappableGURL::spec) .SetMethod("possiblyInvalidSpec", &WrappableGURL::possibly_invalid_spec) .SetMethod("resolve", &WrappableGURL::Resolve) .SetMethod("getWithEmptyPath", &WrappableGURL::GetWithEmptyPath) .SetMethod("getOrigin", &WrappableGURL::GetOrigin) .SetMethod("getAsReferrer", &WrappableGURL::GetAsReferrer) .SetMethod("isStandard", &WrappableGURL::IsStandard) .SetMethod("schemeIsHTTPOrHTTPS", &WrappableGURL::SchemeIsHTTPOrHTTPS) .SetMethod("schemeIsValidForReferrer", &WrappableGURL::SchemeIsValidForReferrer) .SetMethod("schemeIsWSOrWSS", &WrappableGURL::SchemeIsWSOrWSS) .SetMethod("schemeIsFile", &WrappableGURL::SchemeIsFile) .SetMethod("schemeIsFileSystem", &WrappableGURL::SchemeIsFileSystem) .SetMethod("schemeIsCryptographic", &WrappableGURL::SchemeIsCryptographic) .SetMethod("schemeIsBlob", &WrappableGURL::SchemeIsBlob) .SetMethod("schemeIsSuborigin", &WrappableGURL::SchemeIsSuborigin) .SetMethod("getContent", &WrappableGURL::GetContent) .SetMethod("hostIsIPAddress", &WrappableGURL::HostIsIPAddress) .SetMethod("hasScheme", &WrappableGURL::has_scheme) .SetMethod("scheme", &WrappableGURL::scheme) .SetMethod("hasUsername", &WrappableGURL::has_username) .SetMethod("username", &WrappableGURL::username) .SetMethod("hasPassword", &WrappableGURL::has_password) .SetMethod("password", &WrappableGURL::password) .SetMethod("hasHost", &WrappableGURL::has_host) .SetMethod("host", &WrappableGURL::host) .SetMethod("hasPort", &WrappableGURL::has_port) .SetMethod("port", &WrappableGURL::port) .SetMethod("hasPath", &WrappableGURL::has_path) .SetMethod("path", &WrappableGURL::path) .SetMethod("hasQuery", &WrappableGURL::has_query) .SetMethod("query", &WrappableGURL::query) .SetMethod("hasRef", &WrappableGURL::has_ref) .SetMethod("ref", &WrappableGURL::ref) .SetMethod("effectiveIntPort", &WrappableGURL::EffectiveIntPort) .SetMethod("intPort", &WrappableGURL::IntPort) .SetMethod("extractFileName", &WrappableGURL::ExtractFileName) .SetMethod("pathForRequest", &WrappableGURL::PathForRequest) .SetMethod("hostNoBrackets", &WrappableGURL::HostNoBrackets) .SetMethod("domainIs", &WrappableGURL::DomainIs) .SetMethod("innerUrl", &WrappableGURL::inner_url); } static gin::WrapperInfo kWrapperInfo; }; gin::WrapperInfo WrappableGURL::kWrapperInfo = { gin::kEmbedderNativeGin }; } // namespace URLBindings::URLBindings(extensions::ScriptContext* context) : extensions::ObjectBackedNativeHandler(context) { RouteFunction("New", base::Bind(&URLBindings::New, base::Unretained(this))); RouteFunction("FormatForDisplay", base::Bind(&URLBindings::FormatForDisplay, base::Unretained(this))); RouteFunction("Parse", base::Bind(&URLBindings::Parse, base::Unretained(this))); } URLBindings::~URLBindings() { } // static v8::Local<v8::Object> URLBindings::API(extensions::ScriptContext* context) { context->module_system()->RegisterNativeHandler( "muon_url", std::unique_ptr<extensions::NativeHandler>( new URLBindings(context))); v8::Local<v8::Object> url_api = v8::Object::New(context->isolate()); context->module_system()->SetNativeLazyField( url_api, "new", "muon_url", "New"); context->module_system()->SetNativeLazyField( url_api, "formatForDisplay", "muon_url", "FormatForDisplay"); context->module_system()->SetNativeLazyField( url_api, "parse", "muon_url", "Parse"); return url_api; } void URLBindings::New(const v8::FunctionCallbackInfo<v8::Value>& args) { if (args.Length() != 1) { context()->isolate()->ThrowException(v8::String::NewFromUtf8( context()->isolate(), "`url` is a required field")); return; } std::string url_string = *v8::String::Utf8Value(args[0]); gin::Handle<WrappableGURL> gurl = gin::CreateHandle( context()->isolate(), new WrappableGURL(url_string)); args.GetReturnValue().Set( gurl->GetWrapper(context()->isolate()).ToLocalChecked()); } void URLBindings::FormatForDisplay( const v8::FunctionCallbackInfo<v8::Value>& args) { auto isolate = context()->isolate(); if (args.Length() != 1) { isolate->ThrowException(v8::String::NewFromUtf8( isolate, "`url` is a required field")); return; } std::string url_string = *v8::String::Utf8Value(args[0]); base::string16 formatted_url = url_formatter::FormatUrl(GURL(url_string), url_formatter::kFormatUrlOmitUsernamePassword, net::UnescapeRule::SPACES, nullptr, nullptr, nullptr); args.GetReturnValue().Set(gin::ConvertToV8(isolate, formatted_url)); } // returns a mostly node Url.parse compatible object for backwards compat void URLBindings::Parse( const v8::FunctionCallbackInfo<v8::Value>& args) { auto isolate = context()->isolate(); if (args.Length() != 1) { isolate->ThrowException(v8::String::NewFromUtf8( isolate, "`url` is a required field")); return; } std::string url_string = *v8::String::Utf8Value(args[0]); GURL gurl(url_string); gin::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); if (gurl.is_valid()) { if (gurl.has_username()) dict.Set("auth", gurl.username() + (gurl.has_password() ? ":" + gurl.password() : "")); dict.Set("hash", gurl.ref()); dict.Set("hostname", gurl.host()); dict.Set("host", gurl.host() + ":" + gurl.port()); dict.Set("href", gurl.possibly_invalid_spec()); dict.Set("path", gurl.PathForRequest()); dict.Set("pathname", gurl.path()); dict.Set("port", gurl.port()); dict.Set("protocol", gurl.scheme()); dict.Set("query", gurl.query()); dict.Set("search", "?" + gurl.query()); dict.Set("origin", gurl.GetOrigin()); } args.GetReturnValue().Set(gin::ConvertToV8(isolate, dict)); } } // namespace brave
// Copyright (c) 2017 The Brave 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 <memory> #include <string> #include "brave/common/extensions/url_bindings.h" #include "brave/common/converters/gurl_converter.h" #include "brave/common/converters/string16_converter.h" #include "components/url_formatter/url_formatter.h" #include "extensions/renderer/script_context.h" #include "gin/arguments.h" #include "gin/converter.h" #include "gin/dictionary.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "url/gurl.h" #include "v8/include/v8.h" namespace brave { namespace { class WrappableGURL : public GURL, public gin::Wrappable<WrappableGURL> { public: explicit WrappableGURL(const GURL& other) : GURL(other) {} explicit WrappableGURL(base::StringPiece url_string) : GURL(url_string) {} explicit WrappableGURL(base::StringPiece16 url_string) : GURL(url_string) {} bool is_valid() const { return GURL::is_valid(); } bool is_empty() const { return GURL::is_empty(); } const std::string& spec() const { return GURL::spec(); } const std::string& possibly_invalid_spec() const { return GURL::possibly_invalid_spec(); } WrappableGURL* GetWithEmptyPath() const { return new WrappableGURL(GURL::GetWithEmptyPath()); } WrappableGURL* GetOrigin() const { return new WrappableGURL(GURL::GetOrigin()); } WrappableGURL* GetAsReferrer() const { return new WrappableGURL(GURL::GetAsReferrer()); } bool IsStandard() const { return GURL::IsStandard(); } bool SchemeIsHTTPOrHTTPS() const { return GURL::SchemeIsHTTPOrHTTPS(); } bool SchemeIsValidForReferrer() const { return GURL::SchemeIsValidForReferrer(); } bool SchemeIsWSOrWSS() const { return GURL::SchemeIsWSOrWSS(); } bool SchemeIsFile() const { return GURL::SchemeIsFile(); } bool SchemeIsFileSystem() const { return GURL::SchemeIsFileSystem(); } bool SchemeIsCryptographic() const { return GURL::SchemeIsCryptographic(); } bool SchemeIsBlob() const { return GURL::SchemeIsBlob(); } bool SchemeIsSuborigin() const { return GURL::SchemeIsSuborigin(); } std::string GetContent() const { return GURL::GetContent(); } bool HostIsIPAddress() const { return GURL::HostIsIPAddress(); } bool has_scheme() const { return GURL::has_scheme(); } std::string scheme() const { return GURL::scheme(); } bool has_host() const { return GURL::has_host(); } std::string host() const { return GURL::host(); } bool has_username() const { return GURL::has_username(); } std::string username() const { return GURL::username(); } bool has_password() const { return GURL::has_password(); } std::string password() const { return GURL::password(); } bool has_port() const { return GURL::has_port(); } std::string port() const { return GURL::port(); } bool has_path() const { return GURL::has_path(); } std::string path() const { return GURL::path(); } bool has_query() const { return GURL::has_query(); } std::string query() const { return GURL::query(); } bool has_ref() const { return GURL::has_ref(); } std::string ref() const { return GURL::ref(); } int EffectiveIntPort() const { return GURL::EffectiveIntPort(); } int IntPort() const { return GURL::IntPort(); } std::string ExtractFileName() const { return GURL::ExtractFileName(); } std::string PathForRequest() const { return GURL::PathForRequest(); } std::string HostNoBrackets() const { return GURL::HostNoBrackets(); } WrappableGURL* inner_url() const { return new WrappableGURL(*GURL::inner_url()); } bool DomainIs(std::string lower_ascii_domain) const { return GURL::DomainIs(lower_ascii_domain); } WrappableGURL* Resolve(const std::string& relative) const { return new WrappableGURL(GURL::Resolve(relative)); } gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override { return gin::Wrappable<WrappableGURL>::GetObjectTemplateBuilder(isolate) .SetMethod("isValid", &WrappableGURL::is_valid) .SetMethod("isEmpty", &WrappableGURL::is_empty) .SetMethod("spec", &WrappableGURL::spec) .SetMethod("possiblyInvalidSpec", &WrappableGURL::possibly_invalid_spec) .SetMethod("resolve", &WrappableGURL::Resolve) .SetMethod("getWithEmptyPath", &WrappableGURL::GetWithEmptyPath) .SetMethod("getOrigin", &WrappableGURL::GetOrigin) .SetMethod("getAsReferrer", &WrappableGURL::GetAsReferrer) .SetMethod("isStandard", &WrappableGURL::IsStandard) .SetMethod("schemeIsHTTPOrHTTPS", &WrappableGURL::SchemeIsHTTPOrHTTPS) .SetMethod("schemeIsValidForReferrer", &WrappableGURL::SchemeIsValidForReferrer) .SetMethod("schemeIsWSOrWSS", &WrappableGURL::SchemeIsWSOrWSS) .SetMethod("schemeIsFile", &WrappableGURL::SchemeIsFile) .SetMethod("schemeIsFileSystem", &WrappableGURL::SchemeIsFileSystem) .SetMethod("schemeIsCryptographic", &WrappableGURL::SchemeIsCryptographic) .SetMethod("schemeIsBlob", &WrappableGURL::SchemeIsBlob) .SetMethod("schemeIsSuborigin", &WrappableGURL::SchemeIsSuborigin) .SetMethod("getContent", &WrappableGURL::GetContent) .SetMethod("hostIsIPAddress", &WrappableGURL::HostIsIPAddress) .SetMethod("hasScheme", &WrappableGURL::has_scheme) .SetMethod("scheme", &WrappableGURL::scheme) .SetMethod("hasUsername", &WrappableGURL::has_username) .SetMethod("username", &WrappableGURL::username) .SetMethod("hasPassword", &WrappableGURL::has_password) .SetMethod("password", &WrappableGURL::password) .SetMethod("hasHost", &WrappableGURL::has_host) .SetMethod("host", &WrappableGURL::host) .SetMethod("hasPort", &WrappableGURL::has_port) .SetMethod("port", &WrappableGURL::port) .SetMethod("hasPath", &WrappableGURL::has_path) .SetMethod("path", &WrappableGURL::path) .SetMethod("hasQuery", &WrappableGURL::has_query) .SetMethod("query", &WrappableGURL::query) .SetMethod("hasRef", &WrappableGURL::has_ref) .SetMethod("ref", &WrappableGURL::ref) .SetMethod("effectiveIntPort", &WrappableGURL::EffectiveIntPort) .SetMethod("intPort", &WrappableGURL::IntPort) .SetMethod("extractFileName", &WrappableGURL::ExtractFileName) .SetMethod("pathForRequest", &WrappableGURL::PathForRequest) .SetMethod("hostNoBrackets", &WrappableGURL::HostNoBrackets) .SetMethod("domainIs", &WrappableGURL::DomainIs) .SetMethod("innerUrl", &WrappableGURL::inner_url); } static gin::WrapperInfo kWrapperInfo; }; gin::WrapperInfo WrappableGURL::kWrapperInfo = { gin::kEmbedderNativeGin }; } // namespace URLBindings::URLBindings(extensions::ScriptContext* context) : extensions::ObjectBackedNativeHandler(context) { RouteFunction("New", base::Bind(&URLBindings::New, base::Unretained(this))); RouteFunction("FormatForDisplay", base::Bind(&URLBindings::FormatForDisplay, base::Unretained(this))); RouteFunction("Parse", base::Bind(&URLBindings::Parse, base::Unretained(this))); } URLBindings::~URLBindings() { } // static v8::Local<v8::Object> URLBindings::API(extensions::ScriptContext* context) { context->module_system()->RegisterNativeHandler( "muon_url", std::unique_ptr<extensions::NativeHandler>( new URLBindings(context))); v8::Local<v8::Object> url_api = v8::Object::New(context->isolate()); context->module_system()->SetNativeLazyField( url_api, "new", "muon_url", "New"); context->module_system()->SetNativeLazyField( url_api, "formatForDisplay", "muon_url", "FormatForDisplay"); context->module_system()->SetNativeLazyField( url_api, "parse", "muon_url", "Parse"); return url_api; } void URLBindings::New(const v8::FunctionCallbackInfo<v8::Value>& args) { if (args.Length() != 1) { context()->isolate()->ThrowException(v8::String::NewFromUtf8( context()->isolate(), "`url` is a required field")); return; } std::string url_string = *v8::String::Utf8Value(args[0]); gin::Handle<WrappableGURL> gurl = gin::CreateHandle( context()->isolate(), new WrappableGURL(url_string)); args.GetReturnValue().Set( gurl->GetWrapper(context()->isolate()).ToLocalChecked()); } void URLBindings::FormatForDisplay( const v8::FunctionCallbackInfo<v8::Value>& args) { auto isolate = context()->isolate(); if (args.Length() != 1) { isolate->ThrowException(v8::String::NewFromUtf8( isolate, "`url` is a required field")); return; } std::string url_string = *v8::String::Utf8Value(args[0]); base::string16 formatted_url = url_formatter::FormatUrl(GURL(url_string), url_formatter::kFormatUrlOmitUsernamePassword, net::UnescapeRule::SPACES, nullptr, nullptr, nullptr); args.GetReturnValue().Set(gin::ConvertToV8(isolate, formatted_url)); } // returns a mostly node Url.parse compatible object for backwards compat void URLBindings::Parse( const v8::FunctionCallbackInfo<v8::Value>& args) { auto isolate = context()->isolate(); if (args.Length() != 1) { isolate->ThrowException(v8::String::NewFromUtf8( isolate, "`url` is a required field")); return; } std::string url_string = *v8::String::Utf8Value(args[0]); GURL gurl(url_string); gin::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); if (gurl.is_valid()) { if (gurl.has_username()) dict.Set("auth", gurl.username() + (gurl.has_password() ? ":" + gurl.password() : "")); dict.Set("hash", (gurl.has_ref() ? "#" : "") + gurl.ref()); dict.Set("hostname", gurl.host()); dict.Set("host", gurl.host() + (gurl.has_port() ? ":" + gurl.port() : "")); dict.Set("href", gurl.possibly_invalid_spec()); dict.Set("path", gurl.PathForRequest()); dict.Set("pathname", gurl.path()); dict.Set("port", gurl.port()); dict.Set("protocol", gurl.scheme() + (gurl.has_scheme() ? ":" : "")); dict.Set("query", gurl.query()); dict.Set("search", "?" + gurl.query()); dict.Set("origin", gurl.GetOrigin()); } args.GetReturnValue().Set(gin::ConvertToV8(isolate, dict)); } } // namespace brave
Make muon.url.parse work more like Node's
Make muon.url.parse work more like Node's Fix https://github.com/brave/browser-laptop/issues/9503
C++
mit
brave/muon,brave/muon,brave/electron,brave/muon,brave/muon,brave/muon,brave/electron,brave/muon,brave/electron,brave/electron,brave/electron,brave/electron
5f9ce18a845fa5d5daf17d3714a30058e07bb9fe
src/platform/LinuxMedia.cxx
src/platform/LinuxMedia.cxx
/* bzflag * Copyright (c) 1993-2013 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "LinuxMedia.h" #include <math.h> #include <fcntl.h> #ifdef BSD #include <machine/endian.h> #else #include <endian.h> #endif #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include "bzsignal.h" #include <sys/soundcard.h> #include <sys/ioctl.h> #include <TimeKeeper.h> #include <errno.h> #include <string.h> #ifdef HALF_RATE_AUDIO static const int defaultAudioRate=11025; #else static const int defaultAudioRate=22050; #endif // // LinuxMedia // LinuxMedia::LinuxMedia() : BzfMedia(), audioReady(false), audioBufferSize(defaultAudioRate), audioPortFd(-1), queueIn(-1), queueOut(-1), outputBuffer(NULL), childProcID(0), audio8Bit(false), getospaceBroken(false) { // do nothing } LinuxMedia::~LinuxMedia() { // do nothing } double LinuxMedia::getTime() { struct timeval tv; gettimeofday(&tv, 0); return (double)tv.tv_sec + 1.0e-6 * (double)tv.tv_usec; } double LinuxMedia::stopwatch(bool start) { if (start) { stopwatchTime = getTime(); return 0.0; } return getTime() - stopwatchTime; } bool LinuxMedia::openAudio() { // don't re-initialize if (audioReady) return false; // check for and open audio hardware if (!checkForAudioHardware() || !openAudioHardware()) return false; // open communication channel (FIFO pipe). close on exec. int fd[2]; if (pipe(fd)<0) { closeAudio(); return false; } queueIn = fd[1]; queueOut = fd[0]; fcntl(queueIn, F_SETFL, fcntl(queueIn, F_GETFL, 0) | O_NDELAY); fcntl(queueOut, F_SETFL, fcntl(queueOut, F_GETFL, 0) | O_NDELAY); fcntl(queueIn, F_SETFD, fcntl(queueIn, F_GETFD, 0) | FD_CLOEXEC); fcntl(queueOut, F_SETFD, fcntl(queueOut, F_GETFD, 0) | FD_CLOEXEC); // compute maxFd for use in select() call maxFd = queueOut; if (maxFd<audioPortFd) maxFd = audioPortFd; maxFd++; // make an output buffer outputBuffer = new short[audioBufferSize]; // Set default no thread childProcID=0; // ready to go audioReady = true; return true; } bool LinuxMedia::checkForAudioHardware() { bool flag=false; if (!access("/dev/dsp", W_OK)) flag=true; if (!access("/dev/sound/dsp", W_OK)) flag=true; return flag; } bool LinuxMedia::openIoctl( int cmd, void* value, bool req) { if (audioPortFd == -1) return false; if (ioctl(audioPortFd, cmd, value) < 0) { fprintf(stderr, "audio ioctl failed (cmd %x, err %d)... ", cmd, errno); if (req) { close(audioPortFd); audioPortFd = -1; fprintf(stderr, "giving up on audio\n"); } else { fprintf(stderr, "ignored\n"); } return false; } return true; } static const int NumChunks = 4; bool LinuxMedia::openAudioHardware() { int format, n; // what's the audio format? #if BYTE_ORDER == BIG_ENDIAN format = AFMT_S16_BE; #else format = AFMT_S16_LE; #endif // what the frequency? audioOutputRate = defaultAudioRate; // how big a fragment to use? we want to hold at around 1/10th of // a second. int fragmentSize = (int)(0.08f * (float)audioOutputRate); n = 0; while ((1 << n) < fragmentSize) ++n; // samples are two bytes each and we're in stereo so quadruple the size fragmentSize = n + 2; // now how many fragments and what's the low water mark (in fragments)? int fragmentInfo = (NumChunks << 16) | fragmentSize; audioLowWaterMark = 2; // open device (but don't wait for it) audioPortFd = open("/dev/dsp", O_WRONLY | O_NDELAY, 0); if (audioPortFd == -1) { audioPortFd = open("/dev/sound/dsp", O_WRONLY | O_NDELAY, 0); if (audioPortFd == -1) { fprintf(stderr, "Failed to open audio device /dev/dsp or /dev/sound/dsp (%d)\n", errno); return false; } } // back to blocking I/O fcntl(audioPortFd, F_SETFL, fcntl(audioPortFd, F_GETFL, 0) & ~O_NDELAY); /* close audio on exec so launched server doesn't hold sound device */ fcntl(audioPortFd, F_SETFD, fcntl(audioPortFd, F_GETFD) | FD_CLOEXEC); // initialize device openIoctl(SNDCTL_DSP_RESET, 0); n = fragmentInfo; noSetFragment = false; if (!openIoctl((int)SNDCTL_DSP_SETFRAGMENT, &n, false)) { // this is not good. we can't set the size of the fragment // buffers. we'd like something short to minimize latencies // and the default is probably too long. we've got two // options here: accept the latency or try to force the // driver to play partial fragments. we'll try the later // unless BZF_AUDIO_NOPOST is in the environment if (!getenv("BZF_AUDIO_NOPOST")) noSetFragment = true; } n = format; openIoctl((int)SNDCTL_DSP_SETFMT, &n, false); if (n != format) { audio8Bit = true; n = AFMT_U8; openIoctl((int)SNDCTL_DSP_SETFMT, &n); } n = 1; openIoctl((int)SNDCTL_DSP_STEREO, &n); n = defaultAudioRate; openIoctl((int)SNDCTL_DSP_SPEED, &n); // set audioBufferSize, which is the number of samples (not bytes) // in each fragment. there are two bytes per sample so divide the // fragment size by two unless we're in audio8Bit mode. also, if // we couldn't set the fragment size then force the buffer size to // the size we would've asked for. we'll force the buffer to be // flushed after we write that much data to keep latency low. if (noSetFragment || !openIoctl((int)SNDCTL_DSP_GETBLKSIZE, &audioBufferSize, false) || audioBufferSize > (1 << fragmentSize)) { audioBufferSize = 1 << fragmentSize; noSetFragment = true; } if (!audio8Bit) audioBufferSize >>= 1; // SNDCTL_DSP_GETOSPACE not supported on all platforms. check if // it fails here and, if so, do a workaround by using the wall // clock. *shudder* if (audioPortFd != -1) { audio_buf_info info; if (!openIoctl((int)SNDCTL_DSP_GETOSPACE, &info, false)) { getospaceBroken = true; chunksPending = 0; chunksPerSecond = (double)getAudioOutputRate() / (double)getAudioBufferChunkSize(); } } return (audioPortFd != -1); } void LinuxMedia::closeAudio() { delete [] outputBuffer; if (audioPortFd>=0) close(audioPortFd); if (queueIn!=-1) close(queueIn); if (queueOut!=-1) close(queueOut); audioReady=false; audioPortFd=-1; queueIn=-1; queueOut=-1; outputBuffer=0; } bool LinuxMedia::startAudioThread( void (*proc)(void*), void* data) { // if no audio thread then just call proc and return if (!hasAudioThread()) { proc(data); return true; } // has an audio thread so fork and call proc if (childProcID) return true; if ((childProcID=fork()) > 0) { close(queueOut); close(audioPortFd); return true; } else if (childProcID < 0) { return false; } close(queueIn); proc(data); exit(0); } void LinuxMedia::stopAudioThread() { if (childProcID != 0) kill(childProcID, SIGTERM); childProcID=0; } bool LinuxMedia::hasAudioThread() const { #if defined(NO_AUDIO_THREAD) return false; #else return true; #endif } void LinuxMedia::audioThreadInit(void*) { } void LinuxMedia::writeSoundCommand(const void* cmd, int len) { if (!audioReady) return; write(queueIn, cmd, len); } bool LinuxMedia::readSoundCommand(void* cmd, int len) { return (read(queueOut, cmd, len)==len); } int LinuxMedia::getAudioOutputRate() const { return audioOutputRate; } int LinuxMedia::getAudioBufferSize() const { return NumChunks*(audioBufferSize>>1); } int LinuxMedia::getAudioBufferChunkSize() const { return audioBufferSize>>1; } bool LinuxMedia::isAudioTooEmpty() const { if (getospaceBroken) { if (chunksPending > 0) { // get time elapsed since chunkTime const double dt = getTime() - chunkTime; // how many chunks could've played in the elapsed time? const int numChunks = (int)(dt * chunksPerSecond); // remove pending chunks LinuxMedia* self = (LinuxMedia*)this; self->chunksPending -= numChunks; if (chunksPending < 0) self->chunksPending = 0; else self->chunkTime += (double)numChunks / chunksPerSecond; } return chunksPending < audioLowWaterMark; } else { audio_buf_info info; if (ioctl(audioPortFd, SNDCTL_DSP_GETOSPACE, &info) < 0) return false; return info.fragments > info.fragstotal - audioLowWaterMark; } } void LinuxMedia::writeAudioFrames8Bit( const float* samples, int numFrames) { int numSamples = 2 * numFrames; int limit; char *smOutputBuffer; smOutputBuffer=(char*)outputBuffer; while (numSamples > 0) { if (numSamples>audioBufferSize) limit=audioBufferSize; else limit=numSamples; for (int j = 0; j < limit; j++) { if (samples[j] <= -32767.0) smOutputBuffer[j] = 0; else if (samples[j] >= 32767.0) smOutputBuffer[j] = (char)255; else smOutputBuffer[j] = char((samples[j]+32767)/257); } // fill out the chunk (we never write a partial chunk) if (limit < audioBufferSize) { for (int j = limit; j < audioBufferSize; ++j) smOutputBuffer[j] = 127; limit = audioBufferSize; } write(audioPortFd, smOutputBuffer, limit); samples += limit; numSamples -= limit; } } void LinuxMedia::writeAudioFrames16Bit( const float* samples, int numFrames) { int numSamples = 2 * numFrames; int limit = 0; while (numSamples > 0) { if (numSamples>audioBufferSize) limit=audioBufferSize; else limit=numSamples; for (int j = 0; j < limit; j++) { if (samples[j] < -32767.0) outputBuffer[j] = -32767; else if (samples[j] > 32767.0) outputBuffer[j] = 32767; else outputBuffer[j] = short(samples[j]); } // fill out the chunk (we never write a partial chunk) if (limit < audioBufferSize) { for (int j = limit; j < audioBufferSize; ++j) outputBuffer[j] = 0; limit = audioBufferSize; } write(audioPortFd, outputBuffer, 2*limit); samples += limit; numSamples -= limit; } } void LinuxMedia::writeAudioFrames( const float* samples, int numFrames) { if (audio8Bit) writeAudioFrames8Bit(samples, numFrames); else writeAudioFrames16Bit(samples, numFrames); // if we couldn't set the fragment size then force the driver // to play the short buffer. if (noSetFragment) { int dummy = 0; ioctl(audioPortFd, SNDCTL_DSP_POST, &dummy); } if (getospaceBroken) { if (chunksPending == 0) chunkTime = getTime(); chunksPending += (numFrames + getAudioBufferChunkSize() - 1) / getAudioBufferChunkSize(); } } void LinuxMedia::audioSleep( bool checkLowWater, double endTime) { fd_set commandSelectSet; struct timeval tv; // To do both these operations at once, we need to poll. if (checkLowWater) { // start looping TimeKeeper start = TimeKeeper::getCurrent(); do { // break if buffer has drained enough if (isAudioTooEmpty()) break; FD_ZERO(&commandSelectSet); FD_SET((unsigned int)queueOut, &commandSelectSet); tv.tv_sec=0; tv.tv_usec=50000; if (select(maxFd, &commandSelectSet, 0, 0, &tv)) break; } while (endTime<0.0 || (TimeKeeper::getCurrent()-start)<endTime); } else { FD_ZERO(&commandSelectSet); FD_SET((unsigned int)queueOut, &commandSelectSet); tv.tv_sec=int(endTime); tv.tv_usec=int(1.0e6*(endTime-floor(endTime))); select(maxFd, &commandSelectSet, 0, 0, (endTime>=0.0)?&tv : 0); } } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8
/* bzflag * Copyright (c) 1993-2013 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "LinuxMedia.h" #include <math.h> #include <fcntl.h> #ifdef BSD #include <machine/endian.h> #else #include <endian.h> #endif #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include "bzsignal.h" #include <sys/soundcard.h> #include <sys/ioctl.h> #include <TimeKeeper.h> #include <errno.h> #include <string.h> #ifdef HALF_RATE_AUDIO static const int defaultAudioRate=11025; #else static const int defaultAudioRate=22050; #endif // // LinuxMedia // LinuxMedia::LinuxMedia() : BzfMedia(), audioReady(false), audioBufferSize(defaultAudioRate), audioPortFd(-1), queueIn(-1), queueOut(-1), outputBuffer(NULL), childProcID(0), audio8Bit(false), getospaceBroken(false) { // do nothing } LinuxMedia::~LinuxMedia() { // do nothing } double LinuxMedia::getTime() { struct timeval tv; gettimeofday(&tv, 0); return (double)tv.tv_sec + 1.0e-6 * (double)tv.tv_usec; } double LinuxMedia::stopwatch(bool start) { if (start) { stopwatchTime = getTime(); return 0.0; } return getTime() - stopwatchTime; } bool LinuxMedia::openAudio() { // don't re-initialize if (audioReady) return false; // check for and open audio hardware if (!checkForAudioHardware() || !openAudioHardware()) return false; // open communication channel (FIFO pipe). close on exec. int fd[2]; if (pipe(fd)<0) { closeAudio(); return false; } queueIn = fd[1]; queueOut = fd[0]; fcntl(queueIn, F_SETFL, fcntl(queueIn, F_GETFL, 0) | O_NDELAY); fcntl(queueOut, F_SETFL, fcntl(queueOut, F_GETFL, 0) | O_NDELAY); fcntl(queueIn, F_SETFD, fcntl(queueIn, F_GETFD, 0) | FD_CLOEXEC); fcntl(queueOut, F_SETFD, fcntl(queueOut, F_GETFD, 0) | FD_CLOEXEC); // compute maxFd for use in select() call maxFd = queueOut; if (maxFd<audioPortFd) maxFd = audioPortFd; maxFd++; // make an output buffer outputBuffer = new short[audioBufferSize]; // Set default no thread childProcID=0; // ready to go audioReady = true; return true; } bool LinuxMedia::checkForAudioHardware() { bool flag=false; if (!access("/dev/dsp", W_OK)) flag=true; if (!access("/dev/sound/dsp", W_OK)) flag=true; return flag; } bool LinuxMedia::openIoctl( int cmd, void* value, bool req) { if (audioPortFd == -1) return false; if (ioctl(audioPortFd, cmd, value) < 0) { fprintf(stderr, "audio ioctl failed (cmd %x, err %d)... ", cmd, errno); if (req) { close(audioPortFd); audioPortFd = -1; fprintf(stderr, "giving up on audio\n"); } else { fprintf(stderr, "ignored\n"); } return false; } return true; } static const int NumChunks = 4; bool LinuxMedia::openAudioHardware() { int format, n; // what's the audio format? #if BYTE_ORDER == BIG_ENDIAN format = AFMT_S16_BE; #else format = AFMT_S16_LE; #endif // what the frequency? audioOutputRate = defaultAudioRate; // how big a fragment to use? we want to hold at around 1/10th of // a second. int fragmentSize = (int)(0.08f * (float)audioOutputRate); n = 0; while ((1 << n) < fragmentSize) ++n; // samples are two bytes each and we're in stereo so quadruple the size fragmentSize = n + 2; // now how many fragments and what's the low water mark (in fragments)? int fragmentInfo = (NumChunks << 16) | fragmentSize; audioLowWaterMark = 2; // open device (but don't wait for it) audioPortFd = open("/dev/dsp", O_WRONLY | O_NDELAY, 0); if (audioPortFd == -1) { audioPortFd = open("/dev/sound/dsp", O_WRONLY | O_NDELAY, 0); if (audioPortFd == -1) { fprintf(stderr, "Failed to open audio device /dev/dsp or /dev/sound/dsp (%d)\n", errno); return false; } } // back to blocking I/O fcntl(audioPortFd, F_SETFL, fcntl(audioPortFd, F_GETFL, 0) & ~O_NDELAY); /* close audio on exec so launched server doesn't hold sound device */ fcntl(audioPortFd, F_SETFD, fcntl(audioPortFd, F_GETFD) | FD_CLOEXEC); // initialize device openIoctl(SNDCTL_DSP_RESET, 0); n = fragmentInfo; noSetFragment = false; if (!openIoctl((int)SNDCTL_DSP_SETFRAGMENT, &n, false)) { // this is not good. we can't set the size of the fragment // buffers. we'd like something short to minimize latencies // and the default is probably too long. we've got two // options here: accept the latency or try to force the // driver to play partial fragments. we'll try the later // unless BZF_AUDIO_NOPOST is in the environment if (!getenv("BZF_AUDIO_NOPOST")) noSetFragment = true; } n = format; openIoctl((int)SNDCTL_DSP_SETFMT, &n, false); if (n != format) { audio8Bit = true; n = AFMT_U8; openIoctl((int)SNDCTL_DSP_SETFMT, &n); } n = 1; openIoctl((int)SNDCTL_DSP_STEREO, &n); n = defaultAudioRate; openIoctl((int)SNDCTL_DSP_SPEED, &n); // set audioBufferSize, which is the number of samples (not bytes) // in each fragment. there are two bytes per sample so divide the // fragment size by two unless we're in audio8Bit mode. also, if // we couldn't set the fragment size then force the buffer size to // the size we would've asked for. we'll force the buffer to be // flushed after we write that much data to keep latency low. if (noSetFragment || !openIoctl((int)SNDCTL_DSP_GETBLKSIZE, &audioBufferSize, false) || audioBufferSize > (1 << fragmentSize)) { audioBufferSize = 1 << fragmentSize; noSetFragment = true; } if (!audio8Bit) audioBufferSize >>= 1; // SNDCTL_DSP_GETOSPACE not supported on all platforms. check if // it fails here and, if so, do a workaround by using the wall // clock. *shudder* if (audioPortFd != -1) { audio_buf_info info; if (!openIoctl((int)SNDCTL_DSP_GETOSPACE, &info, false)) { getospaceBroken = true; chunksPending = 0; chunksPerSecond = (double)getAudioOutputRate() / (double)getAudioBufferChunkSize(); } } return (audioPortFd != -1); } void LinuxMedia::closeAudio() { delete [] outputBuffer; if (audioPortFd>=0) close(audioPortFd); if (queueIn!=-1) close(queueIn); if (queueOut!=-1) close(queueOut); audioReady=false; audioPortFd=-1; queueIn=-1; queueOut=-1; outputBuffer=0; } bool LinuxMedia::startAudioThread( void (*proc)(void*), void* data) { // if no audio thread then just call proc and return if (!hasAudioThread()) { proc(data); return true; } // has an audio thread so fork and call proc if (childProcID) return true; if ((childProcID=fork()) > 0) { close(queueOut); close(audioPortFd); return true; } else if (childProcID < 0) { return false; } close(queueIn); proc(data); exit(0); } void LinuxMedia::stopAudioThread() { if (childProcID != 0) kill(childProcID, SIGTERM); childProcID=0; } bool LinuxMedia::hasAudioThread() const { #if defined(NO_AUDIO_THREAD) return false; #else return true; #endif } void LinuxMedia::audioThreadInit(void*) { } void LinuxMedia::writeSoundCommand(const void* cmd, int len) { if (!audioReady) return; write(queueIn, cmd, len); } bool LinuxMedia::readSoundCommand(void* cmd, int len) { return (read(queueOut, cmd, len)==len); } int LinuxMedia::getAudioOutputRate() const { return audioOutputRate; } int LinuxMedia::getAudioBufferSize() const { return NumChunks*(audioBufferSize>>1); } int LinuxMedia::getAudioBufferChunkSize() const { return audioBufferSize>>1; } bool LinuxMedia::isAudioTooEmpty() const { if (getospaceBroken) { LinuxMedia* self = const_cast<LinuxMedia*>(this); if (self->chunksPending > 0) { // get time elapsed since chunkTime const double dt = getTime() - chunkTime; // how many chunks could've played in the elapsed time? const int numChunks = (int)(dt * chunksPerSecond); // remove pending chunks self->chunksPending -= numChunks; if (self->chunksPending < 0) self->chunksPending = 0; else self->chunkTime += (double)numChunks / chunksPerSecond; } return self->chunksPending < audioLowWaterMark; } else { audio_buf_info info; if (ioctl(audioPortFd, SNDCTL_DSP_GETOSPACE, &info) < 0) return false; return info.fragments > info.fragstotal - audioLowWaterMark; } } void LinuxMedia::writeAudioFrames8Bit( const float* samples, int numFrames) { int numSamples = 2 * numFrames; int limit; char *smOutputBuffer; smOutputBuffer=(char*)outputBuffer; while (numSamples > 0) { if (numSamples>audioBufferSize) limit=audioBufferSize; else limit=numSamples; for (int j = 0; j < limit; j++) { if (samples[j] <= -32767.0) smOutputBuffer[j] = 0; else if (samples[j] >= 32767.0) smOutputBuffer[j] = (char)255; else smOutputBuffer[j] = char((samples[j]+32767)/257); } // fill out the chunk (we never write a partial chunk) if (limit < audioBufferSize) { for (int j = limit; j < audioBufferSize; ++j) smOutputBuffer[j] = 127; limit = audioBufferSize; } write(audioPortFd, smOutputBuffer, limit); samples += limit; numSamples -= limit; } } void LinuxMedia::writeAudioFrames16Bit( const float* samples, int numFrames) { int numSamples = 2 * numFrames; int limit = 0; while (numSamples > 0) { if (numSamples>audioBufferSize) limit=audioBufferSize; else limit=numSamples; for (int j = 0; j < limit; j++) { if (samples[j] < -32767.0) outputBuffer[j] = -32767; else if (samples[j] > 32767.0) outputBuffer[j] = 32767; else outputBuffer[j] = short(samples[j]); } // fill out the chunk (we never write a partial chunk) if (limit < audioBufferSize) { for (int j = limit; j < audioBufferSize; ++j) outputBuffer[j] = 0; limit = audioBufferSize; } write(audioPortFd, outputBuffer, 2*limit); samples += limit; numSamples -= limit; } } void LinuxMedia::writeAudioFrames( const float* samples, int numFrames) { if (audio8Bit) writeAudioFrames8Bit(samples, numFrames); else writeAudioFrames16Bit(samples, numFrames); // if we couldn't set the fragment size then force the driver // to play the short buffer. if (noSetFragment) { int dummy = 0; ioctl(audioPortFd, SNDCTL_DSP_POST, &dummy); } if (getospaceBroken) { if (chunksPending == 0) chunkTime = getTime(); chunksPending += (numFrames + getAudioBufferChunkSize() - 1) / getAudioBufferChunkSize(); } } void LinuxMedia::audioSleep( bool checkLowWater, double endTime) { fd_set commandSelectSet; struct timeval tv; // To do both these operations at once, we need to poll. if (checkLowWater) { // start looping TimeKeeper start = TimeKeeper::getCurrent(); do { // break if buffer has drained enough if (isAudioTooEmpty()) break; FD_ZERO(&commandSelectSet); FD_SET((unsigned int)queueOut, &commandSelectSet); tv.tv_sec=0; tv.tv_usec=50000; if (select(maxFd, &commandSelectSet, 0, 0, &tv)) break; } while (endTime<0.0 || (TimeKeeper::getCurrent()-start)<endTime); } else { FD_ZERO(&commandSelectSet); FD_SET((unsigned int)queueOut, &commandSelectSet); tv.tv_sec=int(endTime); tv.tv_usec=int(1.0e6*(endTime-floor(endTime))); select(maxFd, &commandSelectSet, 0, 0, (endTime>=0.0)?&tv : 0); } } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8
Use const_cast<> to suppress a const qualifier warning. Avoid potential optimization trouble by accessing only the non-const view of the object.
Use const_cast<> to suppress a const qualifier warning. Avoid potential optimization trouble by accessing only the non-const view of the object.
C++
lgpl-2.1
adamsdadakaeti/bzflag,khonkhortisan/bzflag,khonkhortisan/bzflag,kongr45gpen/bzflag,khonkhortisan/bzflag,kongr45gpen/bzflag,adamsdadakaeti/bzflag,kongr45gpen/bzflag,adamsdadakaeti/bzflag,kongr45gpen/bzflag,adamsdadakaeti/bzflag,khonkhortisan/bzflag,adamsdadakaeti/bzflag,khonkhortisan/bzflag,adamsdadakaeti/bzflag,kongr45gpen/bzflag,adamsdadakaeti/bzflag,kongr45gpen/bzflag,khonkhortisan/bzflag,khonkhortisan/bzflag,kongr45gpen/bzflag,kongr45gpen/bzflag
5c8022ed26152c935a751132ad60a8242a922714
src/gpu/gl/mesa/GrGLCreateMesaInterface.cpp
src/gpu/gl/mesa/GrGLCreateMesaInterface.cpp
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gl/GrGLInterface.h" #include "../GrGLUtil.h" #define GL_GLEXT_PROTOTYPES #include <GL/osmesa.h> #define GR_GL_GET_PROC(F) interface->f ## F = (GrGL ## F ## Proc) \ OSMesaGetProcAddress("gl" #F); #define GR_GL_GET_PROC_SUFFIX(F, S) interface->f ## F = (GrGL ## F ## Proc) \ OSMesaGetProcAddress("gl" #F #S); // We use OSMesaGetProcAddress for every gl function to avoid accidentally using // non-Mesa gl functions. const GrGLInterface* GrGLCreateMesaInterface() { if (NULL != OSMesaGetCurrentContext()) { GrGLGetStringProc getString = (GrGLGetStringProc) OSMesaGetProcAddress("glGetString"); const char* versionString = (const char*) getString(GL_VERSION); const char* extString = (const char*) getString(GL_EXTENSIONS); GrGLVersion glVer = GrGLGetVersionFromString(versionString); if (glVer < GR_GL_VER(1,5)) { // We must have array and element_array buffer objects. return NULL; } GrGLInterface* interface = new GrGLInterface(); GR_GL_GET_PROC(ActiveTexture); GR_GL_GET_PROC(BeginQuery); GR_GL_GET_PROC(AttachShader); GR_GL_GET_PROC(BindAttribLocation); GR_GL_GET_PROC(BindBuffer); GR_GL_GET_PROC(BindFragDataLocation); GR_GL_GET_PROC(BindTexture); GR_GL_GET_PROC(BlendFunc); if (glVer >= GR_GL_VER(1,4) || GrGLHasExtensionFromString("GL_ARB_imaging", extString)) { GR_GL_GET_PROC(BlendColor); GR_GL_GET_PROC(BlendEquation); } else { if (GrGLHasExtensionFromString("GL_EXT_blend_color", extString)) { GR_GL_GET_PROC_SUFFIX(BlendColor, EXT); } if (GrGLHasExtensionFromString("GL_EXT_blend_minmax", extString) || GrGLHasExtensionFromString("GL_EXT_blend_subtract", extString)) { GR_GL_GET_PROC_SUFFIX(BlendEquation, EXT); } } GR_GL_GET_PROC(BufferData); GR_GL_GET_PROC(BufferSubData); GR_GL_GET_PROC(Clear); GR_GL_GET_PROC(ClearColor); GR_GL_GET_PROC(ClearStencil); GR_GL_GET_PROC(ColorMask); GR_GL_GET_PROC(CompileShader); GR_GL_GET_PROC(CompressedTexImage2D); GR_GL_GET_PROC(CreateProgram); GR_GL_GET_PROC(CreateShader); GR_GL_GET_PROC(CullFace); GR_GL_GET_PROC(DeleteBuffers); GR_GL_GET_PROC(DeleteProgram); GR_GL_GET_PROC(DeleteQueries); GR_GL_GET_PROC(DeleteShader); GR_GL_GET_PROC(DeleteTextures); GR_GL_GET_PROC(DepthMask); GR_GL_GET_PROC(Disable); GR_GL_GET_PROC(DisableVertexAttribArray); GR_GL_GET_PROC(DrawArrays); GR_GL_GET_PROC(DrawBuffer); GR_GL_GET_PROC(DrawBuffers); GR_GL_GET_PROC(DrawElements); GR_GL_GET_PROC(Enable); GR_GL_GET_PROC(EnableVertexAttribArray); GR_GL_GET_PROC(EndQuery); GR_GL_GET_PROC(Finish); GR_GL_GET_PROC(Flush); GR_GL_GET_PROC(FrontFace); GR_GL_GET_PROC(GenBuffers); GR_GL_GET_PROC(GenQueries); GR_GL_GET_PROC(GetBufferParameteriv); GR_GL_GET_PROC(GetError); GR_GL_GET_PROC(GetIntegerv); GR_GL_GET_PROC(GetProgramInfoLog); GR_GL_GET_PROC(GetProgramiv); if (glVer >= GR_GL_VER(3,3) || GrGLHasExtensionFromString("GL_ARB_timer_query", extString)) { GR_GL_GET_PROC(GetQueryObjecti64v); GR_GL_GET_PROC(GetQueryObjectui64v) GR_GL_GET_PROC(QueryCounter); } else if (GrGLHasExtensionFromString("GL_EXT_timer_query", extString)) { GR_GL_GET_PROC_SUFFIX(GetQueryObjecti64v, EXT); GR_GL_GET_PROC_SUFFIX(GetQueryObjectui64v, EXT); } GR_GL_GET_PROC(GetQueryObjectiv); GR_GL_GET_PROC(GetQueryObjectuiv); GR_GL_GET_PROC(GetQueryiv); GR_GL_GET_PROC(GetShaderInfoLog); GR_GL_GET_PROC(GetShaderiv); GR_GL_GET_PROC(GetString); GR_GL_GET_PROC(GetTexLevelParameteriv); GR_GL_GET_PROC(GenTextures); GR_GL_GET_PROC(GetUniformLocation); GR_GL_GET_PROC(LineWidth); GR_GL_GET_PROC(LinkProgram); GR_GL_GET_PROC(MapBuffer); GR_GL_GET_PROC(PixelStorei); GR_GL_GET_PROC(ReadBuffer); GR_GL_GET_PROC(ReadPixels); GR_GL_GET_PROC(Scissor); GR_GL_GET_PROC(ShaderSource); GR_GL_GET_PROC(StencilFunc); GR_GL_GET_PROC(StencilFuncSeparate); GR_GL_GET_PROC(StencilMask); GR_GL_GET_PROC(StencilMaskSeparate); GR_GL_GET_PROC(StencilOp); GR_GL_GET_PROC(StencilOpSeparate); GR_GL_GET_PROC(TexImage2D) GR_GL_GET_PROC(TexParameteri); GR_GL_GET_PROC(TexStorage2D); if (NULL == interface->fTexStorage2D) { GR_GL_GET_PROC_SUFFIX(TexStorage2D, EXT); } GR_GL_GET_PROC(TexSubImage2D); GR_GL_GET_PROC(Uniform1f); GR_GL_GET_PROC(Uniform1i); GR_GL_GET_PROC(Uniform1fv); GR_GL_GET_PROC(Uniform1iv); GR_GL_GET_PROC(Uniform2f); GR_GL_GET_PROC(Uniform2i); GR_GL_GET_PROC(Uniform2fv); GR_GL_GET_PROC(Uniform2iv); GR_GL_GET_PROC(Uniform3f); GR_GL_GET_PROC(Uniform3i); GR_GL_GET_PROC(Uniform3fv); GR_GL_GET_PROC(Uniform3iv); GR_GL_GET_PROC(Uniform4f); GR_GL_GET_PROC(Uniform4i); GR_GL_GET_PROC(Uniform4fv); GR_GL_GET_PROC(Uniform4iv); GR_GL_GET_PROC(UniformMatrix2fv); GR_GL_GET_PROC(UniformMatrix3fv); GR_GL_GET_PROC(UniformMatrix4fv); GR_GL_GET_PROC(UnmapBuffer); GR_GL_GET_PROC(UseProgram); GR_GL_GET_PROC(VertexAttrib4fv); GR_GL_GET_PROC(VertexAttribPointer); GR_GL_GET_PROC(Viewport); // First look for GL3.0 FBO or GL_ARB_framebuffer_object (same since // GL_ARB_framebuffer_object doesn't use ARB suffix.) if (glVer >= GR_GL_VER(3,0) || GrGLHasExtensionFromString("GL_ARB_framebuffer_object", extString)) { GR_GL_GET_PROC(GenFramebuffers); GR_GL_GET_PROC(GetFramebufferAttachmentParameteriv); GR_GL_GET_PROC(GetRenderbufferParameteriv); GR_GL_GET_PROC(BindFramebuffer); GR_GL_GET_PROC(FramebufferTexture2D); GR_GL_GET_PROC(CheckFramebufferStatus); GR_GL_GET_PROC(DeleteFramebuffers); GR_GL_GET_PROC(RenderbufferStorage); GR_GL_GET_PROC(GenRenderbuffers); GR_GL_GET_PROC(DeleteRenderbuffers); GR_GL_GET_PROC(FramebufferRenderbuffer); GR_GL_GET_PROC(BindRenderbuffer); GR_GL_GET_PROC(RenderbufferStorageMultisample); GR_GL_GET_PROC(BlitFramebuffer); } else if (GrGLHasExtensionFromString("GL_EXT_framebuffer_object", extString)) { GR_GL_GET_PROC_SUFFIX(GenFramebuffers, EXT); GR_GL_GET_PROC_SUFFIX(GetFramebufferAttachmentParameteriv, EXT); GR_GL_GET_PROC_SUFFIX(GetRenderbufferParameteriv, EXT); GR_GL_GET_PROC_SUFFIX(BindFramebuffer, EXT); GR_GL_GET_PROC_SUFFIX(FramebufferTexture2D, EXT); GR_GL_GET_PROC_SUFFIX(CheckFramebufferStatus, EXT); GR_GL_GET_PROC_SUFFIX(DeleteFramebuffers, EXT); GR_GL_GET_PROC_SUFFIX(RenderbufferStorage, EXT); GR_GL_GET_PROC_SUFFIX(GenRenderbuffers, EXT); GR_GL_GET_PROC_SUFFIX(DeleteRenderbuffers, EXT); GR_GL_GET_PROC_SUFFIX(FramebufferRenderbuffer, EXT); GR_GL_GET_PROC_SUFFIX(BindRenderbuffer, EXT); if (GrGLHasExtensionFromString("GL_EXT_framebuffer_multisample", extString)) { GR_GL_GET_PROC_SUFFIX(RenderbufferStorageMultisample, EXT); } if (GrGLHasExtensionFromString("GL_EXT_framebuffer_blit", extString)) { GR_GL_GET_PROC_SUFFIX(BlitFramebuffer, EXT); } } else { // we must have FBOs delete interface; return NULL; } GR_GL_GET_PROC(BindFragDataLocationIndexed); interface->fBindingsExported = kDesktop_GrGLBinding; return interface; } else { return NULL; } }
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gl/GrGLInterface.h" #include "../GrGLUtil.h" #define GL_GLEXT_PROTOTYPES #include <GL/osmesa.h> #define GR_GL_GET_PROC(F) interface->f ## F = (GrGL ## F ## Proc) \ OSMesaGetProcAddress("gl" #F); #define GR_GL_GET_PROC_SUFFIX(F, S) interface->f ## F = (GrGL ## F ## Proc) \ OSMesaGetProcAddress("gl" #F #S); // We use OSMesaGetProcAddress for every gl function to avoid accidentally using // non-Mesa gl functions. const GrGLInterface* GrGLCreateMesaInterface() { if (NULL != OSMesaGetCurrentContext()) { GrGLGetStringProc getString = (GrGLGetStringProc) OSMesaGetProcAddress("glGetString"); const char* versionString = (const char*) getString(GL_VERSION); const char* extString = (const char*) getString(GL_EXTENSIONS); GrGLVersion glVer = GrGLGetVersionFromString(versionString); if (glVer < GR_GL_VER(1,5)) { // We must have array and element_array buffer objects. return NULL; } GrGLInterface* interface = new GrGLInterface(); GR_GL_GET_PROC(ActiveTexture); GR_GL_GET_PROC(BeginQuery); GR_GL_GET_PROC(AttachShader); GR_GL_GET_PROC(BindAttribLocation); GR_GL_GET_PROC(BindBuffer); GR_GL_GET_PROC(BindFragDataLocation); GR_GL_GET_PROC(BindTexture); GR_GL_GET_PROC(BlendFunc); if (glVer >= GR_GL_VER(1,4) || GrGLHasExtensionFromString("GL_ARB_imaging", extString)) { GR_GL_GET_PROC(BlendColor); GR_GL_GET_PROC(BlendEquation); } else { if (GrGLHasExtensionFromString("GL_EXT_blend_color", extString)) { GR_GL_GET_PROC_SUFFIX(BlendColor, EXT); } if (GrGLHasExtensionFromString("GL_EXT_blend_minmax", extString) || GrGLHasExtensionFromString("GL_EXT_blend_subtract", extString)) { GR_GL_GET_PROC_SUFFIX(BlendEquation, EXT); } } GR_GL_GET_PROC(BufferData); GR_GL_GET_PROC(BufferSubData); GR_GL_GET_PROC(Clear); GR_GL_GET_PROC(ClearColor); GR_GL_GET_PROC(ClearStencil); GR_GL_GET_PROC(ColorMask); GR_GL_GET_PROC(CompileShader); GR_GL_GET_PROC(CompressedTexImage2D); GR_GL_GET_PROC(CreateProgram); GR_GL_GET_PROC(CreateShader); GR_GL_GET_PROC(CullFace); GR_GL_GET_PROC(DeleteBuffers); GR_GL_GET_PROC(DeleteProgram); GR_GL_GET_PROC(DeleteQueries); GR_GL_GET_PROC(DeleteShader); GR_GL_GET_PROC(DeleteTextures); GR_GL_GET_PROC(DepthMask); GR_GL_GET_PROC(Disable); GR_GL_GET_PROC(DisableVertexAttribArray); GR_GL_GET_PROC(DrawArrays); GR_GL_GET_PROC(DrawBuffer); GR_GL_GET_PROC(DrawBuffers); GR_GL_GET_PROC(DrawElements); GR_GL_GET_PROC(Enable); GR_GL_GET_PROC(EnableVertexAttribArray); GR_GL_GET_PROC(EndQuery); GR_GL_GET_PROC(Finish); GR_GL_GET_PROC(Flush); GR_GL_GET_PROC(FrontFace); GR_GL_GET_PROC(GenBuffers); GR_GL_GET_PROC(GenQueries); GR_GL_GET_PROC(GetBufferParameteriv); GR_GL_GET_PROC(GetError); GR_GL_GET_PROC(GetIntegerv); GR_GL_GET_PROC(GetProgramInfoLog); GR_GL_GET_PROC(GetProgramiv); if (glVer >= GR_GL_VER(3,3) || GrGLHasExtensionFromString("GL_ARB_timer_query", extString)) { GR_GL_GET_PROC(GetQueryObjecti64v); GR_GL_GET_PROC(GetQueryObjectui64v) GR_GL_GET_PROC(QueryCounter); } else if (GrGLHasExtensionFromString("GL_EXT_timer_query", extString)) { GR_GL_GET_PROC_SUFFIX(GetQueryObjecti64v, EXT); GR_GL_GET_PROC_SUFFIX(GetQueryObjectui64v, EXT); } GR_GL_GET_PROC(GetQueryObjectiv); GR_GL_GET_PROC(GetQueryObjectuiv); GR_GL_GET_PROC(GetQueryiv); GR_GL_GET_PROC(GetShaderInfoLog); GR_GL_GET_PROC(GetShaderiv); GR_GL_GET_PROC(GetString); GR_GL_GET_PROC(GetTexLevelParameteriv); GR_GL_GET_PROC(GenTextures); GR_GL_GET_PROC(GetUniformLocation); GR_GL_GET_PROC(LineWidth); GR_GL_GET_PROC(LinkProgram); GR_GL_GET_PROC(MapBuffer); GR_GL_GET_PROC(PixelStorei); GR_GL_GET_PROC(ReadBuffer); GR_GL_GET_PROC(ReadPixels); GR_GL_GET_PROC(Scissor); GR_GL_GET_PROC(ShaderSource); GR_GL_GET_PROC(StencilFunc); GR_GL_GET_PROC(StencilFuncSeparate); GR_GL_GET_PROC(StencilMask); GR_GL_GET_PROC(StencilMaskSeparate); GR_GL_GET_PROC(StencilOp); GR_GL_GET_PROC(StencilOpSeparate); GR_GL_GET_PROC(TexImage2D) GR_GL_GET_PROC(TexParameteri); GR_GL_GET_PROC(TexParameteriv); GR_GL_GET_PROC(TexStorage2D); if (NULL == interface->fTexStorage2D) { GR_GL_GET_PROC_SUFFIX(TexStorage2D, EXT); } GR_GL_GET_PROC(TexSubImage2D); GR_GL_GET_PROC(Uniform1f); GR_GL_GET_PROC(Uniform1i); GR_GL_GET_PROC(Uniform1fv); GR_GL_GET_PROC(Uniform1iv); GR_GL_GET_PROC(Uniform2f); GR_GL_GET_PROC(Uniform2i); GR_GL_GET_PROC(Uniform2fv); GR_GL_GET_PROC(Uniform2iv); GR_GL_GET_PROC(Uniform3f); GR_GL_GET_PROC(Uniform3i); GR_GL_GET_PROC(Uniform3fv); GR_GL_GET_PROC(Uniform3iv); GR_GL_GET_PROC(Uniform4f); GR_GL_GET_PROC(Uniform4i); GR_GL_GET_PROC(Uniform4fv); GR_GL_GET_PROC(Uniform4iv); GR_GL_GET_PROC(UniformMatrix2fv); GR_GL_GET_PROC(UniformMatrix3fv); GR_GL_GET_PROC(UniformMatrix4fv); GR_GL_GET_PROC(UnmapBuffer); GR_GL_GET_PROC(UseProgram); GR_GL_GET_PROC(VertexAttrib4fv); GR_GL_GET_PROC(VertexAttribPointer); GR_GL_GET_PROC(Viewport); // First look for GL3.0 FBO or GL_ARB_framebuffer_object (same since // GL_ARB_framebuffer_object doesn't use ARB suffix.) if (glVer >= GR_GL_VER(3,0) || GrGLHasExtensionFromString("GL_ARB_framebuffer_object", extString)) { GR_GL_GET_PROC(GenFramebuffers); GR_GL_GET_PROC(GetFramebufferAttachmentParameteriv); GR_GL_GET_PROC(GetRenderbufferParameteriv); GR_GL_GET_PROC(BindFramebuffer); GR_GL_GET_PROC(FramebufferTexture2D); GR_GL_GET_PROC(CheckFramebufferStatus); GR_GL_GET_PROC(DeleteFramebuffers); GR_GL_GET_PROC(RenderbufferStorage); GR_GL_GET_PROC(GenRenderbuffers); GR_GL_GET_PROC(DeleteRenderbuffers); GR_GL_GET_PROC(FramebufferRenderbuffer); GR_GL_GET_PROC(BindRenderbuffer); GR_GL_GET_PROC(RenderbufferStorageMultisample); GR_GL_GET_PROC(BlitFramebuffer); } else if (GrGLHasExtensionFromString("GL_EXT_framebuffer_object", extString)) { GR_GL_GET_PROC_SUFFIX(GenFramebuffers, EXT); GR_GL_GET_PROC_SUFFIX(GetFramebufferAttachmentParameteriv, EXT); GR_GL_GET_PROC_SUFFIX(GetRenderbufferParameteriv, EXT); GR_GL_GET_PROC_SUFFIX(BindFramebuffer, EXT); GR_GL_GET_PROC_SUFFIX(FramebufferTexture2D, EXT); GR_GL_GET_PROC_SUFFIX(CheckFramebufferStatus, EXT); GR_GL_GET_PROC_SUFFIX(DeleteFramebuffers, EXT); GR_GL_GET_PROC_SUFFIX(RenderbufferStorage, EXT); GR_GL_GET_PROC_SUFFIX(GenRenderbuffers, EXT); GR_GL_GET_PROC_SUFFIX(DeleteRenderbuffers, EXT); GR_GL_GET_PROC_SUFFIX(FramebufferRenderbuffer, EXT); GR_GL_GET_PROC_SUFFIX(BindRenderbuffer, EXT); if (GrGLHasExtensionFromString("GL_EXT_framebuffer_multisample", extString)) { GR_GL_GET_PROC_SUFFIX(RenderbufferStorageMultisample, EXT); } if (GrGLHasExtensionFromString("GL_EXT_framebuffer_blit", extString)) { GR_GL_GET_PROC_SUFFIX(BlitFramebuffer, EXT); } } else { // we must have FBOs delete interface; return NULL; } GR_GL_GET_PROC(BindFragDataLocationIndexed); interface->fBindingsExported = kDesktop_GrGLBinding; return interface; } else { return NULL; } }
Add glTexParameteriv to MESA GrGLInterface (missing from r4099)
Add glTexParameteriv to MESA GrGLInterface (missing from r4099) git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@4100 2bbb7eff-a529-9590-31e7-b0007b416f81
C++
bsd-3-clause
hbwhlklive/color-emoji.skia,Frankie-666/color-emoji.skia,Hankuo/color-emoji.skia,Frankie-666/color-emoji.skia,MatChung/color-emoji.skia,Frankie-666/color-emoji.skia,MatChung/color-emoji.skia,hbwhlklive/color-emoji.skia,Hankuo/color-emoji.skia,hbwhlklive/color-emoji.skia,Hankuo/color-emoji.skia,Frankie-666/color-emoji.skia,MatChung/color-emoji.skia,Frankie-666/color-emoji.skia,Frankie-666/color-emoji.skia,Hankuo/color-emoji.skia,hbwhlklive/color-emoji.skia,MatChung/color-emoji.skia,Hankuo/color-emoji.skia,Hankuo/color-emoji.skia,hbwhlklive/color-emoji.skia,MatChung/color-emoji.skia,MatChung/color-emoji.skia,hbwhlklive/color-emoji.skia
2ead91911f8d39013d7065344e1ab7f2f41ed587
src/istio/control/tcp/attributes_builder.cc
src/istio/control/tcp/attributes_builder.cc
/* Copyright 2017 Istio 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 "src/istio/control/tcp/attributes_builder.h" #include "include/istio/utils/attribute_names.h" #include "include/istio/utils/attributes_builder.h" namespace istio { namespace control { namespace tcp { namespace { // Connection events for TCP connection. const std::string kConnectionOpen("open"); const std::string kConnectionContinue("continue"); const std::string kConnectionClose("close"); } // namespace void AttributesBuilder::ExtractCheckAttributes(CheckData* check_data) { utils::AttributesBuilder builder(&request_->attributes); std::string source_ip; int source_port; // TODO(kuat): there is no way to propagate source IP in TCP, so we auto-set // it if (check_data->GetSourceIpPort(&source_ip, &source_port)) { builder.AddBytes(utils::AttributeName::kSourceIp, source_ip); } // TODO(diemtvu): add TCP authn filter similar to http case, and use authn // result output here instead. std::string source_user; if (check_data->GetSourceUser(&source_user)) { // TODO(diemtvu): remove kSourceUser once migration to source.principal is // over. https://github.com/istio/istio/issues/4689 builder.AddString(utils::AttributeName::kSourceUser, source_user); builder.AddString(utils::AttributeName::kSourcePrincipal, source_user); } builder.AddBool(utils::AttributeName::kConnectionMtls, check_data->IsMutualTLS()); builder.AddTimestamp(utils::AttributeName::kContextTime, std::chrono::system_clock::now()); builder.AddString(utils::AttributeName::kContextProtocol, "tcp"); builder.AddString(utils::AttributeName::kConnectionEvent, kConnectionOpen); // Get unique downstream connection ID, which is <uuid>-<connection id>. std::string connection_id = check_data->GetConnectionId(); builder.AddString(utils::AttributeName::kConnectionId, connection_id); } void AttributesBuilder::ExtractReportAttributes( ReportData* report_data, bool is_final_report, ReportData::ReportInfo* last_report_info) { utils::AttributesBuilder builder(&request_->attributes); ReportData::ReportInfo info; report_data->GetReportInfo(&info); builder.AddInt64(utils::AttributeName::kConnectionReceviedBytes, info.received_bytes - last_report_info->received_bytes); builder.AddInt64(utils::AttributeName::kConnectionReceviedTotalBytes, info.received_bytes); builder.AddInt64(utils::AttributeName::kConnectionSendBytes, info.send_bytes - last_report_info->send_bytes); builder.AddInt64(utils::AttributeName::kConnectionSendTotalBytes, info.send_bytes); if (is_final_report) { builder.AddDuration(utils::AttributeName::kConnectionDuration, info.duration); if (!request_->check_status.ok()) { builder.AddInt64(utils::AttributeName::kCheckErrorCode, request_->check_status.error_code()); builder.AddString(utils::AttributeName::kCheckErrorMessage, request_->check_status.ToString()); } builder.AddString(utils::AttributeName::kConnectionEvent, kConnectionClose); } else { last_report_info->received_bytes = info.received_bytes; last_report_info->send_bytes = info.send_bytes; builder.AddString(utils::AttributeName::kConnectionEvent, kConnectionContinue); } std::string dest_ip; int dest_port; // Do not overwrite destination IP and port if it has already been set. if (report_data->GetDestinationIpPort(&dest_ip, &dest_port)) { if (!builder.HasAttribute(utils::AttributeName::kDestinationIp)) { builder.AddBytes(utils::AttributeName::kDestinationIp, dest_ip); } if (!builder.HasAttribute(utils::AttributeName::kDestinationPort)) { builder.AddInt64(utils::AttributeName::kDestinationPort, dest_port); } } std::string uid; if (report_data->GetDestinationUID(&uid)) { builder.AddString(utils::AttributeName::kDestinationUID, uid); } builder.AddTimestamp(utils::AttributeName::kContextTime, std::chrono::system_clock::now()); } } // namespace tcp } // namespace control } // namespace istio
/* Copyright 2017 Istio 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 "src/istio/control/tcp/attributes_builder.h" #include "include/istio/utils/attribute_names.h" #include "include/istio/utils/attributes_builder.h" namespace istio { namespace control { namespace tcp { namespace { // Connection events for TCP connection. const std::string kConnectionOpen("open"); const std::string kConnectionContinue("continue"); const std::string kConnectionClose("close"); } // namespace void AttributesBuilder::ExtractCheckAttributes(CheckData* check_data) { utils::AttributesBuilder builder(&request_->attributes); std::string source_ip; int source_port; // TODO(kuat): there is no way to propagate source IP in TCP, so we auto-set // it if (check_data->GetSourceIpPort(&source_ip, &source_port)) { builder.AddBytes(utils::AttributeName::kSourceIp, source_ip); } // TODO(diemtvu): add TCP authn filter similar to http case, and use authn // result output here instead. std::string source_user; if (check_data->GetSourceUser(&source_user)) { // TODO(diemtvu): remove kSourceUser once migration to source.principal is // over. https://github.com/istio/istio/issues/4689 builder.AddString(utils::AttributeName::kSourceUser, source_user); builder.AddString(utils::AttributeName::kSourcePrincipal, source_user); } builder.AddBool(utils::AttributeName::kConnectionMtls, check_data->IsMutualTLS()); builder.AddString(utils::AttributeName::kConnectionRequestedServerName, check_data->GetRequestedServerName()); builder.AddTimestamp(utils::AttributeName::kContextTime, std::chrono::system_clock::now()); builder.AddString(utils::AttributeName::kContextProtocol, "tcp"); builder.AddString(utils::AttributeName::kConnectionEvent, kConnectionOpen); // Get unique downstream connection ID, which is <uuid>-<connection id>. std::string connection_id = check_data->GetConnectionId(); builder.AddString(utils::AttributeName::kConnectionId, connection_id); } void AttributesBuilder::ExtractReportAttributes( ReportData* report_data, bool is_final_report, ReportData::ReportInfo* last_report_info) { utils::AttributesBuilder builder(&request_->attributes); ReportData::ReportInfo info; report_data->GetReportInfo(&info); builder.AddInt64(utils::AttributeName::kConnectionReceviedBytes, info.received_bytes - last_report_info->received_bytes); builder.AddInt64(utils::AttributeName::kConnectionReceviedTotalBytes, info.received_bytes); builder.AddInt64(utils::AttributeName::kConnectionSendBytes, info.send_bytes - last_report_info->send_bytes); builder.AddInt64(utils::AttributeName::kConnectionSendTotalBytes, info.send_bytes); if (is_final_report) { builder.AddDuration(utils::AttributeName::kConnectionDuration, info.duration); if (!request_->check_status.ok()) { builder.AddInt64(utils::AttributeName::kCheckErrorCode, request_->check_status.error_code()); builder.AddString(utils::AttributeName::kCheckErrorMessage, request_->check_status.ToString()); } builder.AddString(utils::AttributeName::kConnectionEvent, kConnectionClose); } else { last_report_info->received_bytes = info.received_bytes; last_report_info->send_bytes = info.send_bytes; builder.AddString(utils::AttributeName::kConnectionEvent, kConnectionContinue); } std::string dest_ip; int dest_port; // Do not overwrite destination IP and port if it has already been set. if (report_data->GetDestinationIpPort(&dest_ip, &dest_port)) { if (!builder.HasAttribute(utils::AttributeName::kDestinationIp)) { builder.AddBytes(utils::AttributeName::kDestinationIp, dest_ip); } if (!builder.HasAttribute(utils::AttributeName::kDestinationPort)) { builder.AddInt64(utils::AttributeName::kDestinationPort, dest_port); } } std::string uid; if (report_data->GetDestinationUID(&uid)) { builder.AddString(utils::AttributeName::kDestinationUID, uid); } builder.AddTimestamp(utils::AttributeName::kContextTime, std::chrono::system_clock::now()); } } // namespace tcp } // namespace control } // namespace istio
add building attribute ConnectionRequestedServerName
add building attribute ConnectionRequestedServerName
C++
apache-2.0
lizan/proxy,lizan/proxy,istio/proxy,lizan/proxy,istio/proxy,istio/proxy,istio/proxy,lizan/proxy
e25defdba4d655ad89eb26a015df13e573d2800d
cli/ligfind.cpp
cli/ligfind.cpp
// // Programmer: Craig Stuart Sapp <[email protected]> // Creation Date: Sat Jun 13 11:45:47 PDT 2020 // Last Modified: Sat Jun 13 11:45:50 PDT 2020 // Filename: ligfind.cpp // URL: https://github.com/craigsapp/humlib/blob/master/cli/ligfind.cpp // Syntax: C++11 // vim: ts=3 noexpandtab nowrap // // Description: Find cases where there are two semi-breves (whole notes) // in a row, with lyric text only on the first note. // This is for the Tasso in Music Project to find locations // where ligature marks should probably be added. // // To do: Maybe add an option to check whether or not there is already // a ligature mark on the two notes. // /* Example output: (staring measure/part name/filename) 19 Quinto Tam1020468a-Io_che_fin_a_quel_punto_altro_non_volsi--Marotta_1600 1 Tenore Tco0806a-Piange_sospira_e_quando_i_caldi_raggi--Monteverdi_1603 2 Tenore Tco0806a-Piange_sospira_e_quando_i_caldi_raggi--Monteverdi_1603 7 Basso Trm0025c-Come_vivro_ne_le_mie_pene_Amore--Billi_1602 24 Alto Trm0048a-Amor_lalma_mallaccia--Meldert_1575 87 Quinto Trm0099a-Geloso_amante_apro_millocchi_e_giro--Luzzaschi_1576 93 Quinto Trm0099a-Geloso_amante_apro_millocchi_e_giro--Luzzaschi_1576 58 Sesto Trm0248a-Vita_de_la_mia_vita--Marenzio_1584 80 Sesto Trm0248a-Vita_de_la_mia_vita--Marenzio_1584 49 Alto Trm0255a-Mentre_in_grembo_a_la_madre_un_giorno--Giovannelli_1599 44 Tenore Trm0256d-Amor_che_qui_dintorno--Nanino_1599 82 Basso Trm0378h-Nel_dolce_seno_de_la_bella_Clori--Luzzaschi_1604 97 Basso Trm0378h-Nel_dolce_seno_de_la_bella_Clori--Luzzaschi_1604 28 Basso Tsg12065a-Segue_egli_la_vittoria_e_la_trafitta--Massaino_1587 9 Alto Tsg12066a--Amico_hai_vinto_io_ti_perdon_perdona--Massaino_1587 16 Alto Tsg12096c-Giunto_a_la_tomba_ove_al_suo_spirto_vivo--Ricci_1597 20 [Basso continuo] Tsg12096g-Giunto_a_la_tomba_ove_al_suo_spirto_vivo--DIndia_1618 29 [Canto] Tsg16060e-La_tral_sangue_e_le_morti_egro_giacente--DIndia_1609 32 [Canto] Tsg19107c-Ma_che_squallido_e_scuro_anco_mi_piaci--DIndia_1609 9 Basso continuo Tsg20128b-Si_volse_Armida_e_l_rimiro_improvviso--Eredi_1629 */ #include "humlib.h" #include <iostream> using namespace hum; using namespace std; void processFile (HumdrumFile& infile); void processPart (HumdrumFile& infile, HTp partstart); void analyzeBarNumbers (HumdrumFile& infile); HTp getNoteList (vector<HTp>& notelist, HTp partstart); void printLigatureCandidate (HTp partname, HTp starting, HTp ending); bool hasText (HTp token); vector<int> m_barnum; // measure number of current line in Humdrum file. /////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { Options options; options.process(argc, argv); HumdrumFileStream instream(options); HumdrumFile infile; while (instream.read(infile)) { processFile(infile); } return 0; } ////////////////////////////// // // processFile -- // void processFile(HumdrumFile& infile) { analyzeBarNumbers(infile); vector<HTp> sstarts; sstarts = infile.getKernSpineStartList(); for (int i=0; i<(int)sstarts.size(); i++) { processPart(infile, sstarts[i]); } } ////////////////////////////// // // analyzeBarNumbers -- Create an index of the measure number // that each line of the input file occurs in. // void analyzeBarNumbers(HumdrumFile& infile) { m_barnum.clear(); m_barnum.resize(infile.getLineCount()); int current = -1; HumRegex hre; for (int i=0; i<infile.getLineCount(); i++) { if (!infile[i].isBarline()) { m_barnum.at(i) = current; continue; } if (hre.search(infile[i].token(0), "=(\\d+)")) { current = hre.getMatchInt(1); } m_barnum.at(i) = current; } } ////////////////////////////// // // processPart -- Create a list of notes, and then // search for two whole notes where the first whole note // has a syllable and the second one has a null syllable. // // Two whole notes may be mean dotted whole notes in // triple mensurations, or could even means 2/3rd of a whole // note in coloration, so a range of durations for whole notes // is considered, from 8/3 to 6 (units of duration are in quarter // notes). // void processPart(HumdrumFile& infile, HTp partstart) { vector<HTp> notelist; HTp partname = getNoteList(notelist, partstart); vector<HumNum> durations(notelist.size()); for (int i=0; i<(int)notelist.size(); i++) { durations[i] = notelist[i]->getTiedDuration(); } HumNum mindur(8, 3); HumNum maxdur(6, 1); for (int i=0; i<(int)durations.size()-1; i++) { if (notelist[i]->isRest()) { continue; } if (notelist[i+1]->isRest()) { continue; } if ((durations[i] >= mindur) && (durations[i] <= maxdur) && (durations[i+1] >= mindur) && (durations[i+1] <= maxdur)) { // exclude cases where the pitch is repeated int pitch1 = Convert::kernToMidiNoteNumber(notelist[i]); int pitch2 = Convert::kernToMidiNoteNumber(notelist[i+1]); if (pitch1 == pitch2) { continue; } bool hastext1 = hasText(notelist[i]); bool hastext2 = hasText(notelist[i+1]); if (hastext1 && !hastext2) { printLigatureCandidate(partname, notelist[i], notelist[i+1]); } } } } ////////////////////////////// // // hasText -- return true if the given note has non-null // **text content in a field to the right of it before the // next **kern spine. Spine splits in **kern data can cause // problems, but there should be no spine splits in data that // will be analyze with this program. // bool hasText(HTp token) { HTp current = token->getNextFieldToken(); while (current) { if (current->isKern()) { break; } if (current->isDataType("**text")) { if (current->isNull()) { return false; } else { return true; } } current = current->getNextFieldToken(); } return false; } ////////////////////////////// // // printLigatureCandidate -- Print pairs of notes that are probably // written as a ligature in the original notation. // void printLigatureCandidate(HTp partname, HTp starting, HTp ending) { HumdrumFile* infile = starting->getOwner()->getOwner(); cerr << m_barnum[starting->getLineIndex()]; if (partname) { cerr << "\t" << partname->substr(3); } else { cerr << "\t"; } cerr << "\t" << infile->getFilenameBase(); cerr << endl; } ////////////////////////////// // // getNoteList -- Get a melodic list of notes in a part // (ignoring any spine splits). Secondary tied notes are // not stored. // HTp getNoteList(vector<HTp>& notelist, HTp partstart) { HumdrumFile* infile = partstart->getOwner()->getOwner(); notelist.clear(); notelist.reserve(infile->getLineCount()); HTp current = partstart->getNextToken(); HTp partname = NULL; while (current) { if (current->isInterpretation()) { if (current->compare(0, 3, "*I\"") == 0) { partname = current; } } if (current->isData() && current->isNoteAttack()) { notelist.push_back(current); } current = current->getNextToken(); } return partname; }
// // Programmer: Craig Stuart Sapp <[email protected]> // Creation Date: Sat Jun 13 11:45:47 PDT 2020 // Last Modified: Sat Jun 13 11:45:50 PDT 2020 // Filename: ligfind.cpp // URL: https://github.com/craigsapp/humlib/blob/master/cli/ligfind.cpp // Syntax: C++11 // vim: ts=3 noexpandtab nowrap // // Description: Find cases where there are two semi-breves (whole notes) // in a row, with lyric text only on the first note. // This is for the Tasso in Music Project to find locations // where ligature marks should probably be added. // // To do: Maybe add an option to check whether or not there is already // a ligature mark on the two notes. // /* Example output: (staring measure/part name/filename) 19 Quinto Tam1020468a-Io_che_fin_a_quel_punto_altro_non_volsi--Marotta_1600 1 Tenore Tco0806a-Piange_sospira_e_quando_i_caldi_raggi--Monteverdi_1603 2 Tenore Tco0806a-Piange_sospira_e_quando_i_caldi_raggi--Monteverdi_1603 7 Basso Trm0025c-Come_vivro_ne_le_mie_pene_Amore--Billi_1602 24 Alto Trm0048a-Amor_lalma_mallaccia--Meldert_1575 87 Quinto Trm0099a-Geloso_amante_apro_millocchi_e_giro--Luzzaschi_1576 93 Quinto Trm0099a-Geloso_amante_apro_millocchi_e_giro--Luzzaschi_1576 58 Sesto Trm0248a-Vita_de_la_mia_vita--Marenzio_1584 80 Sesto Trm0248a-Vita_de_la_mia_vita--Marenzio_1584 49 Alto Trm0255a-Mentre_in_grembo_a_la_madre_un_giorno--Giovannelli_1599 44 Tenore Trm0256d-Amor_che_qui_dintorno--Nanino_1599 82 Basso Trm0378h-Nel_dolce_seno_de_la_bella_Clori--Luzzaschi_1604 97 Basso Trm0378h-Nel_dolce_seno_de_la_bella_Clori--Luzzaschi_1604 28 Basso Tsg12065a-Segue_egli_la_vittoria_e_la_trafitta--Massaino_1587 9 Alto Tsg12066a--Amico_hai_vinto_io_ti_perdon_perdona--Massaino_1587 16 Alto Tsg12096c-Giunto_a_la_tomba_ove_al_suo_spirto_vivo--Ricci_1597 20 [Basso continuo] Tsg12096g-Giunto_a_la_tomba_ove_al_suo_spirto_vivo--DIndia_1618 29 [Canto] Tsg16060e-La_tral_sangue_e_le_morti_egro_giacente--DIndia_1609 32 [Canto] Tsg19107c-Ma_che_squallido_e_scuro_anco_mi_piaci--DIndia_1609 9 Basso continuo Tsg20128b-Si_volse_Armida_e_l_rimiro_improvviso--Eredi_1629 */ #include "humlib.h" #include <iostream> using namespace hum; using namespace std; void processFile (HumdrumFile& infile); void processPart (HumdrumFile& infile, HTp partstart); void analyzeBarNumbers (HumdrumFile& infile); HTp getNoteList (vector<HTp>& notelist, HTp partstart); void printLigatureCandidate (HTp partname, HTp starting, HTp ending); bool hasText (HTp token); vector<int> m_barnum; // measure number of current line in Humdrum file. /////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { Options options; options.process(argc, argv); HumdrumFileStream instream(options); HumdrumFile infile; while (instream.read(infile)) { processFile(infile); } return 0; } ////////////////////////////// // // processFile -- // void processFile(HumdrumFile& infile) { analyzeBarNumbers(infile); vector<HTp> sstarts; sstarts = infile.getKernSpineStartList(); for (int i=0; i<(int)sstarts.size(); i++) { processPart(infile, sstarts[i]); } } ////////////////////////////// // // analyzeBarNumbers -- Create an index of the measure number // that each line of the input file occurs in. // void analyzeBarNumbers(HumdrumFile& infile) { m_barnum.clear(); m_barnum.resize(infile.getLineCount()); int current = -1; HumRegex hre; for (int i=0; i<infile.getLineCount(); i++) { if (!infile[i].isBarline()) { m_barnum.at(i) = current; continue; } if (hre.search(infile[i].token(0), "=(\\d+)")) { current = hre.getMatchInt(1); } m_barnum.at(i) = current; } } ////////////////////////////// // // processPart -- Create a list of notes, and then // search for two whole notes where the first whole note // has a syllable and the second one has a null syllable. // // Two whole notes may be mean dotted whole notes in // triple mensurations, or could even means 2/3rd of a whole // note in coloration, so a range of durations for whole notes // is considered, from 8/3 to 6 (units of duration are in quarter // notes). // void processPart(HumdrumFile& infile, HTp partstart) { vector<HTp> notelist; HTp partname = getNoteList(notelist, partstart); vector<HumNum> durations(notelist.size()); for (int i=0; i<(int)notelist.size(); i++) { durations[i] = notelist[i]->getTiedDuration(); } HumNum mindur(8, 3); HumNum maxdur(6, 1); for (int i=0; i<(int)durations.size()-1; i++) { if (notelist[i]->isRest()) { continue; } if (notelist[i+1]->isRest()) { continue; } if ((durations[i] >= mindur) && (durations[i] <= maxdur) && (durations[i+1] >= mindur) && (durations[i+1] <= maxdur)) { // exclude cases where the pitch is repeated int pitch1 = Convert::kernToMidiNoteNumber(notelist[i]); int pitch2 = Convert::kernToMidiNoteNumber(notelist[i+1]); if (pitch1 == pitch2) { continue; } bool hastext1 = hasText(notelist[i]); bool hastext2 = hasText(notelist[i+1]); if (hastext1 && !hastext2) { printLigatureCandidate(partname, notelist[i], notelist[i+1]); } } } } ////////////////////////////// // // hasText -- return true if the given note has non-null // **text content in a field to the right of it before the // next **kern spine. Spine splits in **kern data can cause // problems, but there should be no spine splits in data that // will be analyze with this program. // bool hasText(HTp token) { HTp current = token->getNextFieldToken(); while (current) { if (current->isKern()) { break; } if (current->isDataType("**text")) { if (current->isNull()) { return false; } else { return true; } } current = current->getNextFieldToken(); } return false; } ////////////////////////////// // // printLigatureCandidate -- Print pairs of notes that are probably // written as a ligature in the original notation. // void printLigatureCandidate(HTp partname, HTp starting, HTp ending) { HumdrumFile* infile = starting->getOwner()->getOwner(); cout << m_barnum[starting->getLineIndex()]; if (partname) { cout << "\t" << partname->substr(3); } else { cout << "\t"; } cout << "\t" << infile->getFilenameBase(); cout << endl; } ////////////////////////////// // // getNoteList -- Get a melodic list of notes in a part // (ignoring any spine splits). Secondary tied notes are // not stored. // HTp getNoteList(vector<HTp>& notelist, HTp partstart) { HumdrumFile* infile = partstart->getOwner()->getOwner(); notelist.clear(); notelist.reserve(infile->getLineCount()); HTp current = partstart->getNextToken(); HTp partname = NULL; while (current) { if (current->isInterpretation()) { if (current->compare(0, 3, "*I\"") == 0) { partname = current; } } if (current->isData() && current->isNoteAttack() && !current->isNull()) { notelist.push_back(current); } current = current->getNextToken(); } return partname; }
Update ligfind program to fix note attack selection.
Update ligfind program to fix note attack selection.
C++
bsd-2-clause
craigsapp/humlib,craigsapp/minHumdrum,craigsapp/minHumdrum,craigsapp/minHumdrum,craigsapp/humlib,craigsapp/humlib
6c4d35bcf10e6b31f858922c407f6fab07aa7ece
src/qtfirebaseanalytics.cpp
src/qtfirebaseanalytics.cpp
#include "qtfirebaseanalytics.h" #include <QGuiApplication> namespace analytics = ::firebase::analytics; QtFirebaseAnalytics *QtFirebaseAnalytics::self = nullptr; QtFirebaseAnalytics::QtFirebaseAnalytics(QObject* parent) : QObject(parent) { if(!self) { self = this; qDebug() << self << "::QtFirebaseAnalytics" << "singleton"; } _ready = false; _initializing = false; if(qFirebase->ready()) init(); else { connect(qFirebase,&QtFirebase::readyChanged, this, &QtFirebaseAnalytics::init); qFirebase->requestInit(); } } QtFirebaseAnalytics::~QtFirebaseAnalytics() { if(_ready) { qDebug() << self << "::~QtFirebaseAnalytics" << "shutting down"; analytics::Terminate(); _ready = false; self = nullptr; } } bool QtFirebaseAnalytics::checkInstance(const char *function) { bool b = (QtFirebaseAnalytics::self != nullptr); if (!b) qWarning("QtFirebaseAnalytics::%s: Please instantiate the QtFirebaseAnalytics object first", function); return b; } void QtFirebaseAnalytics::setUserProperty(const QString &propertyName, const QString &propertyValue) { if(!_ready) { qDebug() << this << "::setUserProperty native part not ready"; return; } qDebug() << this << "::setUserProperty" << propertyName << ":" << propertyValue; analytics::SetUserProperty(propertyName.toLatin1().constData(), propertyValue.toLatin1().constData()); } void QtFirebaseAnalytics::setCurrentScreen(const QString &screenName, const QString &screenClass) { if(!_ready) { qDebug() << this << "::setCurrentScreen native part not ready"; return; } qDebug() << this << "::setCurrentScreen" << screenName << ":" << screenClass ; analytics::SetCurrentScreen(screenName.toLatin1().constData(), screenClass.toLatin1().constData()); } void QtFirebaseAnalytics::logEvent(const QString &name) { if(!_ready) { qDebug() << this << "::logEvent native part not ready"; return; } qDebug() << this << "::logEvent" << name << "logging (no parameters)"; analytics::LogEvent(name.toUtf8().constData()); } void QtFirebaseAnalytics::logEvent(const QString &name, const QString &parameterName, const QString &parameterValue) { if(!_ready) { qDebug() << this << "::logEvent native part not ready"; return; } qDebug() << this << "::logEvent" << name << "logging string parameter" << parameterName << ":" << parameterValue; analytics::LogEvent(name.toUtf8().constData(), parameterName.toUtf8().constData(),parameterValue.toUtf8().constData()); } void QtFirebaseAnalytics::logEvent(const QString &name, const QString &parameterName, const double parameterValue) { if(!_ready) { qDebug() << this << "::logEvent native part not ready"; return; } qDebug() << this << "::logEvent" << name << "logging double parameter" << parameterName << ":" << parameterValue; analytics::LogEvent(name.toUtf8().constData(), parameterName.toUtf8().constData(),parameterValue); } void QtFirebaseAnalytics::logEvent(const QString &name, const QString &parameterName, const int parameterValue) { if(!_ready) { qDebug() << this << "::logEvent native part not ready"; return; } qDebug() << this << "::logEvent" << name << "logging int parameter" << parameterName << ":" << parameterValue; analytics::LogEvent(name.toUtf8().constData(), parameterName.toUtf8().constData(),parameterValue); } void QtFirebaseAnalytics::logEvent(const QString &name, const QVariantMap &bundle) { if(!_ready) { qDebug() << this << "::logEvent native part not ready"; return; } analytics::Parameter *parameters = new analytics::Parameter[bundle.size()]; QByteArrayList keys; QByteArrayList strings; QMapIterator<QString, QVariant> i(bundle); int index = 0; while (i.hasNext()) { i.next(); keys.append(i.key().toUtf8()); QString eventKey = i.key(); QVariant variant = i.value(); if(variant.type() == QVariant::Type(QMetaType::Int)) { parameters[index] = analytics::Parameter(keys.at(index).constData(), variant.toInt()); qDebug() << this << "::logEvent" << "bundle parameter" << eventKey << ":" << variant.toInt(); } else if(variant.type() == QVariant::Type(QMetaType::Double)) { parameters[index] = analytics::Parameter(keys.at(index).constData(),variant.toDouble()); qDebug() << this << "::logEvent" << "bundle parameter" << eventKey << ":" << variant.toDouble(); } else if(variant.type() == QVariant::Type(QMetaType::QString)) { strings.append(variant.toString().toUtf8()); parameters[index] = analytics::Parameter(keys.at(index).constData(), strings.at(strings.size()-1).constData()); qDebug() << this << "::logEvent" << "bundle parameter" << eventKey << ":" << strings.at(strings.size()-1); } else { qWarning() << this << "::logEvent" << "bundle parameter" << eventKey << "has unsupported data type. Sending empty strings"; parameters[index] = analytics::Parameter("", ""); } index++; } qDebug() << this << "::logEvent" << "logging" << "bundle" << name; analytics::LogEvent(name.toUtf8().constData(), parameters, bundle.size()); delete[] parameters; parameters = 0; } QVariantList QtFirebaseAnalytics::userProperties() const { return _userProperties; } void QtFirebaseAnalytics::setUserProperties(const QVariantList &userProperties) { if(!_ready) { qDebug() << this << "::setUserProperties native part not ready"; return; } if (_userProperties != userProperties) { _userProperties = userProperties; if(_userProperties.size() > 25) { } unsigned index = 0; for (QVariantList::iterator j = _userProperties.begin(); j != _userProperties.end(); j++) { if((*j).canConvert<QVariantMap>()) { QVariantMap map = (*j).toMap(); if(!map.isEmpty()) { if(map.first().canConvert<QString>()) { QString key = map.firstKey(); QString value = map.first().toString(); setUserProperty(key,value); } } } else { qWarning() << this << "::setUserProperties" << "wrong entry in userProperties list at index" << index; } index++; } emit userPropertiesChanged(); } } QString QtFirebaseAnalytics::userId() const { return _userId; } void QtFirebaseAnalytics::setUserId(const QString &userId) { if(!_ready) { qDebug() << this << "::setUserId native part not ready"; return; } QString aUserId = userId; if(aUserId.isEmpty()) { unsetUserId(); } if(aUserId.length() > 36) { aUserId = aUserId.left(36); qWarning() << this << "::setUserId" << "ID longer than allowed 36 chars" << "TRUNCATED to" << aUserId; } if(_userId != aUserId) { _userId = aUserId; analytics::SetUserId(_userId.toLatin1().constData()); qDebug() << this << "::setUserId sat to" << _userId; emit userIdChanged(); } } void QtFirebaseAnalytics::unsetUserId() { if(!_ready) { qDebug() << this << "::unsetUserId native part not ready"; return; } if(!_userId.isEmpty()) { _userId.clear(); analytics::SetUserId(NULL); emit userIdChanged(); } } unsigned int QtFirebaseAnalytics::sessionTimeout() const { return _sessionTimeout; } void QtFirebaseAnalytics::setSessionTimeout(unsigned int sessionTimeout) { if(_sessionTimeout != sessionTimeout) { _sessionTimeout = sessionTimeout; emit sessionTimeoutChanged(); } } bool QtFirebaseAnalytics::ready() { return _ready; } void QtFirebaseAnalytics::setReady(bool ready) { if (_ready != ready) { _ready = ready; qDebug() << self << "::setReady" << ready; emit readyChanged(); } } bool QtFirebaseAnalytics::enabled() { return _enabled; } void QtFirebaseAnalytics::setEnabled(bool enabled) { if(!_ready) { qDebug() << this << "::setEnabled native part not ready"; return; } if (_enabled != enabled) { analytics::SetAnalyticsCollectionEnabled(enabled); _enabled = enabled; qDebug() << self << "::setEnabled" << enabled; emit enabledChanged(); } } unsigned int QtFirebaseAnalytics::minimumSessionDuration() { return _minimumSessionDuration; } void QtFirebaseAnalytics::setMinimumSessionDuration(unsigned int minimumSessionDuration) { if(!_ready) { qDebug() << this << "::setMinimumSessionDuration native part not ready"; return; } if (_minimumSessionDuration != minimumSessionDuration) { analytics::SetMinimumSessionDuration(minimumSessionDuration); _minimumSessionDuration = minimumSessionDuration; qDebug() << self << "::setMinimumSessionDuration" << minimumSessionDuration; emit minimumSessionDurationChanged(); } } void QtFirebaseAnalytics::init() { if(!qFirebase->ready()) { qDebug() << self << "::init" << "base not ready"; return; } if(!_ready && !_initializing) { _initializing = true; analytics::Initialize(*qFirebase->firebaseApp()); qDebug() << self << "::init" << "native initialized"; _initializing = false; setReady(true); } }
#include "qtfirebaseanalytics.h" #include <QGuiApplication> namespace analytics = ::firebase::analytics; QtFirebaseAnalytics *QtFirebaseAnalytics::self = nullptr; QtFirebaseAnalytics::QtFirebaseAnalytics(QObject* parent) : QObject(parent) { if(!self) { self = this; qDebug() << self << "::QtFirebaseAnalytics" << "singleton"; } _ready = false; _initializing = false; if(qFirebase->ready()) init(); else { connect(qFirebase,&QtFirebase::readyChanged, this, &QtFirebaseAnalytics::init); qFirebase->requestInit(); } } QtFirebaseAnalytics::~QtFirebaseAnalytics() { if(_ready) { qDebug() << self << "::~QtFirebaseAnalytics" << "shutting down"; analytics::Terminate(); _ready = false; self = nullptr; } } bool QtFirebaseAnalytics::checkInstance(const char *function) { bool b = (QtFirebaseAnalytics::self != nullptr); if (!b) qWarning("QtFirebaseAnalytics::%s: Please instantiate the QtFirebaseAnalytics object first", function); return b; } void QtFirebaseAnalytics::setUserProperty(const QString &propertyName, const QString &propertyValue) { if(!_ready) { qDebug() << this << "::setUserProperty native part not ready"; return; } qDebug() << this << "::setUserProperty" << propertyName << ":" << propertyValue; analytics::SetUserProperty(propertyName.toLatin1().constData(), propertyValue.toLatin1().constData()); } void QtFirebaseAnalytics::setCurrentScreen(const QString &screenName, const QString &screenClass) { if(!_ready) { qDebug() << this << "::setCurrentScreen native part not ready"; return; } qDebug() << this << "::setCurrentScreen" << screenName << ":" << screenClass ; analytics::SetCurrentScreen(screenName.toLatin1().constData(), screenClass.toLatin1().constData()); } void QtFirebaseAnalytics::logEvent(const QString &name) { if(!_ready) { qDebug() << this << "::logEvent native part not ready"; return; } qDebug() << this << "::logEvent" << name << "logging (no parameters)"; analytics::LogEvent(name.toUtf8().constData()); } void QtFirebaseAnalytics::logEvent(const QString &name, const QString &parameterName, const QString &parameterValue) { if(!_ready) { qDebug() << this << "::logEvent native part not ready"; return; } qDebug() << this << "::logEvent" << name << "logging string parameter" << parameterName << ":" << parameterValue; analytics::LogEvent(name.toUtf8().constData(), parameterName.toUtf8().constData(),parameterValue.toUtf8().constData()); } void QtFirebaseAnalytics::logEvent(const QString &name, const QString &parameterName, const double parameterValue) { if(!_ready) { qDebug() << this << "::logEvent native part not ready"; return; } qDebug() << this << "::logEvent" << name << "logging double parameter" << parameterName << ":" << parameterValue; analytics::LogEvent(name.toUtf8().constData(), parameterName.toUtf8().constData(),parameterValue); } void QtFirebaseAnalytics::logEvent(const QString &name, const QString &parameterName, const int parameterValue) { if(!_ready) { qDebug() << this << "::logEvent native part not ready"; return; } qDebug() << this << "::logEvent" << name << "logging int parameter" << parameterName << ":" << parameterValue; analytics::LogEvent(name.toUtf8().constData(), parameterName.toUtf8().constData(),parameterValue); } void QtFirebaseAnalytics::logEvent(const QString &name, const QVariantMap &bundle) { if(!_ready) { qDebug() << this << "::logEvent native part not ready"; return; } analytics::Parameter *parameters = new analytics::Parameter[bundle.size()]; QByteArrayList keys; QByteArrayList strings; QMapIterator<QString, QVariant> i(bundle); int index = 0; while (i.hasNext()) { i.next(); keys.append(i.key().toUtf8()); QString eventKey = i.key(); QVariant variant = i.value(); if(variant.type() == QVariant::Type(QMetaType::Int)) { parameters[index] = analytics::Parameter(keys.at(index).constData(), variant.toInt()); qDebug() << this << "::logEvent" << "bundle parameter" << eventKey << ":" << variant.toInt(); } else if(variant.type() == QVariant::Type(QMetaType::Double)) { parameters[index] = analytics::Parameter(keys.at(index).constData(),variant.toDouble()); qDebug() << this << "::logEvent" << "bundle parameter" << eventKey << ":" << variant.toDouble(); } else if(variant.type() == QVariant::Type(QMetaType::QString)) { strings.append(variant.toString().toUtf8()); parameters[index] = analytics::Parameter(keys.at(index).constData(), strings.at(strings.size()-1).constData()); qDebug() << this << "::logEvent" << "bundle parameter" << eventKey << ":" << strings.at(strings.size()-1); } else { qWarning() << this << "::logEvent" << "bundle parameter" << eventKey << "has unsupported data type. Sending empty strings"; parameters[index] = analytics::Parameter("", ""); } index++; } qDebug() << this << "::logEvent" << "logging" << "bundle" << name; analytics::LogEvent(name.toUtf8().constData(), parameters, static_cast<size_t>(bundle.size())); delete[] parameters; parameters = nullptr; } QVariantList QtFirebaseAnalytics::userProperties() const { return _userProperties; } void QtFirebaseAnalytics::setUserProperties(const QVariantList &userProperties) { if(!_ready) { qDebug() << this << "::setUserProperties native part not ready"; return; } if (_userProperties != userProperties) { _userProperties = userProperties; if(_userProperties.size() > 25) { } unsigned index = 0; for (QVariantList::iterator j = _userProperties.begin(); j != _userProperties.end(); j++) { if((*j).canConvert<QVariantMap>()) { QVariantMap map = (*j).toMap(); if(!map.isEmpty()) { if(map.first().canConvert<QString>()) { QString key = map.firstKey(); QString value = map.first().toString(); setUserProperty(key,value); } } } else { qWarning() << this << "::setUserProperties" << "wrong entry in userProperties list at index" << index; } index++; } emit userPropertiesChanged(); } } QString QtFirebaseAnalytics::userId() const { return _userId; } void QtFirebaseAnalytics::setUserId(const QString &userId) { if(!_ready) { qDebug() << this << "::setUserId native part not ready"; return; } QString aUserId = userId; if(aUserId.isEmpty()) { unsetUserId(); } if(aUserId.length() > 36) { aUserId = aUserId.left(36); qWarning() << this << "::setUserId" << "ID longer than allowed 36 chars" << "TRUNCATED to" << aUserId; } if(_userId != aUserId) { _userId = aUserId; analytics::SetUserId(_userId.toLatin1().constData()); qDebug() << this << "::setUserId sat to" << _userId; emit userIdChanged(); } } void QtFirebaseAnalytics::unsetUserId() { if(!_ready) { qDebug() << this << "::unsetUserId native part not ready"; return; } if(!_userId.isEmpty()) { _userId.clear(); analytics::SetUserId(nullptr); emit userIdChanged(); } } unsigned int QtFirebaseAnalytics::sessionTimeout() const { return _sessionTimeout; } void QtFirebaseAnalytics::setSessionTimeout(unsigned int sessionTimeout) { if(_sessionTimeout != sessionTimeout) { _sessionTimeout = sessionTimeout; emit sessionTimeoutChanged(); } } bool QtFirebaseAnalytics::ready() { return _ready; } void QtFirebaseAnalytics::setReady(bool ready) { if (_ready != ready) { _ready = ready; qDebug() << self << "::setReady" << ready; emit readyChanged(); } } bool QtFirebaseAnalytics::enabled() { return _enabled; } void QtFirebaseAnalytics::setEnabled(bool enabled) { if(!_ready) { qDebug() << this << "::setEnabled native part not ready"; return; } if (_enabled != enabled) { analytics::SetAnalyticsCollectionEnabled(enabled); _enabled = enabled; qDebug() << self << "::setEnabled" << enabled; emit enabledChanged(); } } unsigned int QtFirebaseAnalytics::minimumSessionDuration() { return _minimumSessionDuration; } void QtFirebaseAnalytics::setMinimumSessionDuration(unsigned int minimumSessionDuration) { if(!_ready) { qDebug() << this << "::setMinimumSessionDuration native part not ready"; return; } if (_minimumSessionDuration != minimumSessionDuration) { analytics::SetMinimumSessionDuration(minimumSessionDuration); _minimumSessionDuration = minimumSessionDuration; qDebug() << self << "::setMinimumSessionDuration" << minimumSessionDuration; emit minimumSessionDurationChanged(); } } void QtFirebaseAnalytics::init() { if(!qFirebase->ready()) { qDebug() << self << "::init" << "base not ready"; return; } if(!_ready && !_initializing) { _initializing = true; analytics::Initialize(*qFirebase->firebaseApp()); qDebug() << self << "::init" << "native initialized"; _initializing = false; setReady(true); } }
Fix a few warnings. Use nullptr
Fix a few warnings. Use nullptr
C++
mit
Larpon/QtFirebase,Larpon/QtFirebase,Larpon/QtFirebase
b1b7737ae19020e305a175ad700404c67f8c6e1e
clipp/proxy.cpp
clipp/proxy.cpp
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS 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. ****************************************************************************/ /** * @file * @brief IronBee --- CLIPP Proxy Consumer Implementation * * @author Craig Forbes <[email protected]> */ #include "ironbee_config_auto.h" #include <sstream> #include "proxy.hpp" #include <boost/algorithm/string/replace.hpp> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <boost/scoped_array.hpp> using namespace std; using boost::asio::ip::tcp; namespace IronBee { namespace CLIPP { namespace { using namespace Input; void accept_handler(const boost::system::error_code& e) { if (e) { cout << "Error in accept handler" << endl; exit(1); } } class ProxyDelegate : public Delegate { public: stringstream to_origin; stringstream from_proxy; ProxyDelegate(const std::string& proxy_ip, uint16_t proxy_port, uint16_t listen_port) : m_client_sock(m_io_service), m_listener(m_io_service), m_origin_sock(m_io_service), m_proxy_ip(proxy_ip), m_proxy_port(proxy_port), m_listen_port(listen_port) { // nop } void read_data(tcp::socket& sock, stringstream& rstream, int timeout=5) { for (int i=0; i < (timeout * 10); ++i) { if (sock.available() > 0) { break; } usleep(100000); } while (sock.available() > 0) { boost::scoped_array<char> data(new char[8192]); boost::system::error_code error; size_t length = sock.read_some( boost::asio::buffer(data.get(), 8192), error); if (error == boost::asio::error::eof) { break; // Connection closed cleanly by peer. } else if (error) { BOOST_THROW_EXCEPTION( boost::system::system_error(error) ); } rstream.write(data.get(), length); } } void connection_opened(const ConnectionEvent& event) { tcp::endpoint origin_endpoint(tcp::v4(), m_listen_port); m_listener.open(origin_endpoint.protocol()); m_listener.set_option(boost::asio::socket_base::reuse_address(true)); m_listener.bind(origin_endpoint); m_listener.listen(); tcp::endpoint proxy_endpoint( boost::asio::ip::address::from_string(m_proxy_ip), m_proxy_port); m_client_sock.connect(proxy_endpoint); } void connection_closed(const NullEvent& event) { read_data(m_client_sock, from_proxy); if (m_origin_sock.is_open()) { m_origin_sock.close(); } m_client_sock.close(); } void request_started(const RequestEvent& event) { boost::asio::write(m_client_sock, boost::asio::buffer(event.raw.data, event.raw.length)); boost::asio::write(m_client_sock, boost::asio::buffer("\r\n", 2)); } void request_header(const HeaderEvent& event) { boost::asio::streambuf b; std::ostream out(&b); BOOST_FOREACH(const header_t& header, event.headers) { out << header.first.data << ": " << header.second.data << "\r\n"; } out << "\r\n"; boost::asio::write(m_client_sock, b); } void request_body(const DataEvent& event) { boost::asio::write(m_client_sock, boost::asio::buffer(event.data.data, event.data.length)); } void request_finished(NullEvent& event) { // This event may not occur, so do no work here. } void response_started(const ResponseEvent& event) { m_listener.async_accept(m_origin_sock, boost::bind(&accept_handler, boost::asio::placeholders::error)); // Retry for 5 seconds in 0.1 second intervals for (int i=0; i < 50 ; ++i) { m_io_service.poll(); if (m_origin_sock.is_open()) { break; } usleep(100000); } if (m_origin_sock.is_open()) { read_data(m_origin_sock, to_origin); boost::asio::streambuf b; std::ostream out(&b); out << event.raw.data << "\r\n"; boost::asio::write(m_origin_sock, b); } else { to_origin << "[ERROR: Failed Accepting Connection]"; } } void response_header(const HeaderEvent& event) { boost::asio::streambuf b; std::ostream out(&b); BOOST_FOREACH(const header_t& header, event.headers) { out << header.first.data << ": " << header.second.data << "\r\n"; } out << "\r\n"; if (m_origin_sock.is_open()) { boost::asio::write(m_origin_sock, b); } } void response_body(const DataEvent& event) { if (m_origin_sock.is_open()) { boost::asio::write(m_origin_sock, boost::asio::buffer(event.data.data, event.data.length)); } } void response_finished(const NullEvent& event) { // This event may not occur, so do no work here. } private: typedef boost::shared_ptr<tcp::socket> socket_ptr; boost::asio::io_service m_io_service; std::string m_proxy_ip; uint16_t m_proxy_port; uint16_t m_listen_port; tcp::socket m_client_sock; tcp::socket m_origin_sock; tcp::acceptor m_listener; }; } // anonymous namespace ProxyConsumer::ProxyConsumer(const std::string& proxy_host, uint16_t proxy_port, uint16_t listen_port) : m_proxy_host(proxy_host), m_proxy_port(proxy_port), m_listen_port(listen_port) { // nop } bool ProxyConsumer::operator()(const input_p& input) { if ( ! input ) { return true; } ProxyDelegate proxyer(m_proxy_host, m_proxy_port, m_listen_port); input->connection.dispatch(proxyer); cout << "Connection Id:" << input->id << endl; string outstr = proxyer.to_origin.str(); boost::algorithm::replace_all(outstr, "\\", "\\\\"); boost::algorithm::replace_all(outstr, "\n", "\\n"); boost::algorithm::replace_all(outstr, "\r", "\\r"); cout << "[" << input->id << "] Origin Request:" << outstr << endl; outstr = proxyer.from_proxy.str(); boost::algorithm::replace_all(outstr, "\\", "\\\\"); boost::algorithm::replace_all(outstr, "\n", "\\n"); boost::algorithm::replace_all(outstr, "\r", "\\r"); cout << "[" << input->id << "] Proxy Response:" << outstr << endl; return true; } } // CLIPP } // IronBee
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS 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. ****************************************************************************/ /** * @file * @brief IronBee --- CLIPP Proxy Consumer Implementation * * @author Craig Forbes <[email protected]> */ #include "ironbee_config_auto.h" #include <sstream> #include "proxy.hpp" #include <boost/algorithm/string/replace.hpp> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <boost/scoped_array.hpp> using namespace std; using boost::asio::ip::tcp; namespace IronBee { namespace CLIPP { namespace { using namespace Input; void accept_handler(const boost::system::error_code& e) { if (e) { cout << "Error in accept handler" << endl; exit(1); } } class ProxyDelegate : public Delegate { public: stringstream to_origin; stringstream from_proxy; ProxyDelegate(const std::string& proxy_ip, uint16_t proxy_port, uint16_t listen_port) : m_proxy_ip(proxy_ip), m_proxy_port(proxy_port), m_listen_port(listen_port), m_client_sock(m_io_service), m_origin_sock(m_io_service), m_listener(m_io_service) { // nop } void read_data(tcp::socket& sock, stringstream& rstream, int timeout=5) { for (int i=0; i < (timeout * 10); ++i) { if (sock.available() > 0) { break; } usleep(100000); } while (sock.available() > 0) { boost::scoped_array<char> data(new char[8192]); boost::system::error_code error; size_t length = sock.read_some( boost::asio::buffer(data.get(), 8192), error); if (error == boost::asio::error::eof) { break; // Connection closed cleanly by peer. } else if (error) { BOOST_THROW_EXCEPTION( boost::system::system_error(error) ); } rstream.write(data.get(), length); } } void connection_opened(const ConnectionEvent& event) { tcp::endpoint origin_endpoint(tcp::v4(), m_listen_port); m_listener.open(origin_endpoint.protocol()); m_listener.set_option(boost::asio::socket_base::reuse_address(true)); m_listener.bind(origin_endpoint); m_listener.listen(); tcp::endpoint proxy_endpoint( boost::asio::ip::address::from_string(m_proxy_ip), m_proxy_port); m_client_sock.connect(proxy_endpoint); } void connection_closed(const NullEvent& event) { read_data(m_client_sock, from_proxy); if (m_origin_sock.is_open()) { m_origin_sock.close(); } m_client_sock.close(); } void request_started(const RequestEvent& event) { boost::asio::write(m_client_sock, boost::asio::buffer(event.raw.data, event.raw.length)); boost::asio::write(m_client_sock, boost::asio::buffer("\r\n", 2)); } void request_header(const HeaderEvent& event) { boost::asio::streambuf b; std::ostream out(&b); BOOST_FOREACH(const header_t& header, event.headers) { out << header.first.data << ": " << header.second.data << "\r\n"; } out << "\r\n"; boost::asio::write(m_client_sock, b); } void request_body(const DataEvent& event) { boost::asio::write(m_client_sock, boost::asio::buffer(event.data.data, event.data.length)); } void request_finished(const NullEvent& event) { // This event may not occur, so do no work here. } void response_started(const ResponseEvent& event) { m_listener.async_accept(m_origin_sock, boost::bind(&accept_handler, boost::asio::placeholders::error)); // Retry for 5 seconds in 0.1 second intervals for (int i=0; i < 50 ; ++i) { m_io_service.poll(); if (m_origin_sock.is_open()) { break; } usleep(100000); } if (m_origin_sock.is_open()) { read_data(m_origin_sock, to_origin); boost::asio::streambuf b; std::ostream out(&b); out << event.raw.data << "\r\n"; boost::asio::write(m_origin_sock, b); } else { to_origin << "[ERROR: Failed Accepting Connection]"; } } void response_header(const HeaderEvent& event) { boost::asio::streambuf b; std::ostream out(&b); BOOST_FOREACH(const header_t& header, event.headers) { out << header.first.data << ": " << header.second.data << "\r\n"; } out << "\r\n"; if (m_origin_sock.is_open()) { boost::asio::write(m_origin_sock, b); } } void response_body(const DataEvent& event) { if (m_origin_sock.is_open()) { boost::asio::write(m_origin_sock, boost::asio::buffer(event.data.data, event.data.length)); } } void response_finished(const NullEvent& event) { // This event may not occur, so do no work here. } private: typedef boost::shared_ptr<tcp::socket> socket_ptr; boost::asio::io_service m_io_service; std::string m_proxy_ip; uint16_t m_proxy_port; uint16_t m_listen_port; tcp::socket m_client_sock; tcp::socket m_origin_sock; tcp::acceptor m_listener; }; } // anonymous namespace ProxyConsumer::ProxyConsumer(const std::string& proxy_host, uint16_t proxy_port, uint16_t listen_port) : m_proxy_host(proxy_host), m_proxy_port(proxy_port), m_listen_port(listen_port) { // nop } bool ProxyConsumer::operator()(const input_p& input) { if ( ! input ) { return true; } ProxyDelegate proxyer(m_proxy_host, m_proxy_port, m_listen_port); input->connection.dispatch(proxyer); cout << "Connection Id:" << input->id << endl; string outstr = proxyer.to_origin.str(); boost::algorithm::replace_all(outstr, "\\", "\\\\"); boost::algorithm::replace_all(outstr, "\n", "\\n"); boost::algorithm::replace_all(outstr, "\r", "\\r"); cout << "[" << input->id << "] Origin Request:" << outstr << endl; outstr = proxyer.from_proxy.str(); boost::algorithm::replace_all(outstr, "\\", "\\\\"); boost::algorithm::replace_all(outstr, "\n", "\\n"); boost::algorithm::replace_all(outstr, "\r", "\\r"); cout << "[" << input->id << "] Proxy Response:" << outstr << endl; return true; } } // CLIPP } // IronBee
Fix compile errors on modern C++ compilers.
Fix compile errors on modern C++ compilers.
C++
apache-2.0
b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,ironbee/ironbee,ironbee/ironbee,b1v1r/ironbee,ironbee/ironbee,ironbee/ironbee,b1v1r/ironbee,ironbee/ironbee,ironbee/ironbee,ironbee/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,b1v1r/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,b1v1r/ironbee
b903741cfc8ada22b5891359bcb518f6896da2ab
cnn/cnn/cnn.hpp
cnn/cnn/cnn.hpp
#ifndef CNN_HEADER #define CNN_HEADER #include <unordered_map> #include "util.hpp" #include "convolution.hpp" #include "maxpool.hpp" #include "fullconnect.hpp" #include "rbf.hpp" #include "eventpool.hpp" #define BUFSIZE (64 * 1024 * 1024) namespace cnn { class CNN { public: CNN(const std::string &xmlFileName, bool isQueueInOrder = true, const std::string &xclbinFile = "NONE") { this->isQueueInOrder = isQueueInOrder; // Parse the xml file. char *buf = new char[BUFSIZE]; fileToChar(xmlFileName, buf, BUFSIZE); rapidxml::xml_document<> doc; doc.parse<0>(buf); rapidxml::xml_node<> *root = doc.first_node(); // Get the kernel file name. std::string kernelFileName(root->first_node("kernelFileName")->value()); // Get the input size. size_t inSize = getSizeT(root, "inSize"); // Get the queue barrier. queueBarrier = getSizeT(root, "queueBarrier"); // Initialize the OpenCL. initOpenCL(isQueueInOrder, inSize); // For every layer. bool isFront = true; for (rapidxml::xml_node<> *layer = root->first_node("layer"); layer; layer = layer->next_sibling("layer")) { Flag flag = INNER; if (isFront) { flag |= FRONT; isFront = false; } if (!(layer->next_sibling())) { flag |= BACK; } layers.push_back(createLayer(layer, xclbinFile != "NONE", flag)); } delete[] buf; } ~CNN() { for (int i = 0; i < layers.size(); ++i) { delete layers[i]; } for (auto iter = programs.begin(); iter != programs.end(); ++iter) { clReleaseProgram(iter->second); } clReleaseCommandQueue(queue); clReleaseContext(context); } // Forward with CPU. unsigned long long forwardCPU(const vec &in) { unsigned long long totalTime = layers[0]->forwardCPU(in); for (size_t i = 1; i < layers.size(); ++i) { totalTime += layers[i]->forwardCPU(layers[i - 1]->out); } return totalTime; } // Forward with OpenCL. unsigned long long forwardCL(const vec &in) { // Prepare the input cl_mem. cl_int err; err = clEnqueueWriteBuffer(queue, clIn, CL_TRUE, 0, in.size() * sizeof(cl_float), (void *)&in[0], 0, NULL, NULL); handleError(err, "Failed copy input buffer. "); // Enqueue the first kernel. unsigned long long totalTime = layers[0]->forwardCL(queue); for (size_t i = 1; i < layers.size(); ++i) { totalTime += layers[i]->forwardCL(queue); } // Get the result to the last layer's out vec. err = clEnqueueReadBuffer(queue, layers[layers.size() - 1]->clOut, CL_TRUE, 0, getOutSize() * sizeof(cl_float), &(layers[layers.size() - 1]->out[0]), 0, NULL, NULL); return totalTime; } // Forward more than one input with in order command queue. std::vector<cl_event> forwardCLBatch(const vec &in, vec &out, size_t n, double *averageTime) { // Make sure that input size is correct. size_t inSize = getInSize(); size_t outSize = getOutSize(); size_t eventSize = layers.size() + 2; if (in.size() != inSize * n) { std::cerr << "Wrong input size! " << std::endl; exit(-2); } clock_t start = clock(), diff; // Reserve the output buffer. out.resize(outSize * n); // Reserve the event buffer. // One event for each layer plus two events for IO. std::vector<cl_event> events(n * eventSize); // For OpenCL error. cl_int err; for (size_t i = 0; i < n; ++i) { // Prepare the input cl_mem. err = clEnqueueWriteBuffer(queue, clIn, CL_FALSE, 0, inSize * sizeof(cl_float), (void *)&in[i * inSize], i == 0 ? 0 : 1, i == 0 ? NULL : &events[(i - 1) * eventSize], &events[i * eventSize]); handleError(err, "Failed copy input buffer. "); // For each layer. for (size_t l = 0; l < layers.size(); ++l) { err = clEnqueueNDRangeKernel(queue, layers[l]->kernel, 3, NULL, layers[l]->global, layers[l]->workGroupSize, 1, &events[i * eventSize + l], &events[i * eventSize + l + 1]); handleError(err, "Failed enqueuing kernel. "); } // Get the output. err = clEnqueueReadBuffer(queue, layers[layers.size() - 1]->clOut, CL_FALSE, 0, outSize * sizeof(cl_float), &out[i * outSize], 1, &events[i * eventSize + layers.size()], &events[i * eventSize + layers.size() + 1]); handleError(err, "Failed enqueuing reading buffer. "); // Wait for the command queue. if (i % queueBarrier == queueBarrier - 1) { err = clFinish(queue); handleError(err, "Failed waiting for event. "); } } diff = clock() - start; *averageTime = (double)diff / (double)CLOCKS_PER_SEC / (double)n; std::cout << "Average time: " << *averageTime << "s" << std::endl; return events; } // Forward with pipelined command queue. std::vector<cl_event> forwardCLPipeline(const vec &in, vec &out, size_t n, double *averageTime) { // Check if the command queue supports out of order queue. if (isQueueInOrder) { std::cout << "Warning: using an in order command queue for pipeline cnn!" << std::endl; } // Make sure that input size is correct. size_t inSize = getInSize(); size_t outSize = getOutSize(); size_t eventSize = layers.size() + 2; if (in.size() != inSize * n) { std::cerr << "Wrong input size! " << std::endl; exit(-2); } // Initialize the event pool. EventPool events(layers.size() + 2, n); clock_t start = clock(), diff; // Reserve the output buffer. out.resize(outSize * n); // For OpenCL error. cl_int err; // Temporary holder for returned event. cl_event event; uint32_t len; cl_event *eventList; for (size_t i = 0; i < n; ++i) { // Prepare the input cl_mem. eventList = events.getDependentEventList(0, i, &len); err = clEnqueueWriteBuffer(queue, clIn, CL_FALSE, 0, inSize * sizeof(cl_float), (void *)&in[i * inSize], len, eventList, &event); handleError(err, "Failed copy input buffer. "); events.pushEvent(0, i, event); // For each layer. for (size_t l = 0; l < layers.size(); ++l) { eventList = events.getDependentEventList(l + 1, i, &len); err = clEnqueueNDRangeKernel(queue, layers[l]->kernel, 3, NULL, layers[l]->global, layers[l]->workGroupSize, len, eventList, &event); handleError(err, "Failed enqueuing kernel. "); events.pushEvent(l + 1, i, event); } // Get the output. eventList = events.getDependentEventList(layers.size() + 1, i, &len); err = clEnqueueReadBuffer(queue, layers[layers.size() - 1]->clOut, CL_FALSE, 0, outSize * sizeof(cl_float), &out[i * outSize], len, eventList, &event); handleError(err, "Failed enqueuing reading buffer. "); events.pushEvent(layers.size() + 1, i, event); // Wait for the command queue. if (i % queueBarrier == queueBarrier - 1) { err = clFinish(queue); handleError(err, "Failed waiting for event. "); } } diff = clock() - start; *averageTime = (double)diff / (double)CLOCKS_PER_SEC / (double)n; std::cout << "Pipelined average time: " << *averageTime << "s" << std::endl; return events.sort(); } // For OpenCL. cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue queue; std::unordered_map<std::string, cl_program> programs; cl_mem clIn; size_t queueBarrier; bool isQueueInOrder; std::vector<Layer *> layers; size_t getInSize() const { return layers[0]->iWidth * layers[0]->iHeight * layers[0]->iDepth; } size_t getOutSize() const { size_t last = layers.size() - 1; return layers[last]->out.size(); } const vec &getOut() const { return layers[layers.size() - 1]->out; } private: void initOpenCL(bool isQueueInOrder, size_t inSize) { cl_int err; // Choose the first platform. err = clGetPlatformIDs(1, &platform, NULL); // Choose the first device. err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &device, NULL); printDeviceInfo(std::cout, device); cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 }; context = clCreateContext( properties, 1, &device, NULL, NULL, &err); handleError(err, "Failed creating context. "); clRetainContext(context); queue = clCreateCommandQueue( context, device, CL_QUEUE_PROFILING_ENABLE | (isQueueInOrder ? 0 : CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE), &err); handleError(err, "Failed creating command queue. "); clRetainCommandQueue(queue); clIn = clCreateBuffer( context, CL_MEM_READ_ONLY, inSize * sizeof(cl_float), NULL, &err); handleError(err, "Failed creating clIn"); err = clRetainMemObject(clIn); handleError(err, "Failed retaining clIn"); } // Create a layer. Layer *createLayer(rapidxml::xml_node<> *root, bool isBinary, Flag flag) { LayerParam params; params.flag = flag; // Get the parameters for the convolutional layer. params.iWidth = getSizeT(root, "iWidth"); params.iHeight = getSizeT(root, "iHeight"); params.iDepth = getSizeT(root, "iDepth"); params.oWidth = getSizeT(root, "oWidth"); params.oHeight = getSizeT(root, "oHeight"); params.oDepth = getSizeT(root, "oDepth"); params.oWidthTile = getSizeT(root, "oWidthTile"); params.oHeightTile = getSizeT(root, "oHeightTile"); params.oDepthTile = getSizeT(root, "oDepthTile"); params.iDepthTile = getSizeT(root, "iDepthTile"); params.kernelSize = getSizeT(root, "kernelSize"); // Get the kernel name. params.kernelName = getString(root, "kernelName"); // Get the work group size. std::vector<size_t> workGroupSize; getAllItem(root->first_node("workGroupSize"), workGroupSize); for (size_t i = 0; i < workGroupSize.size(); ++i) { params.workGroupSize[i] = workGroupSize[i]; } // Create the weight vector. cnn::vec weight; getAllItem(root->first_node("weight"), weight); // Create the offset vector. cnn::vec offset; getAllItem(root->first_node("offset"), offset); // Get the program. cl_program program; if (isBinary) { std::string xclbinFileName = getString(root, "xclbinFileName"); auto iter = programs.find(xclbinFileName); if (iter != programs.end()) { program = iter->second; } else { program = buildProgramFromBinary(xclbinFileName.c_str(), context, device); cl_int err = clRetainProgram(program); handleError(err, "Failed retaining program. "); programs.insert(std::make_pair(xclbinFileName, program)); } } else { std::string kernelFileName = getString(root, "kernelFileName"); auto iter = programs.find(kernelFileName); if (iter != programs.end()) { program = iter->second; } else { program = buildProgramFromSource(kernelFileName.c_str(), context, device); cl_int err = clRetainProgram(program); handleError(err, "Failed retaining program. "); programs.insert(std::make_pair(kernelFileName, program)); } } std::string type = getString(root, "type"); if (type == "conv") { return new cnn::ConvolutionLayer(params, weight, offset, context, program, clIn ); } else if (type == "pool") { return new cnn::MaxPoolLayer(params, weight, offset, context, program, clIn ); } else if (type == "full") { return new cnn::FullConnectLayer(params, weight, offset, context, program, clIn ); } else if (type == "rbf") { return new cnn::RBFLayer(params, weight, offset, context, program, clIn ); } else { std::cerr << "createLayer: Unsupported layer: " << type << std::endl; exit(-1); } } }; } #endif
#ifndef CNN_HEADER #define CNN_HEADER #include <map> #include "util.hpp" #include "convolution.hpp" #include "maxpool.hpp" #include "fullconnect.hpp" #include "rbf.hpp" #include "eventpool.hpp" #define BUFSIZE (64 * 1024 * 1024) namespace cnn { class CNN { public: CNN(const std::string &xmlFileName, bool isQueueInOrder = true, const std::string &xclbinFile = "NONE") { this->isQueueInOrder = isQueueInOrder; // Parse the xml file. char *buf = new char[BUFSIZE]; fileToChar(xmlFileName, buf, BUFSIZE); rapidxml::xml_document<> doc; doc.parse<0>(buf); rapidxml::xml_node<> *root = doc.first_node(); // Get the kernel file name. std::string kernelFileName(root->first_node("kernelFileName")->value()); // Get the input size. size_t inSize = getSizeT(root, "inSize"); // Get the queue barrier. queueBarrier = getSizeT(root, "queueBarrier"); // Initialize the OpenCL. initOpenCL(isQueueInOrder, inSize); // For every layer. bool isFront = true; for (rapidxml::xml_node<> *layer = root->first_node("layer"); layer; layer = layer->next_sibling("layer")) { Flag flag = INNER; if (isFront) { flag |= FRONT; isFront = false; } if (!(layer->next_sibling())) { flag |= BACK; } layers.push_back(createLayer(layer, xclbinFile != "NONE", flag)); } delete[] buf; } ~CNN() { for (int i = 0; i < layers.size(); ++i) { delete layers[i]; } for (auto iter = programs.begin(); iter != programs.end(); ++iter) { clReleaseProgram(iter->second); } clReleaseCommandQueue(queue); clReleaseContext(context); } // Forward with CPU. unsigned long long forwardCPU(const vec &in) { unsigned long long totalTime = layers[0]->forwardCPU(in); for (size_t i = 1; i < layers.size(); ++i) { totalTime += layers[i]->forwardCPU(layers[i - 1]->out); } return totalTime; } // Forward with OpenCL. unsigned long long forwardCL(const vec &in) { // Prepare the input cl_mem. cl_int err; err = clEnqueueWriteBuffer(queue, clIn, CL_TRUE, 0, in.size() * sizeof(cl_float), (void *)&in[0], 0, NULL, NULL); handleError(err, "Failed copy input buffer. "); // Enqueue the first kernel. unsigned long long totalTime = layers[0]->forwardCL(queue); for (size_t i = 1; i < layers.size(); ++i) { totalTime += layers[i]->forwardCL(queue); } // Get the result to the last layer's out vec. err = clEnqueueReadBuffer(queue, layers[layers.size() - 1]->clOut, CL_TRUE, 0, getOutSize() * sizeof(cl_float), &(layers[layers.size() - 1]->out[0]), 0, NULL, NULL); return totalTime; } // Forward more than one input with in order command queue. std::vector<cl_event> forwardCLBatch(const vec &in, vec &out, size_t n, double *averageTime) { // Make sure that input size is correct. size_t inSize = getInSize(); size_t outSize = getOutSize(); size_t eventSize = layers.size() + 2; if (in.size() != inSize * n) { std::cerr << "Wrong input size! " << std::endl; exit(-2); } clock_t start = clock(), diff; // Reserve the output buffer. out.resize(outSize * n); // Reserve the event buffer. // One event for each layer plus two events for IO. std::vector<cl_event> events(n * eventSize); // For OpenCL error. cl_int err; for (size_t i = 0; i < n; ++i) { // Prepare the input cl_mem. err = clEnqueueWriteBuffer(queue, clIn, CL_FALSE, 0, inSize * sizeof(cl_float), (void *)&in[i * inSize], i == 0 ? 0 : 1, i == 0 ? NULL : &events[(i - 1) * eventSize], &events[i * eventSize]); handleError(err, "Failed copy input buffer. "); // For each layer. for (size_t l = 0; l < layers.size(); ++l) { err = clEnqueueNDRangeKernel(queue, layers[l]->kernel, 3, NULL, layers[l]->global, layers[l]->workGroupSize, 1, &events[i * eventSize + l], &events[i * eventSize + l + 1]); handleError(err, "Failed enqueuing kernel. "); } // Get the output. err = clEnqueueReadBuffer(queue, layers[layers.size() - 1]->clOut, CL_FALSE, 0, outSize * sizeof(cl_float), &out[i * outSize], 1, &events[i * eventSize + layers.size()], &events[i * eventSize + layers.size() + 1]); handleError(err, "Failed enqueuing reading buffer. "); // Wait for the command queue. if (i % queueBarrier == queueBarrier - 1) { err = clFinish(queue); handleError(err, "Failed waiting for event. "); } } diff = clock() - start; *averageTime = (double)diff / (double)CLOCKS_PER_SEC / (double)n; std::cout << "Average time: " << *averageTime << "s" << std::endl; return events; } // Forward with pipelined command queue. std::vector<cl_event> forwardCLPipeline(const vec &in, vec &out, size_t n, double *averageTime) { // Check if the command queue supports out of order queue. if (isQueueInOrder) { std::cout << "Warning: using an in order command queue for pipeline cnn!" << std::endl; } // Make sure that input size is correct. size_t inSize = getInSize(); size_t outSize = getOutSize(); size_t eventSize = layers.size() + 2; if (in.size() != inSize * n) { std::cerr << "Wrong input size! " << std::endl; exit(-2); } // Initialize the event pool. EventPool events(layers.size() + 2, n); clock_t start = clock(), diff; // Reserve the output buffer. out.resize(outSize * n); // For OpenCL error. cl_int err; // Temporary holder for returned event. cl_event event; uint32_t len; cl_event *eventList; for (size_t i = 0; i < n; ++i) { // Prepare the input cl_mem. eventList = events.getDependentEventList(0, i, &len); err = clEnqueueWriteBuffer(queue, clIn, CL_FALSE, 0, inSize * sizeof(cl_float), (void *)&in[i * inSize], len, eventList, &event); handleError(err, "Failed copy input buffer. "); events.pushEvent(0, i, event); // For each layer. for (size_t l = 0; l < layers.size(); ++l) { eventList = events.getDependentEventList(l + 1, i, &len); err = clEnqueueNDRangeKernel(queue, layers[l]->kernel, 3, NULL, layers[l]->global, layers[l]->workGroupSize, len, eventList, &event); handleError(err, "Failed enqueuing kernel. "); events.pushEvent(l + 1, i, event); } // Get the output. eventList = events.getDependentEventList(layers.size() + 1, i, &len); err = clEnqueueReadBuffer(queue, layers[layers.size() - 1]->clOut, CL_FALSE, 0, outSize * sizeof(cl_float), &out[i * outSize], len, eventList, &event); handleError(err, "Failed enqueuing reading buffer. "); events.pushEvent(layers.size() + 1, i, event); // Wait for the command queue. if (i % queueBarrier == queueBarrier - 1) { err = clFinish(queue); handleError(err, "Failed waiting for event. "); } } diff = clock() - start; *averageTime = (double)diff / (double)CLOCKS_PER_SEC / (double)n; std::cout << "Pipelined average time: " << *averageTime << "s" << std::endl; return events.sort(); } // For OpenCL. cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue queue; std::map<std::string, cl_program> programs; cl_mem clIn; size_t queueBarrier; bool isQueueInOrder; std::vector<Layer *> layers; size_t getInSize() const { return layers[0]->iWidth * layers[0]->iHeight * layers[0]->iDepth; } size_t getOutSize() const { size_t last = layers.size() - 1; return layers[last]->out.size(); } const vec &getOut() const { return layers[layers.size() - 1]->out; } private: void initOpenCL(bool isQueueInOrder, size_t inSize) { cl_int err; // Choose the first platform. err = clGetPlatformIDs(1, &platform, NULL); // Choose the first device. err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &device, NULL); printDeviceInfo(std::cout, device); cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 }; context = clCreateContext( properties, 1, &device, NULL, NULL, &err); handleError(err, "Failed creating context. "); clRetainContext(context); queue = clCreateCommandQueue( context, device, CL_QUEUE_PROFILING_ENABLE | (isQueueInOrder ? 0 : CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE), &err); handleError(err, "Failed creating command queue. "); clRetainCommandQueue(queue); clIn = clCreateBuffer( context, CL_MEM_READ_ONLY, inSize * sizeof(cl_float), NULL, &err); handleError(err, "Failed creating clIn"); err = clRetainMemObject(clIn); handleError(err, "Failed retaining clIn"); } // Create a layer. Layer *createLayer(rapidxml::xml_node<> *root, bool isBinary, Flag flag) { LayerParam params; params.flag = flag; // Get the parameters for the convolutional layer. params.iWidth = getSizeT(root, "iWidth"); params.iHeight = getSizeT(root, "iHeight"); params.iDepth = getSizeT(root, "iDepth"); params.oWidth = getSizeT(root, "oWidth"); params.oHeight = getSizeT(root, "oHeight"); params.oDepth = getSizeT(root, "oDepth"); params.oWidthTile = getSizeT(root, "oWidthTile"); params.oHeightTile = getSizeT(root, "oHeightTile"); params.oDepthTile = getSizeT(root, "oDepthTile"); params.iDepthTile = getSizeT(root, "iDepthTile"); params.kernelSize = getSizeT(root, "kernelSize"); // Get the kernel name. params.kernelName = getString(root, "kernelName"); // Get the work group size. std::vector<size_t> workGroupSize; getAllItem(root->first_node("workGroupSize"), workGroupSize); for (size_t i = 0; i < workGroupSize.size(); ++i) { params.workGroupSize[i] = workGroupSize[i]; } // Create the weight vector. cnn::vec weight; getAllItem(root->first_node("weight"), weight); // Create the offset vector. cnn::vec offset; getAllItem(root->first_node("offset"), offset); // Get the program. cl_program program; if (isBinary) { std::string xclbinFileName = getString(root, "xclbinFileName"); std::map<std::string, cl_program>::iterator iter = programs.find(xclbinFileName); if (iter != programs.end()) { program = iter->second; } else { program = buildProgramFromBinary(xclbinFileName.c_str(), context, device); cl_int err = clRetainProgram(program); handleError(err, "Failed retaining program. "); programs.insert(std::pair<std::string, cl_program>(xclbinFileName, program)); } } else { std::string kernelFileName = getString(root, "kernelFileName"); std::map<std::string, cl_program>::iterator iter = programs.find(kernelFileName); if (iter != programs.end()) { program = iter->second; } else { program = buildProgramFromSource(kernelFileName.c_str(), context, device); cl_int err = clRetainProgram(program); handleError(err, "Failed retaining program. "); programs.insert(std::pair<std::string, cl_program>(kernelFileName, program)); } } std::string type = getString(root, "type"); if (type == "conv") { return new cnn::ConvolutionLayer(params, weight, offset, context, program, clIn ); } else if (type == "pool") { return new cnn::MaxPoolLayer(params, weight, offset, context, program, clIn ); } else if (type == "full") { return new cnn::FullConnectLayer(params, weight, offset, context, program, clIn ); } else if (type == "rbf") { return new cnn::RBFLayer(params, weight, offset, context, program, clIn ); } else { std::cerr << "createLayer: Unsupported layer: " << type << std::endl; exit(-1); } } }; } #endif
rewrite the program to not use c++0x
rewrite the program to not use c++0x
C++
mit
seanzw/OpenCL-FPGA,seanzw/OpenCL-FPGA,seanzw/OpenCL-FPGA,seanzw/OpenCL-FPGA
c443bd3a0304be1248b176a81383143e64d3333e
plugin.C
plugin.C
#include <maya/MAnimControl.h> #include <maya/MCallbackIdArray.h> #include <maya/MEventMessage.h> #include <maya/MGlobal.h> #include <maya/MFnPlugin.h> #include "EngineCommand.h" #include "AssetCommand.h" #include "AssetNode.h" #include "CurveMeshInputNode.h" #include "FluidGridConvert.h" #include "InputNode.h" #include "util.h" #include <HAPI_Version.h> #include <cstdlib> #ifndef _WIN32 #include <unistd.h> #else #include <process.h> #endif void printHAPIVersion() { int i, j, k; char version[32]; MString msg; { HAPI_GetEnvInt( HAPI_ENVINT_VERSION_HOUDINI_MAJOR, &i ); HAPI_GetEnvInt( HAPI_ENVINT_VERSION_HOUDINI_MINOR, &j ); HAPI_GetEnvInt( HAPI_ENVINT_VERSION_HOUDINI_BUILD, &k ); msg = "Houdini version: "; sprintf(version, "%d.%d.%d", i, j, k); msg += version; if(!(i == HAPI_VERSION_HOUDINI_MAJOR && j == HAPI_VERSION_HOUDINI_MINOR && k == HAPI_VERSION_HOUDINI_BUILD)) { msg += ", expected: "; sprintf(version, "%d.%d.%d", HAPI_VERSION_HOUDINI_MAJOR, HAPI_VERSION_HOUDINI_MINOR, HAPI_VERSION_HOUDINI_BUILD); msg += version; } MGlobal::displayInfo(msg); } { HAPI_GetEnvInt( HAPI_ENVINT_VERSION_HOUDINI_ENGINE_MAJOR, &i ); HAPI_GetEnvInt( HAPI_ENVINT_VERSION_HOUDINI_ENGINE_MINOR, &j ); HAPI_GetEnvInt( HAPI_ENVINT_VERSION_HOUDINI_ENGINE_API, &k ); msg = "Houdini Engine version: "; sprintf(version, "%d.%d (API: %d)", i, j, k); msg += version; if(!(i == HAPI_VERSION_HOUDINI_ENGINE_MAJOR && j == HAPI_VERSION_HOUDINI_ENGINE_MINOR && k == HAPI_VERSION_HOUDINI_ENGINE_API)) { msg += ", expected: "; sprintf(version, "%d.%d (API: %d)", HAPI_VERSION_HOUDINI_ENGINE_MAJOR, HAPI_VERSION_HOUDINI_ENGINE_MINOR, HAPI_VERSION_HOUDINI_ENGINE_API); msg += version; } MGlobal::displayInfo(msg); } } namespace { template <typename VAL, class CHILD> class OptionVarBase { public: OptionVarBase(const char* name, const VAL& defaultValue) : myDefaultValue(defaultValue) { myName = "houdiniEngine"; myName += name; bool exists = false; static_cast<const CHILD&>(*this).getImpl(exists); if (!exists) { MGlobal::setOptionVarValue(myName.c_str(), myDefaultValue); } } VAL get() const { bool exists = false; const VAL value = static_cast<const CHILD&>(*this).getImpl(exists); return exists ? value : myDefaultValue; } protected: std::string myName; const VAL myDefaultValue; private: OptionVarBase& operator=(const OptionVarBase&); }; class IntOptionVar: public OptionVarBase<int, IntOptionVar> { public: typedef OptionVarBase<int, IntOptionVar> Base; IntOptionVar(const char* name, int defaultValue) : Base(name, defaultValue) {} int getImpl(bool& exists) const { return MGlobal::optionVarIntValue(myName.c_str(), &exists); } }; class StringOptionVar: public OptionVarBase<MString, StringOptionVar> { public: typedef OptionVarBase<MString, StringOptionVar> Base; StringOptionVar(const char* name, const char* defaultValue) : Base(name, defaultValue) {} MString getImpl(bool& exists) const { return MGlobal::optionVarStringValue(myName.c_str(), &exists); } }; struct OptionVars { OptionVars() : asyncMode("AsynchronousMode", 1) , sessionType( "SessionType", static_cast<int>(HAPI_SESSION_INPROCESS) ) , thriftServer("ThriftServer", "localhost") , thriftPort("ThriftPort", 9090) , sessionPipeCustom("SessionPipeCustom", 0) , thriftPipe("ThriftPipe", "hapi") {} IntOptionVar asyncMode; IntOptionVar sessionType; StringOptionVar thriftServer; IntOptionVar thriftPort; IntOptionVar sessionPipeCustom; StringOptionVar thriftPipe; private: OptionVars& operator=(const OptionVars&); }; } namespace SessionType { enum Enum { ST_INPROCESS, ST_THRIFT_SOCKET, ST_THRIFT_PIPE }; } HAPI_Result initializeSession(const OptionVars& optionVars) { if ( Util::theHAPISession.get() ) { MGlobal::displayInfo( "Houdini Engine session is already created. Skipping."); return HAPI_RESULT_SUCCESS; } const SessionType::Enum sessionType = static_cast<SessionType::Enum>( optionVars.sessionType.get() ); Util::theHAPISession.reset( new Util::HAPISession ); HAPI_Result sessionResult = HAPI_RESULT_FAILURE; switch (sessionType) { case SessionType::ST_INPROCESS: MGlobal::displayInfo( "Creating an in-process Houdini Engine session." ); sessionResult = HAPI_CreateInProcessSession( Util::theHAPISession.get() ); break; case SessionType::ST_THRIFT_SOCKET: { MString hostName = "localhost"; int port = -1; MString msgHostPort; hostName = optionVars.thriftServer.get(); port = optionVars.thriftPort.get(); msgHostPort = hostName + ":" + port; sessionResult = HAPI_CreateThriftSocketSession( Util::theHAPISession.get(), hostName.asChar(), port ); if( !HAPI_FAIL(sessionResult) ) { MGlobal::displayInfo( "Connected to Houdini Engine server using TCP socket " "at " + msgHostPort + "." ); } else { MGlobal::displayInfo( "Failed to connected to Houdini Engine server using " "TCP socket at " + msgHostPort + "." ); } } break; case SessionType::ST_THRIFT_PIPE: { MString pipeName; MString msgPipe; if( !optionVars.sessionPipeCustom.get() ) { HAPI_ThriftServerOptions serverOptions; serverOptions.autoClose = true; serverOptions.timeoutMs = 10 * 1000; pipeName = "hapi"; pipeName += getpid(); MGlobal::displayInfo( "Automatically starting Houdini Engine server " "using named pipe." ); HAPI_ProcessId processId; sessionResult = HAPI_StartThriftNamedPipeServer( &serverOptions, pipeName.asChar(), &processId); if( HAPI_FAIL(sessionResult) ) { MGlobal::displayError( "Failed to automatically start Houdini Engine " "server using named pipe." ); return HAPI_RESULT_FAILURE; } msgPipe = pipeName; MGlobal::displayInfo( "Automatically started Houdini Engine server " "using named pipe at \"" + msgPipe + "\"." ); } else { pipeName = optionVars.thriftPipe.get(); msgPipe = pipeName; } sessionResult = HAPI_CreateThriftNamedPipeSession( Util::theHAPISession.get(), pipeName.asChar() ); if( !HAPI_FAIL(sessionResult) ) { MGlobal::displayInfo( "Connected to Houdini Engine server using named pipe " "at \"" + msgPipe + "\"." ); } else { MGlobal::displayInfo( "Failed to connected to Houdini Engine server using " "named pipe at \"" + msgPipe + "\"." ); } } break; } if ( sessionResult != HAPI_RESULT_SUCCESS ) { Util::theHAPISession.reset(NULL); MGlobal::displayError( "Could not create a Houdini Engine session. " "Please edit the Back End preferences and reload the plug-in." ); } return sessionResult; } HAPI_Result initializeHAPI(const OptionVars& optionVars) { if( HAPI_IsInitialized( Util::theHAPISession.get() ) == HAPI_RESULT_SUCCESS ) { MGlobal::displayInfo( "Houdini Engine is already initialized. Skipping initialization." ); return HAPI_RESULT_SUCCESS; } const char* otl_dir = getenv("HAPI_OTL_PATH"); const char* dso_dir = getenv("HAPI_DSO_PATH"); HAPI_CookOptions cook_options = HAPI_CookOptions_Create(); cook_options.maxVerticesPerPrimitive = -1; cook_options.refineCurveToLinear = false; bool use_cooking_thread = optionVars.asyncMode.get() == 1; HAPI_Result hstat = HAPI_Initialize( Util::theHAPISession.get(), &cook_options, use_cooking_thread, -1, NULL, otl_dir, dso_dir, NULL, NULL ); if(HAPI_FAIL(hstat)) { MGlobal::displayInfo("Houdini Engine failed to initialize."); return hstat; } // Set the client name. HAPI_SetServerEnvString( Util::theHAPISession.get(), HAPI_ENV_CLIENT_NAME, "maya" ); MGlobal::displayInfo("Houdini Engine initialized successfully."); return HAPI_RESULT_SUCCESS; } bool cleanupHAPI() { if ( !Util::theHAPISession.get() ) { return true; } // If HAPI is not initialized, then don't try to do cleanup. This could be // because HAPI failed to initialize, or HARS disconnected. if( HAPI_FAIL( HAPI_IsInitialized( Util::theHAPISession.get() ) ) ) { return true; } HAPI_Result hstat = HAPI_RESULT_SUCCESS; hstat = HAPI_Cleanup( Util::theHAPISession.get() ); if(hstat != HAPI_RESULT_SUCCESS) { CHECK_HAPI(hstat); return false; } return true; } void updateTimelineCallback(void* clientData) { HAPI_TimelineOptions timelineOptions; MTime oneUnitTime; // Houdini's "frame 1" is "0 seconds", but Maya's "frame 0" is "0 seconds". // So we need to offset the time by 1. timelineOptions.fps = float( 1.0 / oneUnitTime.as(MTime::kSeconds) ); timelineOptions.startTime = (MAnimControl::animationStartTime() - oneUnitTime) .as(MTime::kSeconds); timelineOptions.endTime = (MAnimControl::animationEndTime() - oneUnitTime) .as(MTime::kSeconds); HAPI_SetTimelineOptions( Util::theHAPISession.get(), &timelineOptions ); } MCallbackIdArray messageCallbacks; void initializeMessageCallbacks() { MStatus status; MCallbackId callbackId; callbackId = MEventMessage::addEventCallback( "playbackRangeSliderChanged", updateTimelineCallback, NULL, &status ); if(status) { messageCallbacks.append(callbackId); } else { CHECK_MSTATUS(status); } callbackId = MEventMessage::addEventCallback( "timeUnitChanged", updateTimelineCallback, NULL, &status ); if(status) { messageCallbacks.append(callbackId); } else { CHECK_MSTATUS(status); } } void cleanupMessageCallbacks() { MStatus status; status = MMessage::removeCallbacks(messageCallbacks); CHECK_MSTATUS(status); } PLUGIN_EXPORT MStatus initializePlugin(MObject obj) { OptionVars optionVars; initializeSession(optionVars); if(!HAPI_FAIL(initializeHAPI(optionVars))) { printHAPIVersion(); } char engine_version[32]; sprintf(engine_version, "%d.%d (API: %d)", HAPI_VERSION_HOUDINI_ENGINE_MAJOR, HAPI_VERSION_HOUDINI_ENGINE_MINOR, HAPI_VERSION_HOUDINI_ENGINE_API); MStatus status; MFnPlugin plugin( obj, "Side Effects", engine_version, "Any" ); status = plugin.registerUI( "houdiniEngineCreateUI", "houdiniEngineDeleteUI" ); CHECK_MSTATUS_AND_RETURN_IT(status); status = plugin.registerTransform( AssetNode::typeName, AssetNode::typeId, AssetNode::creator, AssetNode::initialize, MPxTransformationMatrix::creator, MPxTransformationMatrix::baseTransformationMatrixId ); CHECK_MSTATUS_AND_RETURN_IT(status); status = plugin.registerNode( InputNode::typeName, InputNode::typeId, InputNode::creator, InputNode::initialize ); CHECK_MSTATUS_AND_RETURN_IT(status); status = plugin.registerNode( CurveMeshInputNode::typeName, CurveMeshInputNode::typeId, CurveMeshInputNode::creator, CurveMeshInputNode::initialize ); CHECK_MSTATUS_AND_RETURN_IT(status); #if MAYA_API_VERSION >= 201400 status = plugin.registerNode( FluidGridConvert::typeName, FluidGridConvert::typeId, FluidGridConvert::creator, FluidGridConvert::initialize ); #endif status = plugin.registerCommand( EngineCommand::commandName, EngineCommand::creator, EngineCommand::newSyntax ); CHECK_MSTATUS_AND_RETURN_IT(status); status = plugin.registerCommand( "houdiniAsset", AssetCommand::creator, AssetCommand::newSyntax); CHECK_MSTATUS_AND_RETURN_IT(status); initializeMessageCallbacks(); // update the timeline option for the first time updateTimelineCallback(NULL); return status; } PLUGIN_EXPORT MStatus uninitializePlugin(MObject obj) { MStatus status; MFnPlugin plugin(obj); cleanupMessageCallbacks(); status = plugin.deregisterNode(AssetNode::typeId); CHECK_MSTATUS_AND_RETURN_IT(status); #if MAYA_API_VERSION >= 201400 status = plugin.deregisterNode(FluidGridConvert::typeId); CHECK_MSTATUS_AND_RETURN_IT(status); #endif status = plugin.deregisterCommand(EngineCommand::commandName); CHECK_MSTATUS_AND_RETURN_IT(status); status = plugin.deregisterCommand("houdiniAsset"); CHECK_MSTATUS_AND_RETURN_IT(status); if(cleanupHAPI()) { MGlobal::displayInfo("Houdini Engine cleaned up successfully."); } else { MGlobal::displayInfo("Houdini Engine failed to clean up."); return MStatus::kFailure; } return status; }
#include <maya/MAnimControl.h> #include <maya/MCallbackIdArray.h> #include <maya/MEventMessage.h> #include <maya/MGlobal.h> #include <maya/MFnPlugin.h> #include "EngineCommand.h" #include "AssetCommand.h" #include "AssetNode.h" #include "CurveMeshInputNode.h" #include "FluidGridConvert.h" #include "InputNode.h" #include "util.h" #include <HAPI_Version.h> #include <cstdlib> #ifndef _WIN32 #include <unistd.h> #else #include <process.h> #endif void printHAPIVersion() { int i, j, k; char version[32]; MString msg; { HAPI_GetEnvInt( HAPI_ENVINT_VERSION_HOUDINI_MAJOR, &i ); HAPI_GetEnvInt( HAPI_ENVINT_VERSION_HOUDINI_MINOR, &j ); HAPI_GetEnvInt( HAPI_ENVINT_VERSION_HOUDINI_BUILD, &k ); msg = "Houdini version: "; sprintf(version, "%d.%d.%d", i, j, k); msg += version; if(!(i == HAPI_VERSION_HOUDINI_MAJOR && j == HAPI_VERSION_HOUDINI_MINOR && k == HAPI_VERSION_HOUDINI_BUILD)) { msg += ", expected: "; sprintf(version, "%d.%d.%d", HAPI_VERSION_HOUDINI_MAJOR, HAPI_VERSION_HOUDINI_MINOR, HAPI_VERSION_HOUDINI_BUILD); msg += version; } MGlobal::displayInfo(msg); } { HAPI_GetEnvInt( HAPI_ENVINT_VERSION_HOUDINI_ENGINE_MAJOR, &i ); HAPI_GetEnvInt( HAPI_ENVINT_VERSION_HOUDINI_ENGINE_MINOR, &j ); HAPI_GetEnvInt( HAPI_ENVINT_VERSION_HOUDINI_ENGINE_API, &k ); msg = "Houdini Engine version: "; sprintf(version, "%d.%d (API: %d)", i, j, k); msg += version; if(!(i == HAPI_VERSION_HOUDINI_ENGINE_MAJOR && j == HAPI_VERSION_HOUDINI_ENGINE_MINOR && k == HAPI_VERSION_HOUDINI_ENGINE_API)) { msg += ", expected: "; sprintf(version, "%d.%d (API: %d)", HAPI_VERSION_HOUDINI_ENGINE_MAJOR, HAPI_VERSION_HOUDINI_ENGINE_MINOR, HAPI_VERSION_HOUDINI_ENGINE_API); msg += version; } MGlobal::displayInfo(msg); } } namespace { template <typename VAL, class CHILD> class OptionVarBase { public: OptionVarBase(const char* name, const VAL& defaultValue) : myDefaultValue(defaultValue) { myName = "houdiniEngine"; myName += name; bool exists = false; static_cast<const CHILD&>(*this).getImpl(exists); if (!exists) { MGlobal::setOptionVarValue(myName.c_str(), myDefaultValue); } } VAL get() const { bool exists = false; const VAL value = static_cast<const CHILD&>(*this).getImpl(exists); return exists ? value : myDefaultValue; } protected: std::string myName; const VAL myDefaultValue; private: OptionVarBase& operator=(const OptionVarBase&); }; class IntOptionVar: public OptionVarBase<int, IntOptionVar> { public: typedef OptionVarBase<int, IntOptionVar> Base; IntOptionVar(const char* name, int defaultValue) : Base(name, defaultValue) {} int getImpl(bool& exists) const { return MGlobal::optionVarIntValue(myName.c_str(), &exists); } }; class StringOptionVar: public OptionVarBase<MString, StringOptionVar> { public: typedef OptionVarBase<MString, StringOptionVar> Base; StringOptionVar(const char* name, const char* defaultValue) : Base(name, defaultValue) {} MString getImpl(bool& exists) const { return MGlobal::optionVarStringValue(myName.c_str(), &exists); } }; struct OptionVars { OptionVars() : asyncMode("AsynchronousMode", 1) , sessionType( "SessionType", static_cast<int>(HAPI_SESSION_INPROCESS) ) , thriftServer("ThriftServer", "localhost") , thriftPort("ThriftPort", 9090) , sessionPipeCustom("SessionPipeCustom", 0) , thriftPipe("ThriftPipe", "hapi") {} IntOptionVar asyncMode; IntOptionVar sessionType; StringOptionVar thriftServer; IntOptionVar thriftPort; IntOptionVar sessionPipeCustom; StringOptionVar thriftPipe; private: OptionVars& operator=(const OptionVars&); }; } namespace SessionType { enum Enum { ST_INPROCESS, ST_THRIFT_SOCKET, ST_THRIFT_PIPE }; } HAPI_Result initializeSession(const OptionVars& optionVars) { if ( Util::theHAPISession.get() ) { MGlobal::displayInfo( "Houdini Engine session is already created. Skipping."); return HAPI_RESULT_SUCCESS; } const SessionType::Enum sessionType = static_cast<SessionType::Enum>( optionVars.sessionType.get() ); Util::theHAPISession.reset( new Util::HAPISession ); HAPI_Result sessionResult = HAPI_RESULT_FAILURE; switch (sessionType) { case SessionType::ST_INPROCESS: MGlobal::displayInfo( "Creating an in-process Houdini Engine session." ); sessionResult = HAPI_CreateInProcessSession( Util::theHAPISession.get() ); break; case SessionType::ST_THRIFT_SOCKET: { MString hostName = "localhost"; int port = -1; MString msgHostPort; hostName = optionVars.thriftServer.get(); port = optionVars.thriftPort.get(); msgHostPort = hostName + ":" + port; sessionResult = HAPI_CreateThriftSocketSession( Util::theHAPISession.get(), hostName.asChar(), port ); if( !HAPI_FAIL(sessionResult) ) { MGlobal::displayInfo( "Connected to Houdini Engine server using TCP socket " "at " + msgHostPort + "." ); } else { MGlobal::displayInfo( "Failed to connected to Houdini Engine server using " "TCP socket at " + msgHostPort + "." ); } } break; case SessionType::ST_THRIFT_PIPE: { MString pipeName; MString msgPipe; if( !optionVars.sessionPipeCustom.get() ) { HAPI_ThriftServerOptions serverOptions; serverOptions.autoClose = true; serverOptions.timeoutMs = 10 * 1000; pipeName = "hapi"; pipeName += getpid(); MGlobal::displayInfo( "Automatically starting Houdini Engine server " "using named pipe." ); HAPI_ProcessId processId; sessionResult = HAPI_StartThriftNamedPipeServer( &serverOptions, pipeName.asChar(), &processId); if( HAPI_FAIL(sessionResult) ) { MGlobal::displayError( "Failed to automatically start Houdini Engine " "server using named pipe." ); return HAPI_RESULT_FAILURE; } msgPipe = pipeName; MGlobal::displayInfo( "Automatically started Houdini Engine server " "using named pipe at \"" + msgPipe + "\"." ); } else { pipeName = optionVars.thriftPipe.get(); msgPipe = pipeName; } sessionResult = HAPI_CreateThriftNamedPipeSession( Util::theHAPISession.get(), pipeName.asChar() ); if( !HAPI_FAIL(sessionResult) ) { MGlobal::displayInfo( "Connected to Houdini Engine server using named pipe " "at \"" + msgPipe + "\"." ); } else { MGlobal::displayInfo( "Failed to connected to Houdini Engine server using " "named pipe at \"" + msgPipe + "\"." ); } } break; } if ( sessionResult != HAPI_RESULT_SUCCESS ) { Util::theHAPISession.reset(NULL); MGlobal::displayError( "Could not create a Houdini Engine session. " "Please edit the Back End preferences and reload the plug-in." ); } return sessionResult; } HAPI_Result initializeHAPI(const OptionVars& optionVars) { if( HAPI_IsInitialized( Util::theHAPISession.get() ) == HAPI_RESULT_SUCCESS ) { MGlobal::displayInfo( "Houdini Engine is already initialized. Skipping initialization." ); return HAPI_RESULT_SUCCESS; } const char* otl_dir = getenv("HAPI_OTL_PATH"); const char* dso_dir = getenv("HAPI_DSO_PATH"); HAPI_CookOptions cook_options = HAPI_CookOptions_Create(); cook_options.maxVerticesPerPrimitive = -1; cook_options.refineCurveToLinear = false; bool use_cooking_thread = optionVars.asyncMode.get() == 1; HAPI_Result hstat = HAPI_Initialize( Util::theHAPISession.get(), &cook_options, use_cooking_thread, -1, NULL, otl_dir, dso_dir, NULL, NULL ); if(HAPI_FAIL(hstat)) { MGlobal::displayInfo("Houdini Engine failed to initialize."); return hstat; } // Set the client name. HAPI_SetServerEnvString( Util::theHAPISession.get(), HAPI_ENV_CLIENT_NAME, "maya" ); MGlobal::displayInfo("Houdini Engine initialized successfully."); return HAPI_RESULT_SUCCESS; } bool cleanupHAPI() { if ( !Util::theHAPISession.get() ) { return true; } // If HAPI is not initialized, then don't try to do cleanup. This could be // because HAPI failed to initialize, or HARS disconnected. if( HAPI_FAIL( HAPI_IsInitialized( Util::theHAPISession.get() ) ) ) { return true; } HAPI_Result hstat = HAPI_RESULT_SUCCESS; hstat = HAPI_Cleanup( Util::theHAPISession.get() ); if(hstat != HAPI_RESULT_SUCCESS) { CHECK_HAPI(hstat); return false; } return true; } void updateTimelineCallback(void* clientData) { HAPI_TimelineOptions timelineOptions; MTime oneUnitTime; // Houdini's "frame 1" is "0 seconds", but Maya's "frame 0" is "0 seconds". // So we need to offset the time by 1. timelineOptions.fps = float( 1.0 / oneUnitTime.as(MTime::kSeconds) ); timelineOptions.startTime = (MAnimControl::animationStartTime() - oneUnitTime) .as(MTime::kSeconds); timelineOptions.endTime = (MAnimControl::animationEndTime() - oneUnitTime) .as(MTime::kSeconds); HAPI_SetTimelineOptions( Util::theHAPISession.get(), &timelineOptions ); } MCallbackIdArray messageCallbacks; void initializeMessageCallbacks() { MStatus status; MCallbackId callbackId; callbackId = MEventMessage::addEventCallback( "playbackRangeSliderChanged", updateTimelineCallback, NULL, &status ); if(status) { messageCallbacks.append(callbackId); } else { CHECK_MSTATUS(status); } callbackId = MEventMessage::addEventCallback( "timeUnitChanged", updateTimelineCallback, NULL, &status ); if(status) { messageCallbacks.append(callbackId); } else { CHECK_MSTATUS(status); } } void cleanupMessageCallbacks() { MStatus status; status = MMessage::removeCallbacks(messageCallbacks); CHECK_MSTATUS(status); } PLUGIN_EXPORT MStatus initializePlugin(MObject obj) { OptionVars optionVars; initializeSession(optionVars); if(!HAPI_FAIL(initializeHAPI(optionVars))) { printHAPIVersion(); } char engine_version[32]; sprintf(engine_version, "%d.%d (API: %d)", HAPI_VERSION_HOUDINI_ENGINE_MAJOR, HAPI_VERSION_HOUDINI_ENGINE_MINOR, HAPI_VERSION_HOUDINI_ENGINE_API); MStatus status; MFnPlugin plugin( obj, "Side Effects", engine_version, "Any" ); status = plugin.registerUI( "houdiniEngineCreateUI", "houdiniEngineDeleteUI" ); CHECK_MSTATUS_AND_RETURN_IT(status); status = plugin.registerTransform( AssetNode::typeName, AssetNode::typeId, AssetNode::creator, AssetNode::initialize, MPxTransformationMatrix::creator, MPxTransformationMatrix::baseTransformationMatrixId ); CHECK_MSTATUS_AND_RETURN_IT(status); status = plugin.registerNode( InputNode::typeName, InputNode::typeId, InputNode::creator, InputNode::initialize ); CHECK_MSTATUS_AND_RETURN_IT(status); status = plugin.registerNode( CurveMeshInputNode::typeName, CurveMeshInputNode::typeId, CurveMeshInputNode::creator, CurveMeshInputNode::initialize ); CHECK_MSTATUS_AND_RETURN_IT(status); #if MAYA_API_VERSION >= 201400 status = plugin.registerNode( FluidGridConvert::typeName, FluidGridConvert::typeId, FluidGridConvert::creator, FluidGridConvert::initialize ); #endif status = plugin.registerCommand( EngineCommand::commandName, EngineCommand::creator, EngineCommand::newSyntax ); CHECK_MSTATUS_AND_RETURN_IT(status); status = plugin.registerCommand( "houdiniAsset", AssetCommand::creator, AssetCommand::newSyntax); CHECK_MSTATUS_AND_RETURN_IT(status); initializeMessageCallbacks(); // update the timeline option for the first time updateTimelineCallback(NULL); return status; } PLUGIN_EXPORT MStatus uninitializePlugin(MObject obj) { MStatus status; MFnPlugin plugin(obj); cleanupMessageCallbacks(); status = plugin.deregisterNode(AssetNode::typeId); CHECK_MSTATUS_AND_RETURN_IT(status); status = plugin.deregisterNode(InputGeometryNode::typeId); CHECK_MSTATUS_AND_RETURN_IT(status); status = plugin.deregisterNode(CurveMeshInputNode::typeId); CHECK_MSTATUS_AND_RETURN_IT(status); #if MAYA_API_VERSION >= 201400 status = plugin.deregisterNode(FluidGridConvert::typeId); CHECK_MSTATUS_AND_RETURN_IT(status); #endif status = plugin.deregisterCommand(EngineCommand::commandName); CHECK_MSTATUS_AND_RETURN_IT(status); status = plugin.deregisterCommand("houdiniAsset"); CHECK_MSTATUS_AND_RETURN_IT(status); if(cleanupHAPI()) { MGlobal::displayInfo("Houdini Engine cleaned up successfully."); } else { MGlobal::displayInfo("Houdini Engine failed to clean up."); return MStatus::kFailure; } return status; }
Add missing deregisterNode() calls
Add missing deregisterNode() calls
C++
mit
sideeffects/HoudiniEngineForMaya,sideeffects/HoudiniEngineForMaya,sideeffects/HoudiniEngineForMaya
056a036712d2cafa2cc3d9903bf12de989535a7a
Machines/Apple/ADB/Keyboard.cpp
Machines/Apple/ADB/Keyboard.cpp
// // Keyboard.cpp // Clock Signal // // Created by Thomas Harte on 13/02/2021. // Copyright © 2021 Thomas Harte. All rights reserved. // #include "Keyboard.hpp" using namespace Apple::ADB; Keyboard::Keyboard(Bus &bus) : ReactiveDevice(bus, 2) {} void Keyboard::perform_command(const Command &command) { switch(command.type) { case Command::Type::Reset: modifiers_ = 0xffff; case Command::Type::Flush: { std::lock_guard lock_guard(keys_mutex_); pending_events_.clear(); } break; case Command::Type::Talk: switch(command.reg) { case 0: { // Post up to two key events, or nothing if there are // no events pending. std::lock_guard lock_guard(keys_mutex_); if(!pending_events_.empty()) { if(pending_events_.size() > 1) { post_response({pending_events_[0], pending_events_[1]}); pending_events_.erase(pending_events_.begin(), pending_events_.begin()+2); } else { // Two bytes are required; provide a key up of the fictional // key zero as the second. // That's arbitrary; verify with real machines. post_response({pending_events_[0], 0x80}); pending_events_.clear(); } } } break; case 2: { std::lock_guard lock_guard(keys_mutex_); post_response({uint8_t(modifiers_ >> 8), uint8_t(modifiers_)}); } break; default: break; } break; case Command::Type::Listen: // If a listen is incoming for register 2, prepare to capture LED statuses. if(command.reg == 2) { receive_bytes(2); } break; default: break; } } void Keyboard::did_receive_data(const Command &, const std::vector<uint8_t> &data) { // This must be a register 2 listen; update the LED statuses. // TODO: and possibly display these. modifiers_ = (modifiers_ & 0xfff8) | (data[1] & 7); } bool Keyboard::set_key_pressed(Key key, bool is_pressed) { // ADB keyboard events: low 7 bits are a key code; bit 7 is either 0 for pressed or 1 for released. std::lock_guard lock_guard(keys_mutex_); pending_events_.push_back(uint8_t(key) | (is_pressed ? 0x00 : 0x80)); pressed_keys_[size_t(key)] = is_pressed; // Track modifier state also. /* In all cases below: 0 = pressed/on; 1 = released/off. b15: None (reserved) b14: Delete b13: Caps lock b12: Reset b11: Control b10: Shift b9: Option b8: Command -- From here onwards, available only on the extended keyboard. b7: Num lock/clear b6: Scroll lock b5–3: None (reserved) b2: Scroll Lock LED b1: Caps Lock LED b0: Num Lock LED */ #define SetModifierBit(x) modifiers_ = (modifiers_ & ~x) | (is_pressed ? 0 : x); #define ToggleModifierBit(x) if(is_pressed) modifiers_ ^= x; switch(key) { default: break; case Key::Delete: SetModifierBit(0x4000); break; case Key::CapsLock: ToggleModifierBit(0x2000); break; case Key::Power: SetModifierBit(0x1000); break; case Key::LeftControl: case Key::RightControl: SetModifierBit(0x0800); break; case Key::LeftShift: case Key::RightShift: SetModifierBit(0x0400); break; case Key::LeftOption: case Key::RightOption: SetModifierBit(0x0200); break; case Key::Command: SetModifierBit(0x0100); break; case Key::KeypadClear: ToggleModifierBit(0x0080); break; case Key::Help: ToggleModifierBit(0x0040); break; } #undef SetModifierBit // Ensure service occurs. post_service_request(); return true; } void Keyboard::clear_all_keys() { // For all keys currently marked as down, enqueue key-up actions. std::lock_guard lock_guard(keys_mutex_); for(size_t key = 0; key < pressed_keys_.size(); key++) { if(pressed_keys_[key]) { pending_events_.push_back(0x80 | uint8_t(key)); pressed_keys_[key] = false; } } if(!pending_events_.empty()) post_service_request(); // Mark all modifiers as released. modifiers_ |= 0xfff8; } // MARK: - KeyboardMapper uint16_t KeyboardMapper::mapped_key_for_key(Inputs::Keyboard::Key key) const { using Key = Inputs::Keyboard::Key; using ADBKey = Apple::ADB::Key; switch(key) { default: return MachineTypes::MappedKeyboardMachine::KeyNotMapped; #define Bind(x, y) case Key::x: return uint16_t(ADBKey::y) #define BindDirect(x) Bind(x, x) BindDirect(BackTick); BindDirect(k1); BindDirect(k2); BindDirect(k3); BindDirect(k4); BindDirect(k5); BindDirect(k6); BindDirect(k7); BindDirect(k8); BindDirect(k9); BindDirect(k0); BindDirect(Help); BindDirect(Home); BindDirect(PageUp); BindDirect(Delete); BindDirect(End); BindDirect(PageDown); BindDirect(Escape); BindDirect(Hyphen); BindDirect(Equals); BindDirect(Backspace); BindDirect(Tab); BindDirect(F1); BindDirect(F2); BindDirect(F3); BindDirect(F4); BindDirect(F5); BindDirect(F6); BindDirect(F7); BindDirect(F8); BindDirect(F9); BindDirect(F10); BindDirect(F11); BindDirect(F12); BindDirect(Q); BindDirect(W); BindDirect(E); BindDirect(R); BindDirect(T); BindDirect(Y); BindDirect(U); BindDirect(I); BindDirect(O); BindDirect(P); BindDirect(A); BindDirect(S); BindDirect(D); BindDirect(F); BindDirect(G); BindDirect(H); BindDirect(J); BindDirect(K); BindDirect(L); BindDirect(Z); BindDirect(X); BindDirect(C); BindDirect(V); BindDirect(B); BindDirect(N); BindDirect(M); BindDirect(OpenSquareBracket); BindDirect(CloseSquareBracket); BindDirect(Semicolon); BindDirect(Quote); BindDirect(Comma); BindDirect(FullStop); BindDirect(ForwardSlash); BindDirect(CapsLock); BindDirect(LeftShift); BindDirect(RightShift); BindDirect(LeftControl); BindDirect(RightControl); BindDirect(LeftOption); BindDirect(RightOption); Bind(LeftMeta, Command); Bind(RightMeta, Command); BindDirect(Space); BindDirect(Backslash); Bind(Enter, Return); BindDirect(Left); BindDirect(Right); BindDirect(Up); BindDirect(Down); Bind(KeypadDelete, KeypadClear); BindDirect(KeypadEquals); BindDirect(KeypadSlash); BindDirect(KeypadAsterisk); BindDirect(KeypadMinus); BindDirect(KeypadPlus); BindDirect(KeypadEnter); BindDirect(KeypadDecimalPoint); BindDirect(Keypad9); BindDirect(Keypad8); BindDirect(Keypad7); BindDirect(Keypad6); BindDirect(Keypad5); BindDirect(Keypad4); BindDirect(Keypad3); BindDirect(Keypad2); BindDirect(Keypad1); BindDirect(Keypad0); // Leaving unmapped: // Power, F13, F14, F15 #undef BindDirect #undef Bind } }
// // Keyboard.cpp // Clock Signal // // Created by Thomas Harte on 13/02/2021. // Copyright © 2021 Thomas Harte. All rights reserved. // #include "Keyboard.hpp" using namespace Apple::ADB; Keyboard::Keyboard(Bus &bus) : ReactiveDevice(bus, 2) {} void Keyboard::perform_command(const Command &command) { switch(command.type) { case Command::Type::Reset: modifiers_ = 0xffff; [[fallthrough]]; case Command::Type::Flush: { std::lock_guard lock_guard(keys_mutex_); pending_events_.clear(); } break; case Command::Type::Talk: switch(command.reg) { case 0: { // Post up to two key events, or nothing if there are // no events pending. std::lock_guard lock_guard(keys_mutex_); if(!pending_events_.empty()) { if(pending_events_.size() > 1) { post_response({pending_events_[0], pending_events_[1]}); pending_events_.erase(pending_events_.begin(), pending_events_.begin()+2); } else { // Two bytes are required; provide a key up of the fictional // key zero as the second. // That's arbitrary; verify with real machines. post_response({pending_events_[0], 0x80}); pending_events_.clear(); } } } break; case 2: { std::lock_guard lock_guard(keys_mutex_); post_response({uint8_t(modifiers_ >> 8), uint8_t(modifiers_)}); } break; default: break; } break; case Command::Type::Listen: // If a listen is incoming for register 2, prepare to capture LED statuses. if(command.reg == 2) { receive_bytes(2); } break; default: break; } } void Keyboard::did_receive_data(const Command &, const std::vector<uint8_t> &data) { // This must be a register 2 listen; update the LED statuses. // TODO: and possibly display these. modifiers_ = (modifiers_ & 0xfff8) | (data[1] & 7); } bool Keyboard::set_key_pressed(Key key, bool is_pressed) { // ADB keyboard events: low 7 bits are a key code; bit 7 is either 0 for pressed or 1 for released. std::lock_guard lock_guard(keys_mutex_); pending_events_.push_back(uint8_t(key) | (is_pressed ? 0x00 : 0x80)); pressed_keys_[size_t(key)] = is_pressed; // Track modifier state also. /* In all cases below: 0 = pressed/on; 1 = released/off. b15: None (reserved) b14: Delete b13: Caps lock b12: Reset b11: Control b10: Shift b9: Option b8: Command -- From here onwards, available only on the extended keyboard. b7: Num lock/clear b6: Scroll lock b5–3: None (reserved) b2: Scroll Lock LED b1: Caps Lock LED b0: Num Lock LED */ #define SetModifierBit(x) modifiers_ = (modifiers_ & ~x) | (is_pressed ? 0 : x); #define ToggleModifierBit(x) if(is_pressed) modifiers_ ^= x; switch(key) { default: break; case Key::Delete: SetModifierBit(0x4000); break; case Key::CapsLock: ToggleModifierBit(0x2000); break; case Key::Power: SetModifierBit(0x1000); break; case Key::LeftControl: case Key::RightControl: SetModifierBit(0x0800); break; case Key::LeftShift: case Key::RightShift: SetModifierBit(0x0400); break; case Key::LeftOption: case Key::RightOption: SetModifierBit(0x0200); break; case Key::Command: SetModifierBit(0x0100); break; case Key::KeypadClear: ToggleModifierBit(0x0080); break; case Key::Help: ToggleModifierBit(0x0040); break; } #undef SetModifierBit // Ensure service occurs. post_service_request(); return true; } void Keyboard::clear_all_keys() { // For all keys currently marked as down, enqueue key-up actions. std::lock_guard lock_guard(keys_mutex_); for(size_t key = 0; key < pressed_keys_.size(); key++) { if(pressed_keys_[key]) { pending_events_.push_back(0x80 | uint8_t(key)); pressed_keys_[key] = false; } } if(!pending_events_.empty()) post_service_request(); // Mark all modifiers as released. modifiers_ |= 0xfff8; } // MARK: - KeyboardMapper uint16_t KeyboardMapper::mapped_key_for_key(Inputs::Keyboard::Key key) const { using Key = Inputs::Keyboard::Key; using ADBKey = Apple::ADB::Key; switch(key) { default: return MachineTypes::MappedKeyboardMachine::KeyNotMapped; #define Bind(x, y) case Key::x: return uint16_t(ADBKey::y) #define BindDirect(x) Bind(x, x) BindDirect(BackTick); BindDirect(k1); BindDirect(k2); BindDirect(k3); BindDirect(k4); BindDirect(k5); BindDirect(k6); BindDirect(k7); BindDirect(k8); BindDirect(k9); BindDirect(k0); BindDirect(Help); BindDirect(Home); BindDirect(PageUp); BindDirect(Delete); BindDirect(End); BindDirect(PageDown); BindDirect(Escape); BindDirect(Hyphen); BindDirect(Equals); BindDirect(Backspace); BindDirect(Tab); BindDirect(F1); BindDirect(F2); BindDirect(F3); BindDirect(F4); BindDirect(F5); BindDirect(F6); BindDirect(F7); BindDirect(F8); BindDirect(F9); BindDirect(F10); BindDirect(F11); BindDirect(F12); BindDirect(Q); BindDirect(W); BindDirect(E); BindDirect(R); BindDirect(T); BindDirect(Y); BindDirect(U); BindDirect(I); BindDirect(O); BindDirect(P); BindDirect(A); BindDirect(S); BindDirect(D); BindDirect(F); BindDirect(G); BindDirect(H); BindDirect(J); BindDirect(K); BindDirect(L); BindDirect(Z); BindDirect(X); BindDirect(C); BindDirect(V); BindDirect(B); BindDirect(N); BindDirect(M); BindDirect(OpenSquareBracket); BindDirect(CloseSquareBracket); BindDirect(Semicolon); BindDirect(Quote); BindDirect(Comma); BindDirect(FullStop); BindDirect(ForwardSlash); BindDirect(CapsLock); BindDirect(LeftShift); BindDirect(RightShift); BindDirect(LeftControl); BindDirect(RightControl); BindDirect(LeftOption); BindDirect(RightOption); Bind(LeftMeta, Command); Bind(RightMeta, Command); BindDirect(Space); BindDirect(Backslash); Bind(Enter, Return); BindDirect(Left); BindDirect(Right); BindDirect(Up); BindDirect(Down); Bind(KeypadDelete, KeypadClear); BindDirect(KeypadEquals); BindDirect(KeypadSlash); BindDirect(KeypadAsterisk); BindDirect(KeypadMinus); BindDirect(KeypadPlus); BindDirect(KeypadEnter); BindDirect(KeypadDecimalPoint); BindDirect(Keypad9); BindDirect(Keypad8); BindDirect(Keypad7); BindDirect(Keypad6); BindDirect(Keypad5); BindDirect(Keypad4); BindDirect(Keypad3); BindDirect(Keypad2); BindDirect(Keypad1); BindDirect(Keypad0); // Leaving unmapped: // Power, F13, F14, F15 #undef BindDirect #undef Bind } }
Add missing fallthrough declaration.
Add missing fallthrough declaration.
C++
mit
TomHarte/CLK,TomHarte/CLK,TomHarte/CLK,TomHarte/CLK,TomHarte/CLK
cc7b5b7e508e0427ab4351799a98dc091fb419fc
src/bindings/lua/leanlua_state.cpp
src/bindings/lua/leanlua_state.cpp
/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <iostream> #include <mutex> #include <thread> #include <string> #include <lua.hpp> #include "util/debug.h" #include "util/exception.h" #include "util/memory.h" #include "bindings/lua/leanlua_state.h" #include "bindings/lua/util.h" #include "bindings/lua/name.h" #include "bindings/lua/numerics.h" #include "bindings/lua/options.h" #include "bindings/lua/sexpr.h" #include "bindings/lua/format.h" #include "bindings/lua/level.h" #include "bindings/lua/local_context.h" #include "bindings/lua/expr.h" #include "bindings/lua/context.h" #include "bindings/lua/environment.h" #include "bindings/lua/lean.lua" extern "C" void * lua_realloc(void *, void * q, size_t, size_t new_size) { return lean::realloc(q, new_size); } namespace lean { static void open_state(lua_State * L); static void open_thread(lua_State * L); static void copy_values(lua_State * src, int first, int last, lua_State * tgt) { for (int i = first; i <= last; i++) { if (lua_isstring(src, i)) { lua_pushfstring(tgt, lua_tostring(src, i)); } else if (lua_isnumber(src, i)) { lua_pushnumber(tgt, lua_tonumber(src, i)); } else if (is_expr(src, i)) { push_expr(tgt, to_expr(src, i)); } else if (is_context(src, i)) { push_context(tgt, to_context(src, i)); } else if (is_name(src, i)) { push_name(tgt, to_name(src, i)); } else if (is_mpz(src, i)) { push_mpz(tgt, to_mpz(src, i)); } else if (is_mpq(src, i)) { push_mpq(tgt, to_mpq(src, i)); } else if (is_options(src, i)) { push_options(tgt, to_options(src, i)); } else if (is_sexpr(src, i)) { push_sexpr(tgt, to_sexpr(src, i)); } else if (is_format(src, i)) { push_format(tgt, to_format(src, i)); } else if (is_context_entry(src, i)) { push_context_entry(tgt, to_context_entry(src, i)); } else if (is_local_context(src, i)) { push_local_context(tgt, to_local_context(src, i)); } else if (is_local_entry(src, i)) { push_local_entry(tgt, to_local_entry(src, i)); } else { throw exception("unsupported value type for inter-State call"); } } } struct leanlua_state::imp { lua_State * m_state; std::mutex m_mutex; imp() { #ifdef LEAN_USE_LUA_NEWSTATE m_state = lua_newstate(lua_realloc, nullptr); #else m_state = luaL_newstate(); #endif if (m_state == nullptr) throw exception("fail to create Lua interpreter"); luaL_openlibs(m_state); open_name(m_state); open_mpz(m_state); open_mpq(m_state); open_options(m_state); open_sexpr(m_state); open_format(m_state); open_level(m_state); open_local_context(m_state); open_expr(m_state); open_context(m_state); open_environment(m_state); open_state(m_state); open_thread(m_state); dostring(g_leanlua_extra); } ~imp() { lua_close(m_state); } void dofile(char const * fname) { std::lock_guard<std::mutex> lock(m_mutex); ::lean::dofile(m_state, fname); } void dostring(char const * str) { std::lock_guard<std::mutex> lock(m_mutex); ::lean::dostring(m_state, str); } void dostring(char const * str, environment & env) { set_environment set(m_state, env); dostring(str); } }; leanlua_state::leanlua_state(): m_ptr(new imp()) { } leanlua_state::~leanlua_state() { } void leanlua_state::dofile(char const * fname) { m_ptr->dofile(fname); } void leanlua_state::dostring(char const * str) { m_ptr->dostring(str); } void leanlua_state::dostring(char const * str, environment & env) { m_ptr->dostring(str, env); } constexpr char const * state_mt = "state.mt"; bool is_state(lua_State * L, int idx) { return testudata(L, idx, state_mt); } leanlua_state & to_state(lua_State * L, int idx) { return *static_cast<leanlua_state*>(luaL_checkudata(L, idx, state_mt)); } int push_state(lua_State * L, leanlua_state const & s) { void * mem = lua_newuserdata(L, sizeof(leanlua_state)); new (mem) leanlua_state(s); luaL_getmetatable(L, state_mt); lua_setmetatable(L, -2); return 1; } static int mk_state(lua_State * L) { leanlua_state r; return push_state(L, r); } static int state_gc(lua_State * L) { to_state(L, 1).~leanlua_state(); return 0; } int state_dostring(lua_State * L) { auto S = to_state(L, 1).m_ptr; char const * script = luaL_checkstring(L, 2); int first = 3; int last = lua_gettop(L); std::lock_guard<std::mutex> lock(S->m_mutex); int sz_before = lua_gettop(S->m_state); int result = luaL_loadstring(S->m_state, script); if (result) throw lua_exception(lua_tostring(S->m_state, -1)); copy_values(L, first, last, S->m_state); result = lua_pcall(S->m_state, first > last ? 0 : last - first + 1, LUA_MULTRET, 0); if (result) throw lua_exception(lua_tostring(S->m_state, -1)); int sz_after = lua_gettop(S->m_state); if (sz_after > sz_before) { copy_values(S->m_state, sz_before + 1, sz_after, L); lua_pop(S->m_state, sz_after - sz_before); } return sz_after - sz_before; } static int state_pred(lua_State * L) { lua_pushboolean(L, is_state(L, 1)); return 1; } static const struct luaL_Reg state_m[] = { {"__gc", state_gc}, {"dostring", safe_function<state_dostring>}, {0, 0} }; static void open_state(lua_State * L) { luaL_newmetatable(L, state_mt); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); setfuncs(L, state_m, 0); set_global_function<mk_state>(L, "State"); set_global_function<state_pred>(L, "is_State"); } class leanlua_thread { leanlua_state m_state; int m_sz_before; bool m_error; std::string m_error_msg; std::thread m_thread; public: leanlua_thread(leanlua_state const & st, int sz_before, int num_args): m_state(st), m_sz_before(sz_before), m_error(false), m_thread([=]() { auto S = m_state.m_ptr; std::lock_guard<std::mutex> lock(S->m_mutex); int result = lua_pcall(S->m_state, num_args, LUA_MULTRET, 0); if (result) { m_error = true; m_error_msg = lua_tostring(S->m_state, -1); return; } }) { } ~leanlua_thread() { if (m_thread.joinable()) m_thread.join(); } int wait(lua_State * src) { m_thread.join(); if (m_error) throw lua_exception(m_error_msg.c_str()); auto S = m_state.m_ptr; int sz_after = lua_gettop(S->m_state); if (sz_after > m_sz_before) { copy_values(S->m_state, m_sz_before + 1, sz_after, src); lua_pop(S->m_state, sz_after - m_sz_before); } return sz_after - m_sz_before; } }; constexpr char const * thread_mt = "thread.mt"; bool is_thread(lua_State * L, int idx) { return testudata(L, idx, thread_mt); } leanlua_thread & to_thread(lua_State * L, int idx) { return *static_cast<leanlua_thread*>(luaL_checkudata(L, idx, thread_mt)); } int mk_thread(lua_State * L) { leanlua_state & st = to_state(L, 1); char const * script = luaL_checkstring(L, 2); int first = 3; int last = lua_gettop(L); int nargs = first > last ? 0 : last - first + 1; int sz_before; auto S = st.m_ptr; { std::lock_guard<std::mutex> lock(S->m_mutex); sz_before = lua_gettop(S->m_state); int result = luaL_loadstring(S->m_state, script); if (result) throw lua_exception(lua_tostring(S->m_state, -1)); copy_values(L, first, last, S->m_state); } void * mem = lua_newuserdata(L, sizeof(leanlua_thread)); new (mem) leanlua_thread(st, sz_before, nargs); luaL_getmetatable(L, thread_mt); lua_setmetatable(L, -2); return 1; } static int thread_gc(lua_State * L) { to_thread(L, 1).~leanlua_thread(); return 0; } static int thread_pred(lua_State * L) { lua_pushboolean(L, is_thread(L, 1)); return 1; } int thread_wait(lua_State * L) { return to_thread(L, 1).wait(L); } static const struct luaL_Reg thread_m[] = { {"__gc", thread_gc}, {"wait", safe_function<thread_wait>}, {0, 0} }; static void open_thread(lua_State * L) { luaL_newmetatable(L, thread_mt); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); setfuncs(L, thread_m, 0); set_global_function<mk_thread>(L, "thread"); set_global_function<thread_pred>(L, "is_thread"); } }
/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <iostream> #include <mutex> #include <thread> #include <string> #include <lua.hpp> #include "util/debug.h" #include "util/exception.h" #include "util/memory.h" #include "bindings/lua/leanlua_state.h" #include "bindings/lua/util.h" #include "bindings/lua/name.h" #include "bindings/lua/numerics.h" #include "bindings/lua/options.h" #include "bindings/lua/sexpr.h" #include "bindings/lua/format.h" #include "bindings/lua/level.h" #include "bindings/lua/local_context.h" #include "bindings/lua/expr.h" #include "bindings/lua/context.h" #include "bindings/lua/environment.h" #include "bindings/lua/lean.lua" extern "C" void * lua_realloc(void *, void * q, size_t, size_t new_size) { return lean::realloc(q, new_size); } namespace lean { static void open_state(lua_State * L); static void open_thread(lua_State * L); static void copy_values(lua_State * src, int first, int last, lua_State * tgt) { for (int i = first; i <= last; i++) { if (lua_isstring(src, i)) { lua_pushfstring(tgt, lua_tostring(src, i)); } else if (lua_isnumber(src, i)) { lua_pushnumber(tgt, lua_tonumber(src, i)); } else if (is_expr(src, i)) { push_expr(tgt, to_expr(src, i)); } else if (is_context(src, i)) { push_context(tgt, to_context(src, i)); } else if (is_name(src, i)) { push_name(tgt, to_name(src, i)); } else if (is_mpz(src, i)) { push_mpz(tgt, to_mpz(src, i)); } else if (is_mpq(src, i)) { push_mpq(tgt, to_mpq(src, i)); } else if (is_options(src, i)) { push_options(tgt, to_options(src, i)); } else if (is_sexpr(src, i)) { push_sexpr(tgt, to_sexpr(src, i)); } else if (is_format(src, i)) { push_format(tgt, to_format(src, i)); } else if (is_context_entry(src, i)) { push_context_entry(tgt, to_context_entry(src, i)); } else if (is_local_context(src, i)) { push_local_context(tgt, to_local_context(src, i)); } else if (is_local_entry(src, i)) { push_local_entry(tgt, to_local_entry(src, i)); } else { throw exception("unsupported value type for inter-State call"); } } } struct leanlua_state::imp { lua_State * m_state; std::mutex m_mutex; imp() { // TODO(Leo) investigate why TCMALLOC + lua_realloc do not work together // #ifdef LEAN_USE_LUA_NEWSTATE #if 0 m_state = lua_newstate(lua_realloc, nullptr); #else m_state = luaL_newstate(); #endif if (m_state == nullptr) throw exception("fail to create Lua interpreter"); luaL_openlibs(m_state); open_name(m_state); open_mpz(m_state); open_mpq(m_state); open_options(m_state); open_sexpr(m_state); open_format(m_state); open_level(m_state); open_local_context(m_state); open_expr(m_state); open_context(m_state); open_environment(m_state); open_state(m_state); open_thread(m_state); dostring(g_leanlua_extra); } ~imp() { lua_close(m_state); } void dofile(char const * fname) { std::lock_guard<std::mutex> lock(m_mutex); ::lean::dofile(m_state, fname); } void dostring(char const * str) { std::lock_guard<std::mutex> lock(m_mutex); ::lean::dostring(m_state, str); } void dostring(char const * str, environment & env) { set_environment set(m_state, env); dostring(str); } }; leanlua_state::leanlua_state(): m_ptr(new imp()) { } leanlua_state::~leanlua_state() { } void leanlua_state::dofile(char const * fname) { m_ptr->dofile(fname); } void leanlua_state::dostring(char const * str) { m_ptr->dostring(str); } void leanlua_state::dostring(char const * str, environment & env) { m_ptr->dostring(str, env); } constexpr char const * state_mt = "state.mt"; bool is_state(lua_State * L, int idx) { return testudata(L, idx, state_mt); } leanlua_state & to_state(lua_State * L, int idx) { return *static_cast<leanlua_state*>(luaL_checkudata(L, idx, state_mt)); } int push_state(lua_State * L, leanlua_state const & s) { void * mem = lua_newuserdata(L, sizeof(leanlua_state)); new (mem) leanlua_state(s); luaL_getmetatable(L, state_mt); lua_setmetatable(L, -2); return 1; } static int mk_state(lua_State * L) { leanlua_state r; return push_state(L, r); } static int state_gc(lua_State * L) { to_state(L, 1).~leanlua_state(); return 0; } int state_dostring(lua_State * L) { auto S = to_state(L, 1).m_ptr; char const * script = luaL_checkstring(L, 2); int first = 3; int last = lua_gettop(L); std::lock_guard<std::mutex> lock(S->m_mutex); int sz_before = lua_gettop(S->m_state); int result = luaL_loadstring(S->m_state, script); if (result) throw lua_exception(lua_tostring(S->m_state, -1)); copy_values(L, first, last, S->m_state); result = lua_pcall(S->m_state, first > last ? 0 : last - first + 1, LUA_MULTRET, 0); if (result) throw lua_exception(lua_tostring(S->m_state, -1)); int sz_after = lua_gettop(S->m_state); if (sz_after > sz_before) { copy_values(S->m_state, sz_before + 1, sz_after, L); lua_pop(S->m_state, sz_after - sz_before); } return sz_after - sz_before; } static int state_pred(lua_State * L) { lua_pushboolean(L, is_state(L, 1)); return 1; } static const struct luaL_Reg state_m[] = { {"__gc", state_gc}, {"dostring", safe_function<state_dostring>}, {0, 0} }; static void open_state(lua_State * L) { luaL_newmetatable(L, state_mt); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); setfuncs(L, state_m, 0); set_global_function<mk_state>(L, "State"); set_global_function<state_pred>(L, "is_State"); } class leanlua_thread { leanlua_state m_state; int m_sz_before; bool m_error; std::string m_error_msg; std::thread m_thread; public: leanlua_thread(leanlua_state const & st, int sz_before, int num_args): m_state(st), m_sz_before(sz_before), m_error(false), m_thread([=]() { auto S = m_state.m_ptr; std::lock_guard<std::mutex> lock(S->m_mutex); int result = lua_pcall(S->m_state, num_args, LUA_MULTRET, 0); if (result) { m_error = true; m_error_msg = lua_tostring(S->m_state, -1); return; } }) { } ~leanlua_thread() { if (m_thread.joinable()) m_thread.join(); } int wait(lua_State * src) { m_thread.join(); if (m_error) throw lua_exception(m_error_msg.c_str()); auto S = m_state.m_ptr; int sz_after = lua_gettop(S->m_state); if (sz_after > m_sz_before) { copy_values(S->m_state, m_sz_before + 1, sz_after, src); lua_pop(S->m_state, sz_after - m_sz_before); } return sz_after - m_sz_before; } }; constexpr char const * thread_mt = "thread.mt"; bool is_thread(lua_State * L, int idx) { return testudata(L, idx, thread_mt); } leanlua_thread & to_thread(lua_State * L, int idx) { return *static_cast<leanlua_thread*>(luaL_checkudata(L, idx, thread_mt)); } int mk_thread(lua_State * L) { leanlua_state & st = to_state(L, 1); char const * script = luaL_checkstring(L, 2); int first = 3; int last = lua_gettop(L); int nargs = first > last ? 0 : last - first + 1; int sz_before; auto S = st.m_ptr; { std::lock_guard<std::mutex> lock(S->m_mutex); sz_before = lua_gettop(S->m_state); int result = luaL_loadstring(S->m_state, script); if (result) throw lua_exception(lua_tostring(S->m_state, -1)); copy_values(L, first, last, S->m_state); } void * mem = lua_newuserdata(L, sizeof(leanlua_thread)); new (mem) leanlua_thread(st, sz_before, nargs); luaL_getmetatable(L, thread_mt); lua_setmetatable(L, -2); return 1; } static int thread_gc(lua_State * L) { to_thread(L, 1).~leanlua_thread(); return 0; } static int thread_pred(lua_State * L) { lua_pushboolean(L, is_thread(L, 1)); return 1; } int thread_wait(lua_State * L) { return to_thread(L, 1).wait(L); } static const struct luaL_Reg thread_m[] = { {"__gc", thread_gc}, {"wait", safe_function<thread_wait>}, {0, 0} }; static void open_thread(lua_State * L) { luaL_newmetatable(L, thread_mt); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); setfuncs(L, thread_m, 0); set_global_function<mk_thread>(L, "thread"); set_global_function<thread_pred>(L, "is_thread"); } }
disable custom allocation for Lua, it is crashing
fix(lua): disable custom allocation for Lua, it is crashing Signed-off-by: Leonardo de Moura <[email protected]>
C++
apache-2.0
fpvandoorn/lean,Kha/lean,leanprover/lean,digama0/lean,digama0/lean,codyroux/lean0.1,dselsam/lean,avigad/lean,c-cube/lean,eigengrau/lean,codyroux/lean0.1,soonhokong/travis_test,soonhokong/lean-windows,leanprover/lean,Kha/lean,htzh/lean,fpvandoorn/lean,soonhokong/lean,UlrikBuchholtz/lean,leodemoura/lean,rlewis1988/lean,soonhokong/lean-osx,avigad/lean,avigad/lean,fpvandoorn/lean2,levnach/lean,sp3ctum/lean,UlrikBuchholtz/lean,fpvandoorn/lean,leanprover/lean,soonhokong/travis_test,johoelzl/lean,sp3ctum/lean,soonhokong/lean-osx,soonhokong/lean-windows,soonhokong/lean,rlewis1988/lean,leodemoura/lean,johoelzl/lean,johoelzl/lean,c-cube/lean,Kha/lean,soonhokong/lean-windows,leanprover/lean,fgdorais/lean,rlewis1988/lean,UlrikBuchholtz/lean,Kha/lean,johoelzl/lean,soonhokong/lean-windows,htzh/lean,fgdorais/lean,javra/lean,codyroux/lean0.1,johoelzl/lean,soonhokong/lean-osx,digama0/lean,fpvandoorn/lean2,javra/lean,soonhokong/lean-osx,c-cube/lean,Kha/lean,soonhokong/lean-osx,htzh/lean,levnach/lean,eigengrau/lean,sp3ctum/lean,leanprover-community/lean,leanprover-community/lean,javra/lean,leodemoura/lean,htzh/lean,leanprover/lean,leodemoura/lean,javra/lean,fpvandoorn/lean,UlrikBuchholtz/lean,fpvandoorn/lean,leanprover-community/lean,soonhokong/lean,Kha/lean,fpvandoorn/lean2,levnach/lean,fgdorais/lean,eigengrau/lean,fpvandoorn/lean2,fgdorais/lean,avigad/lean,dselsam/lean,leanprover-community/lean,dselsam/lean,soonhokong/lean,UlrikBuchholtz/lean,leodemoura/lean,dselsam/lean,rlewis1988/lean,fpvandoorn/lean,soonhokong/lean-windows,levnach/lean,johoelzl/lean,codyroux/lean0.1,digama0/lean,sp3ctum/lean,dselsam/lean,avigad/lean,sp3ctum/lean,fgdorais/lean,avigad/lean,soonhokong/travis_test,digama0/lean,dselsam/lean,fgdorais/lean,levnach/lean,javra/lean,leanprover/lean,eigengrau/lean,rlewis1988/lean,fpvandoorn/lean2,htzh/lean,c-cube/lean,soonhokong/lean,eigengrau/lean,leodemoura/lean,rlewis1988/lean,c-cube/lean,leanprover-community/lean,soonhokong/travis_test,leanprover-community/lean,digama0/lean
d24e6d87d2461f897fe08f1ea4424bebc9feb074
stingraykit/log/Logger.cpp
stingraykit/log/Logger.cpp
// Copyright (c) 2011 - 2019, GS Group, https://github.com/GSGroup // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, // provided that the above copyright notice and this permission notice appear in all copies. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include <stingraykit/log/Logger.h> #include <stingraykit/log/SystemLogger.h> #include <stingraykit/string/StringFormat.h> #include <stingraykit/time/TimeEngine.h> #include <stingraykit/FunctionToken.h> #include <stingraykit/SafeSingleton.h> #include <stingraykit/lazy.h> #include <string.h> namespace stingray { namespace { struct NamedLoggerSettings { private: optional<LogLevel> _logLevel; bool _backtrace; bool _highlight; public: NamedLoggerSettings() : _backtrace(false), _highlight(false) { } optional<LogLevel> GetLogLevel() const { return _logLevel; } void SetLogLevel(optional<LogLevel> logLevel) { _logLevel = logLevel; } bool BacktraceEnabled() const { return _backtrace; } void EnableBacktrace(bool enable) { _backtrace = enable; } bool HighlightEnabled() const { return _highlight; } void EnableHighlight(bool enable) { _highlight = enable; } bool IsEmpty() const { return !_logLevel && !_backtrace && !_highlight; } }; class NamedLoggerRegistry { struct StrLess { bool operator () (const char* l, const char* r) const { return strcmp(l, r) < 0; } }; using SettingsRegistry = std::map<std::string, NamedLoggerSettings>; using ObjectsRegistry = std::multimap<const char*, NamedLogger*, StrLess>; private: Mutex _mutex; SettingsRegistry _settings; ObjectsRegistry _objects; public: ObjectsRegistry::const_iterator Register(const char* loggerName, NamedLogger* logger) { MutexLock l(_mutex); const SettingsRegistry::const_iterator it = _settings.find(loggerName); if (it != _settings.end()) { logger->SetLogLevel(it->second.GetLogLevel()); logger->EnableBacktrace(it->second.BacktraceEnabled()); logger->EnableHighlight(it->second.HighlightEnabled()); } return _objects.emplace(loggerName, logger); } void Unregister(ObjectsRegistry::const_iterator it) { MutexLock l(_mutex); _objects.erase(it); } std::set<std::string> GetLoggerNames() const { MutexLock l(_mutex); return std::set<std::string>(keys_iterator(_objects.begin()), keys_iterator(_objects.end())); } void SetLogLevel(const std::string& loggerName, optional<LogLevel> logLevel) { MutexLock l(_mutex); const std::pair<ObjectsRegistry::iterator, ObjectsRegistry::iterator> range = _objects.equal_range(loggerName.c_str()); for (ObjectsRegistry::iterator it = range.first; it != range.second; ++it) it->second->SetLogLevel(logLevel); const SettingsRegistry::iterator it = _settings.emplace(loggerName, NamedLoggerSettings()).first; it->second.SetLogLevel(logLevel); if (it->second.IsEmpty()) _settings.erase(it); } void EnableBacktrace(const std::string& loggerName, bool enable) { MutexLock l(_mutex); const std::pair<ObjectsRegistry::iterator, ObjectsRegistry::iterator> range = _objects.equal_range(loggerName.c_str()); for (ObjectsRegistry::iterator it = range.first; it != range.second; ++it) it->second->EnableBacktrace(enable); const SettingsRegistry::iterator it = _settings.emplace(loggerName, NamedLoggerSettings()).first; it->second.EnableBacktrace(enable); if (it->second.IsEmpty()) _settings.erase(it); } void EnableHighlight(const std::string& loggerName, bool enable) { MutexLock l(_mutex); const std::pair<ObjectsRegistry::iterator, ObjectsRegistry::iterator> range = _objects.equal_range(loggerName.c_str()); for (ObjectsRegistry::iterator it = range.first; it != range.second; ++it) it->second->EnableHighlight(enable); const SettingsRegistry::iterator it = _settings.emplace(loggerName, NamedLoggerSettings()).first; it->second.EnableHighlight(enable); if (it->second.IsEmpty()) _settings.erase(it); } }; class LoggerImpl { using SinksBundle = std::vector<ILoggerSinkPtr>; private: SinksBundle _sinks; Mutex _logMutex; NamedLoggerRegistry _registry; public: void AddSink(const ILoggerSinkPtr& sink) { MutexLock l(_logMutex); _sinks.push_back(sink); } void RemoveSink(const ILoggerSinkPtr& sink) { MutexLock l(_logMutex); SinksBundle::iterator it = std::find(_sinks.begin(), _sinks.end(), sink); if (it != _sinks.end()) _sinks.erase(it); } void Log(const LoggerMessage& message) noexcept { try { EnableInterruptionPoints eip(false); SinksBundle sinks; { MutexLock l(_logMutex); sinks = _sinks; } if (sinks.empty()) SystemLogger::Log(message); else PutMessageToSinks(sinks, message); } catch (const std::exception&) { } } NamedLoggerRegistry& GetRegistry() { return _registry; } private: static void PutMessageToSinks(const SinksBundle& sinks, const LoggerMessage& message) { for (SinksBundle::const_iterator it = sinks.begin(); it != sinks.end(); ++it) { try { (*it)->Log(message); } catch (const std::exception&) { } } } }; STINGRAYKIT_DECLARE_PTR(LoggerImpl); using LoggerSingleton = SafeSingleton<LoggerImpl>; u32 GlobalLogLevel = (u32)LogLevel::STINGRAY_DEFAULT_LOGLEVEL; } ///////////////////////////////////////////////////////////////// void Logger::SetLogLevel(LogLevel logLevel) { AtomicU32::Store(GlobalLogLevel, (u32)logLevel.val(), MemoryOrderRelaxed); Stream(logLevel) << "Log level is " << logLevel; } LogLevel Logger::GetLogLevel() { return (LogLevel::Enum)AtomicU32::Load(GlobalLogLevel, MemoryOrderRelaxed); } LoggerStream Logger::Stream(LogLevel logLevel, DuplicatingLogsFilter* duplicatingLogsFilter) { return LoggerStream(null, GetLogLevel(), logLevel, duplicatingLogsFilter, &Logger::DoLog); } void Logger::SetLogLevel(const std::string& loggerName, optional<LogLevel> logLevel) { if (const LoggerImplPtr logger = LoggerSingleton::Instance()) logger->GetRegistry().SetLogLevel(loggerName, logLevel); } void Logger::EnableBacktrace(const std::string& loggerName, bool enable) { if (const LoggerImplPtr logger = LoggerSingleton::Instance()) logger->GetRegistry().EnableBacktrace(loggerName, enable); } void Logger::EnableHighlight(const std::string& loggerName, bool enable) { if (const LoggerImplPtr logger = LoggerSingleton::Instance()) logger->GetRegistry().EnableHighlight(loggerName, enable); } std::set<std::string> Logger::GetLoggerNames() { if (const LoggerImplPtr logger = LoggerSingleton::Instance()) return logger->GetRegistry().GetLoggerNames(); else return std::set<std::string>(); } Token Logger::AddSink(const ILoggerSinkPtr& sink) { const LoggerImplPtr logger = LoggerSingleton::Instance(); if (!logger) return null; logger->AddSink(sink); return MakeFunctionToken(Bind(&LoggerImpl::RemoveSink, logger, sink)); } void Logger::DoLog(const NamedLoggerParams* loggerParams, LogLevel logLevel, const std::string& text) { optional<LoggerMessage> msg; if (loggerParams) msg.emplace(loggerParams->GetName(), logLevel, loggerParams->BacktraceEnabled() ? StringBuilder() % text % ": " % Backtrace() : text, loggerParams->HighlightEnabled()); else msg.emplace(logLevel, text, false); if (const LoggerImplPtr logger = LoggerSingleton::Instance()) logger->Log(*msg); else SystemLogger::Log(*msg); } ///////////////////////////////////////////////////////////////// NamedLogger::NamedLogger(const char* name, optional<LogLevel> logLevel) : _params(name), _logLevel(OptionalLogLevel::FromLogLevel(logLevel)) { if (const LoggerImplPtr logger = LoggerSingleton::Instance()) _token = MakeFunctionToken(Bind(&NamedLoggerRegistry::Unregister, Bind(&LoggerImpl::GetRegistry, logger), logger->GetRegistry().Register(_params.GetName(), this))); } LogLevel NamedLogger::GetLogLevel() const { return OptionalLogLevel::ToLogLevel(_logLevel.load(MemoryOrderRelaxed)).get_value_or(lazy(&Logger::GetLogLevel)); } void NamedLogger::SetLogLevel(optional<LogLevel> logLevel) { _logLevel.store(OptionalLogLevel::FromLogLevel(logLevel), MemoryOrderRelaxed); Stream(GetLogLevel()) << "Log level is " << logLevel; } bool NamedLogger::BacktraceEnabled() const { return _params.BacktraceEnabled(); } void NamedLogger::EnableBacktrace(bool enable) { _params.EnableBacktrace(enable); Stream(GetLogLevel()) << "Backtrace " << (enable ? "enabled" : "disabled"); } bool NamedLogger::HighlightEnabled() const { return _params.HighlightEnabled(); } void NamedLogger::EnableHighlight(bool enable) { _params.EnableHighlight(enable); } LoggerStream NamedLogger::Stream(LogLevel logLevel) const { return LoggerStream(&_params, GetLogLevel(), logLevel, &_duplicatingLogsFilter, &Logger::DoLog); } ///////////////////////////////////////////////////////////////// namespace { class ElapsedMillisecondsToString { private: const ElapsedTime& _elapsed; public: explicit ElapsedMillisecondsToString(const ElapsedTime& elapsed) : _elapsed(elapsed) { } std::string ToString() const { s64 ms = 0; int mms = 0; try { const s64 elapsed = _elapsed.ElapsedMicroseconds(); ms = elapsed / 1000; mms = elapsed % 1000; } catch (const std::exception&) { } return StringBuilder() % ms % "." % mms; } }; } ActionLogger::ActionLogger(const std::string& action) : _namedLogger(NULL), _logLevel(LogLevel::Info), _action(action) { Logger::Info() << _action << "..."; } ActionLogger::ActionLogger(LogLevel logLevel, const std::string& action) : _namedLogger(NULL), _logLevel(logLevel), _action(action) { Logger::Stream(logLevel) << _action << "..."; } ActionLogger::ActionLogger(const NamedLogger& namedLogger, const std::string& action) : _namedLogger(&namedLogger), _logLevel(LogLevel::Info), _action(action) { _namedLogger->Info() << _action << "..."; } ActionLogger::ActionLogger(const NamedLogger& namedLogger, LogLevel logLevel, const std::string& action) : _namedLogger(&namedLogger), _logLevel(logLevel), _action(action) { _namedLogger->Stream(logLevel) << _action << "..."; } ActionLogger::~ActionLogger() { if (std::uncaught_exception()) { try { if (_namedLogger) _namedLogger->Stream(_logLevel) << _action << " completed with exception in " << ElapsedMillisecondsToString(_elapsedTime) << " ms"; else Logger::Stream(_logLevel) << _action << " completed with exception in " << ElapsedMillisecondsToString(_elapsedTime) << " ms"; } catch (const std::exception&) { return; } } else { if (_namedLogger) _namedLogger->Stream(_logLevel) << _action << " completed in " << ElapsedMillisecondsToString(_elapsedTime) << " ms"; else Logger::Stream(_logLevel) << _action << " completed in " << ElapsedMillisecondsToString(_elapsedTime) << " ms"; } } ///////////////////////////////////////////////////////////////// namespace Detail { namespace LoggerDetail { NullPtrType s_logger; // Static logger fallback }} ///////////////////////////////////////////////////////////////// Tracer::Tracer(const Detail::NamedLoggerAccessor& logger, const char* funcName) : _logger(logger), _logLevel(logger.GetLogLevel()), _funcName(funcName) { if (_logLevel > LogLevel::Trace) return; _startTime = TimeEngine::GetMonotonicMicroseconds(); _logger.Trace() << "TRACER: entering function '" << _funcName << "'"; } Tracer::~Tracer() { if (_logLevel > LogLevel::Trace) return; try { s64 e = TimeEngine::GetMonotonicMicroseconds() - _startTime; s64 ms = e / 1000; int mms = e % 1000; if (std::uncaught_exception()) _logger.Trace() << "TRACER: leaving function '" << _funcName << "' due to an exception (" << StringFormat("%1%.%2$3%", ms, mms) << " ms)"; else _logger.Trace() << "TRACER: leaving function '" << _funcName << "' (" << StringFormat("%1%.%2$3%", ms, mms) << " ms)"; } catch (const std::exception&) { } } }
// Copyright (c) 2011 - 2019, GS Group, https://github.com/GSGroup // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, // provided that the above copyright notice and this permission notice appear in all copies. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include <stingraykit/log/Logger.h> #include <stingraykit/log/SystemLogger.h> #include <stingraykit/string/StringFormat.h> #include <stingraykit/time/TimeEngine.h> #include <stingraykit/FunctionToken.h> #include <stingraykit/SafeSingleton.h> #include <stingraykit/lazy.h> #include <string.h> namespace stingray { namespace { struct NamedLoggerSettings { private: optional<LogLevel> _logLevel; bool _backtrace; bool _highlight; public: NamedLoggerSettings() : _backtrace(false), _highlight(false) { } optional<LogLevel> GetLogLevel() const { return _logLevel; } void SetLogLevel(optional<LogLevel> logLevel) { _logLevel = logLevel; } bool BacktraceEnabled() const { return _backtrace; } void EnableBacktrace(bool enable) { _backtrace = enable; } bool HighlightEnabled() const { return _highlight; } void EnableHighlight(bool enable) { _highlight = enable; } bool IsEmpty() const { return !_logLevel && !_backtrace && !_highlight; } }; class NamedLoggerRegistry { struct StrLess { bool operator () (const char* l, const char* r) const { return strcmp(l, r) < 0; } }; using SettingsRegistry = std::map<std::string, NamedLoggerSettings>; using ObjectsRegistry = std::multimap<const char*, NamedLogger*, StrLess>; private: Mutex _mutex; SettingsRegistry _settings; ObjectsRegistry _objects; public: ObjectsRegistry::const_iterator Register(const char* loggerName, NamedLogger* logger) { MutexLock l(_mutex); const SettingsRegistry::const_iterator it = _settings.find(loggerName); if (it != _settings.end()) { logger->SetLogLevel(it->second.GetLogLevel()); logger->EnableBacktrace(it->second.BacktraceEnabled()); logger->EnableHighlight(it->second.HighlightEnabled()); } return _objects.emplace(loggerName, logger); } void Unregister(ObjectsRegistry::const_iterator it) { MutexLock l(_mutex); _objects.erase(it); } std::set<std::string> GetLoggerNames() const { MutexLock l(_mutex); return std::set<std::string>(keys_iterator(_objects.begin()), keys_iterator(_objects.end())); } void SetLogLevel(const std::string& loggerName, optional<LogLevel> logLevel) { MutexLock l(_mutex); const std::pair<ObjectsRegistry::iterator, ObjectsRegistry::iterator> range = _objects.equal_range(loggerName.c_str()); for (ObjectsRegistry::iterator it = range.first; it != range.second; ++it) it->second->SetLogLevel(logLevel); const SettingsRegistry::iterator it = _settings.emplace(loggerName, NamedLoggerSettings()).first; it->second.SetLogLevel(logLevel); if (it->second.IsEmpty()) _settings.erase(it); } void EnableBacktrace(const std::string& loggerName, bool enable) { MutexLock l(_mutex); const std::pair<ObjectsRegistry::iterator, ObjectsRegistry::iterator> range = _objects.equal_range(loggerName.c_str()); for (ObjectsRegistry::iterator it = range.first; it != range.second; ++it) it->second->EnableBacktrace(enable); const SettingsRegistry::iterator it = _settings.emplace(loggerName, NamedLoggerSettings()).first; it->second.EnableBacktrace(enable); if (it->second.IsEmpty()) _settings.erase(it); } void EnableHighlight(const std::string& loggerName, bool enable) { MutexLock l(_mutex); const std::pair<ObjectsRegistry::iterator, ObjectsRegistry::iterator> range = _objects.equal_range(loggerName.c_str()); for (ObjectsRegistry::iterator it = range.first; it != range.second; ++it) it->second->EnableHighlight(enable); const SettingsRegistry::iterator it = _settings.emplace(loggerName, NamedLoggerSettings()).first; it->second.EnableHighlight(enable); if (it->second.IsEmpty()) _settings.erase(it); } }; class LoggerImpl { using SinksBundle = std::vector<ILoggerSinkPtr>; private: SinksBundle _sinks; Mutex _logMutex; NamedLoggerRegistry _registry; public: void AddSink(const ILoggerSinkPtr& sink) { MutexLock l(_logMutex); _sinks.push_back(sink); } void RemoveSink(const ILoggerSinkPtr& sink) { MutexLock l(_logMutex); SinksBundle::iterator it = std::find(_sinks.begin(), _sinks.end(), sink); if (it != _sinks.end()) _sinks.erase(it); } void Log(const LoggerMessage& message) noexcept { try { EnableInterruptionPoints eip(false); SinksBundle sinks; { MutexLock l(_logMutex); sinks = _sinks; } if (sinks.empty()) SystemLogger::Log(message); else PutMessageToSinks(sinks, message); } catch (const std::exception&) { } } NamedLoggerRegistry& GetRegistry() { return _registry; } private: static void PutMessageToSinks(const SinksBundle& sinks, const LoggerMessage& message) { for (SinksBundle::const_iterator it = sinks.begin(); it != sinks.end(); ++it) { try { (*it)->Log(message); } catch (const std::exception&) { } } } }; STINGRAYKIT_DECLARE_PTR(LoggerImpl); using LoggerSingleton = SafeSingleton<LoggerImpl>; u32 GlobalLogLevel = (u32)LogLevel::STINGRAY_DEFAULT_LOGLEVEL; } ///////////////////////////////////////////////////////////////// void Logger::SetLogLevel(LogLevel logLevel) { AtomicU32::Store(GlobalLogLevel, (u32)logLevel.val(), MemoryOrderRelaxed); Stream(logLevel) << "Log level is " << logLevel; } LogLevel Logger::GetLogLevel() { return (LogLevel::Enum)AtomicU32::Load(GlobalLogLevel, MemoryOrderRelaxed); } LoggerStream Logger::Stream(LogLevel logLevel, DuplicatingLogsFilter* duplicatingLogsFilter) { return LoggerStream(null, GetLogLevel(), logLevel, duplicatingLogsFilter, &Logger::DoLog); } void Logger::SetLogLevel(const std::string& loggerName, optional<LogLevel> logLevel) { if (const LoggerImplPtr logger = LoggerSingleton::Instance()) logger->GetRegistry().SetLogLevel(loggerName, logLevel); } void Logger::EnableBacktrace(const std::string& loggerName, bool enable) { if (const LoggerImplPtr logger = LoggerSingleton::Instance()) logger->GetRegistry().EnableBacktrace(loggerName, enable); } void Logger::EnableHighlight(const std::string& loggerName, bool enable) { if (const LoggerImplPtr logger = LoggerSingleton::Instance()) logger->GetRegistry().EnableHighlight(loggerName, enable); } std::set<std::string> Logger::GetLoggerNames() { if (const LoggerImplPtr logger = LoggerSingleton::Instance()) return logger->GetRegistry().GetLoggerNames(); else return std::set<std::string>(); } Token Logger::AddSink(const ILoggerSinkPtr& sink) { const LoggerImplPtr logger = LoggerSingleton::Instance(); if (!logger) return null; logger->AddSink(sink); return MakeFunctionToken(Bind(&LoggerImpl::RemoveSink, logger, sink)); } void Logger::DoLog(const NamedLoggerParams* loggerParams, LogLevel logLevel, const std::string& text) { optional<LoggerMessage> msg; if (loggerParams) msg.emplace(loggerParams->GetName(), logLevel, loggerParams->BacktraceEnabled() ? StringBuilder() % text % ": " % Backtrace() : text, loggerParams->HighlightEnabled()); else msg.emplace(logLevel, text, false); if (const LoggerImplPtr logger = LoggerSingleton::Instance()) logger->Log(*msg); else SystemLogger::Log(*msg); } ///////////////////////////////////////////////////////////////// NamedLogger::NamedLogger(const char* name, optional<LogLevel> logLevel) : _params(name), _logLevel(OptionalLogLevel::FromLogLevel(logLevel)) { if (const LoggerImplPtr logger = LoggerSingleton::Instance()) _token = MakeFunctionToken(Bind(&NamedLoggerRegistry::Unregister, Bind(&LoggerImpl::GetRegistry, logger), logger->GetRegistry().Register(_params.GetName(), this))); } LogLevel NamedLogger::GetLogLevel() const { return OptionalLogLevel::ToLogLevel(_logLevel.load(MemoryOrderRelaxed)).get_value_or(lazy(&Logger::GetLogLevel)); } void NamedLogger::SetLogLevel(optional<LogLevel> logLevel) { _logLevel.store(OptionalLogLevel::FromLogLevel(logLevel), MemoryOrderRelaxed); Stream(GetLogLevel()) << "Log level is " << logLevel; } bool NamedLogger::BacktraceEnabled() const { return _params.BacktraceEnabled(); } void NamedLogger::EnableBacktrace(bool enable) { _params.EnableBacktrace(enable); Stream(GetLogLevel()) << "Backtrace " << (enable ? "enabled" : "disabled"); } bool NamedLogger::HighlightEnabled() const { return _params.HighlightEnabled(); } void NamedLogger::EnableHighlight(bool enable) { _params.EnableHighlight(enable); } LoggerStream NamedLogger::Stream(LogLevel logLevel) const { return LoggerStream(&_params, GetLogLevel(), logLevel, &_duplicatingLogsFilter, &Logger::DoLog); } ///////////////////////////////////////////////////////////////// namespace { class ElapsedMillisecondsToString { private: const ElapsedTime& _elapsed; public: explicit ElapsedMillisecondsToString(const ElapsedTime& elapsed) : _elapsed(elapsed) { } std::string ToString() const { s64 ms = 0; int mms = 0; try { const s64 elapsed = _elapsed.ElapsedMicroseconds(); ms = elapsed / 1000; mms = elapsed % 1000; } catch (const std::exception&) { } return StringBuilder() % ms % "." % mms; } }; } ActionLogger::ActionLogger(const std::string& action) : _namedLogger(NULL), _logLevel(LogLevel::Info), _action(action) { Logger::Info() << _action << "..."; } ActionLogger::ActionLogger(LogLevel logLevel, const std::string& action) : _namedLogger(NULL), _logLevel(logLevel), _action(action) { Logger::Stream(logLevel) << _action << "..."; } ActionLogger::ActionLogger(const NamedLogger& namedLogger, const std::string& action) : _namedLogger(&namedLogger), _logLevel(LogLevel::Info), _action(action) { _namedLogger->Info() << _action << "..."; } ActionLogger::ActionLogger(const NamedLogger& namedLogger, LogLevel logLevel, const std::string& action) : _namedLogger(&namedLogger), _logLevel(logLevel), _action(action) { _namedLogger->Stream(logLevel) << _action << "..."; } ActionLogger::~ActionLogger() { if (std::uncaught_exception()) { try { if (_namedLogger) _namedLogger->Stream(_logLevel) << _action << " completed with exception in " << ElapsedMillisecondsToString(_elapsedTime) << " ms"; else Logger::Stream(_logLevel) << _action << " completed with exception in " << ElapsedMillisecondsToString(_elapsedTime) << " ms"; } catch (const std::exception&) { } } else if (_namedLogger) _namedLogger->Stream(_logLevel) << _action << " completed in " << ElapsedMillisecondsToString(_elapsedTime) << " ms"; else Logger::Stream(_logLevel) << _action << " completed in " << ElapsedMillisecondsToString(_elapsedTime) << " ms"; } ///////////////////////////////////////////////////////////////// namespace Detail { namespace LoggerDetail { NullPtrType s_logger; // Static logger fallback }} ///////////////////////////////////////////////////////////////// Tracer::Tracer(const Detail::NamedLoggerAccessor& logger, const char* funcName) : _logger(logger), _logLevel(logger.GetLogLevel()), _funcName(funcName) { if (_logLevel > LogLevel::Trace) return; _startTime = TimeEngine::GetMonotonicMicroseconds(); _logger.Trace() << "TRACER: entering function '" << _funcName << "'"; } Tracer::~Tracer() { if (_logLevel > LogLevel::Trace) return; try { s64 e = TimeEngine::GetMonotonicMicroseconds() - _startTime; s64 ms = e / 1000; int mms = e % 1000; if (std::uncaught_exception()) _logger.Trace() << "TRACER: leaving function '" << _funcName << "' due to an exception (" << StringFormat("%1%.%2$3%", ms, mms) << " ms)"; else _logger.Trace() << "TRACER: leaving function '" << _funcName << "' (" << StringFormat("%1%.%2$3%", ms, mms) << " ms)"; } catch (const std::exception&) { } } }
drop redundant return, drop redundant scope
Logger: drop redundant return, drop redundant scope
C++
isc
GSGroup/stingraykit,GSGroup/stingraykit
b1643aed1c43bc3e779722c3768cc348ffffa73d
src/map/src/entity_system.cpp
src/map/src/entity_system.cpp
#include "entity_system.h" #include "cmapclient.h" #include "enumerate.h" #include "itemdb.h" #include <entt.hpp> #include "components/basic_info.h" #include "components/client.h" #include "components/computed_values.h" #include "components/faction.h" #include "components/character_graphics.h" #include "components/guild.h" #include "components/hotbar.h" #include "components/inventory.h" #include "components/item.h" #include "components/level.h" #include "components/life.h" #include "components/magic.h" #include "components/npc.h" #include "components/owner.h" #include "components/position.h" #include "components/skills.h" #include "components/stamina.h" #include "components/stats.h" #include "components/status_effects.h" #include "components/wishlist.h" #include "chat/normal_chat.h" EntitySystem::EntitySystem(std::chrono::milliseconds maxTimePerUpdate) : maxTimePerUpdate(maxTimePerUpdate) { logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); // register recurrent stoof (like saving every 5min) using namespace std::chrono_literals; add_recurrent_timer(5min, [](EntitySystem& self) { self.registry.view<Component::Client>().each([&self](auto entity, auto &client_ptr) { (void)client_ptr; self.save_character(entity); }); }); // callback for nearby calculations registry.construction<Component::Position>().connect<&Nearby::add_entity>(&nearby); registry.destruction<Component::Position>().connect<&Nearby::remove_entity>(&nearby); // dispatcher registration register_dispatcher(std::function{Chat::normal_chat}); } void EntitySystem::stop() { work_queue.kill(); registry.construction<Component::Position>().disconnect<&Nearby::add_entity>(&nearby); registry.destruction<Component::Position>().disconnect<&Nearby::remove_entity>(&nearby); } bool EntitySystem::dispatch_packet(RoseCommon::Entity entity, std::unique_ptr<RoseCommon::CRosePacket>&& packet) { if (!packet) { return false; } if (!dispatcher.is_supported(*packet.get())) { return false; } add_task(std::move([this, entity, packet = std::move(packet)](EntitySystem& entitySystem) mutable { dispatcher.dispatch(entitySystem, entity, std::move(packet)); })); return true; } void EntitySystem::run() { for (auto [res, task] = work_queue.pop_front(); res;) { logger->trace("doing work"); { std::lock_guard<std::mutex> lock(access); std::invoke(std::move(task), *this); } auto [tmp_res, tmp_task] = work_queue.pop_front(); res = tmp_res; task = std::move(tmp_task); } } void EntitySystem::send_map(const RoseCommon::CRosePacket& packet) const { registry.view<const Component::Client>().each([&packet](auto entity, const auto &client_ptr) { (void)entity; if (auto client = client_ptr.client.lock()) { client->send(packet); } }); } void EntitySystem::send_nearby(RoseCommon::Entity entity, const RoseCommon::CRosePacket& packet) const { registry.view<const Component::Client>().each([entity, this, &packet](auto other, const auto &client_ptr) { if (!nearby.is_nearby(*this, entity, other)) return; if (auto client = client_ptr.client.lock()) { client->send(packet); } }); } void EntitySystem::send_nearby_except_me(RoseCommon::Entity entity, const RoseCommon::CRosePacket& packet) const { registry.view<const Component::Client>().each([entity, this, &packet](auto other, const auto &client_ptr) { if (other != entity) { if (!nearby.is_nearby(*this, entity, other)) return; if (auto client = client_ptr.client.lock()) { client->send(packet); } } }); } void EntitySystem::send_to(RoseCommon::Entity entity, const RoseCommon::CRosePacket& packet) const { if (const auto client_ptr = registry.try_get<const Component::Client>(entity)) { if (auto client = client_ptr->client.lock()) { client->send(packet); } } } void EntitySystem::delete_entity(RoseCommon::Entity entity) { add_task([entity](EntitySystem& entitySystem) { entitySystem.registry.destroy(entity); }); } void EntitySystem::update_position(RoseCommon::Entity entity, float x, float y) { if (entity == entt::null) return; auto* pos = try_get_component<Component::Position>(entity); float old_x = 0, old_y = 0; if (!pos) { pos = &add_component<Component::Position>(entity); pos->z = 0; } else { old_x = pos->x; old_y = pos->y; } pos->x = x; pos->y = y; nearby.update_position(entity, old_x, old_y, x, y); } std::vector<RoseCommon::Entity> EntitySystem::get_nearby(RoseCommon::Entity entity) const { return nearby.get_nearby(*this, entity); } RoseCommon::Entity EntitySystem::load_character(uint32_t charId, bool platinium, uint32_t sessionId, std::weak_ptr<CMapClient> client) { using namespace Component; auto conn = Core::connectionPool.getConnection(Core::osirose); Core::CharacterTable characters{}; Core::InventoryTable inventoryTable{}; Core::SkillTable skillsTable{}; auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters)) .from(characters).where(characters.id == charId)); if (static_cast<long>(charRes.front().count) != 1L) { return entt::null; } const auto& charRow = charRes.front(); entt::prototype prototype(registry); auto& basicInfo = prototype.set<BasicInfo>(); basicInfo.name = charRow.name; basicInfo.id = idManager.get_free_id(); basicInfo.tag = sessionId; basicInfo.teamId = basicInfo.id; basicInfo.job = charRow.job; basicInfo.statPoints = charRow.statPoints; basicInfo.skillPoints = charRow.skillPoints; basicInfo.pkFlag = charRow.pkFlag; basicInfo.stone = charRow.stone; basicInfo.charId = charId; auto& component_client = prototype.set<Client>(); component_client.client = client; auto& computedValues = prototype.set<ComputedValues>(); computedValues.command = RoseCommon::Command::STOP; computedValues.moveMode = RoseCommon::MoveMode::WALK; computedValues.runSpeed = 0; computedValues.atkSpeed = 0; computedValues.weightRate = 0; auto& faction = prototype.set<Faction>(); faction.id = charRow.factionid; faction.rank = charRow.factionRank; faction.fame = charRow.fame; faction.factionFame[0] = charRow.factionFame1; faction.factionFame[1] = charRow.factionFame2; faction.points[0] = charRow.factionPoints1; faction.points[1] = charRow.factionPoints2; faction.points[2] = charRow.factionPoints3; auto& characterGraphics = prototype.set<CharacterGraphics>(); characterGraphics.face = charRow.face; characterGraphics.hair = charRow.hair; characterGraphics.race = charRow.race; auto& guild = prototype.set<Guild>(); guild.id = charRow.clanid; guild.contribution = charRow.clanContribution; guild.rank = charRow.clanRank; prototype.set<Hotbar>(); auto invRes = conn(sqlpp::select(sqlpp::all_of(inventoryTable)).from(inventoryTable).where(inventoryTable.charId == charId)); auto& inventory = prototype.set<Inventory>(); for (const auto& row : invRes) { if (row.slot >= RoseCommon::MAX_ITEMS) { continue; } Item item; item.isCreated = false; item.life = 1000; item.hasSocket = row.socket; item.isAppraised = true; item.refine = row.refine; item.count = row.amount; item.gemOpt = row.gemOpt; item.price = 0; inventory.items[row.slot] = load_item(row.itemtype, row.itemid, item); } auto& level = prototype.set<Level>(); level.xp = charRow.exp; level.level = charRow.level; level.penaltyXp = charRow.penaltyExp; auto& life = prototype.set<Life>(); life.hp = charRow.maxHp / 3; // you only get 30% of your health when login in life.maxHp = charRow.maxHp; auto& magic = prototype.set<Magic>(); magic.mp = charRow.maxMp / 3; magic.maxMp = charRow.maxMp; auto& pos = prototype.set<Position>(); pos.x = charRow.x; pos.y = charRow.y; pos.z = 0; pos.spawn = charRow.reviveMap; pos.map = charRow.map; auto skillRes = conn(sqlpp::select(skillsTable.id, skillsTable.level).from(skillsTable).where(skillsTable.charId == charId)); auto& skills = prototype.set<Skills>(); for (const auto& [i, row] : Core::enumerate(skillRes)) { skills.skills[i].set_id(row.id); skills.skills[i].set_level(row.level); } auto& stamina = prototype.set<Stamina>(); stamina.stamina = charRow.stamina; auto& stats = prototype.set<Stats>(); stats.str = charRow.str; stats.dex = charRow.dex; stats.int_ = charRow.int_; stats.con = charRow.con; stats.charm = charRow.charm; stats.sense = charRow.sense; stats.bodySize = 100; stats.headSize = 100; prototype.set<StatusEffects>(); /*auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)).from(wish).where(wish.charId == charId)); auto& wishlist = prototype.set<Wishlist>(); for (const auto& row : wishRes) { if (row.slot >= RoseCommon::MAX_WISHLIST) { continue; } Item item; item.isCreated = false; item.life = 1000; item.hasSocket = row.socket; item.isAppraised = true; item.refine = row.refine; item.count = row.amount; item.gemOpt = row.gemOpt; item.price = row.price; wishlist.items[row.slot] = load_item(row.itemtype, row.itemid, item); }*/ std::lock_guard<std::mutex> lock(access); return prototype(); } void EntitySystem::save_character(RoseCommon::Entity character) { add_task([character](EntitySystem& self) { auto conn = Core::connectionPool.getConnection(Core::osirose); Core::CharacterTable characters{}; using sqlpp::parameter; using namespace Component; const auto& basicInfo = self.get_component<BasicInfo>(character); const auto& faction = self.get_component<Faction>(character); const auto& characterGraphics = self.get_component<CharacterGraphics>(character); const auto& guild = self.get_component<Guild>(character); // TODO: save hotbar // TODO: save inventory const auto& level = self.get_component<Level>(character); const auto& life = self.get_component<Life>(character); const auto& magic = self.get_component<Magic>(character); const auto& pos = self.get_component<Position>(character); // TODO: save skills const auto& stamina = self.get_component<Stamina>(character); const auto& stats = self.get_component<Stats>(character); // TODO: save wishlist conn(sqlpp::update(characters).where(characters.id == basicInfo.charId).set( characters.name = basicInfo.name, characters.job = basicInfo.job, characters.statPoints = basicInfo.statPoints, characters.skillPoints = basicInfo.skillPoints, characters.pkFlag = basicInfo.pkFlag, characters.stone = basicInfo.stone, characters.factionid = faction.id, characters.factionRank = faction.rank, characters.fame = faction.fame, characters.factionFame1 = faction.factionFame[0], characters.factionFame2 = faction.factionFame[1], characters.factionPoints1 = faction.points[0], characters.factionPoints2 = faction.points[1], characters.factionPoints3 = faction.points[2], characters.face = characterGraphics.face, characters.hair = characterGraphics.hair, characters.race = characterGraphics.race, characters.clanid = guild.id, characters.clanContribution = guild.contribution, characters.clanRank = guild.rank, characters.exp = level.xp, characters.level = level.level, characters.penaltyExp = level.penaltyXp, characters.maxHp = life.maxHp, characters.maxMp = magic.maxMp, characters.x = pos.x, characters.y = pos.y, characters.reviveMap = pos.spawn, characters.map = pos.map, characters.stamina = stamina.stamina, characters.str = stats.str, characters.dex = stats.dex, characters.int_ = stats.int_, characters.con = stats.con, characters.charm = stats.charm, characters.sense = stats.sense )); }); } RoseCommon::Entity EntitySystem::create_item(uint8_t type, uint16_t id) { using namespace Component; entt::prototype prototype(registry); const auto &itemDb = RoseCommon::ItemDatabase::getInstance(); if (!itemDb.itemExists(type, id)) { return entt::null; } const auto& def = itemDb.getItemDef(type, id); auto& item = prototype.set<Item>(); item.isCreated = false; item.life = 1000; item.durability = 100; item.hasSocket = false; item.isAppraised = false; item.refine = 0; item.count = 0; item.gemOpt = 0; item.price = 0; prototype.set<RoseCommon::ItemDef>(def); std::lock_guard<std::mutex> lock(access); return prototype(); } RoseCommon::Entity EntitySystem::load_item(uint8_t type, uint16_t id, Component::Item item) { auto entity = create_item(type, id); if (entity == entt::null) { return entt::null; } registry.replace<Component::Item>(entity, item); return entity; } void EntitySystem::save_item(RoseCommon::Entity item, RoseCommon::Entity owner) const { // TODO: should be done as a task??? }
#include "entity_system.h" #include "cmapclient.h" #include "enumerate.h" #include "itemdb.h" #include <entt.hpp> #include "components/basic_info.h" #include "components/client.h" #include "components/computed_values.h" #include "components/faction.h" #include "components/character_graphics.h" #include "components/guild.h" #include "components/hotbar.h" #include "components/inventory.h" #include "components/item.h" #include "components/level.h" #include "components/life.h" #include "components/magic.h" #include "components/npc.h" #include "components/owner.h" #include "components/position.h" #include "components/skills.h" #include "components/stamina.h" #include "components/stats.h" #include "components/status_effects.h" #include "components/wishlist.h" #include "chat/normal_chat.h" EntitySystem::EntitySystem(std::chrono::milliseconds maxTimePerUpdate) : maxTimePerUpdate(maxTimePerUpdate) { logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); // register recurrent stoof (like saving every 5min) using namespace std::chrono_literals; add_recurrent_timer(5min, [](EntitySystem& self) { self.registry.view<Component::Client>().each([&self](auto entity, auto &client_ptr) { (void)client_ptr; self.save_character(entity); }); }); // callback for nearby calculations registry.construction<Component::Position>().connect<&Nearby::add_entity>(&nearby); registry.destruction<Component::Position>().connect<&Nearby::remove_entity>(&nearby); // dispatcher registration register_dispatcher(std::function{Chat::normal_chat}); } void EntitySystem::stop() { work_queue.kill(); registry.construction<Component::Position>().disconnect<&Nearby::add_entity>(&nearby); registry.destruction<Component::Position>().disconnect<&Nearby::remove_entity>(&nearby); } bool EntitySystem::dispatch_packet(RoseCommon::Entity entity, std::unique_ptr<RoseCommon::CRosePacket>&& packet) { if (!packet) { return false; } if (!dispatcher.is_supported(*packet.get())) { return false; } add_task(std::move([this, entity, packet = std::move(packet)](EntitySystem& entitySystem) mutable { dispatcher.dispatch(entitySystem, entity, std::move(packet)); })); return true; } void EntitySystem::run() { for (auto [res, task] = work_queue.pop_front(); res;) { logger->trace("doing work"); { std::lock_guard<std::mutex> lock(access); std::invoke(std::move(task), *this); } auto [tmp_res, tmp_task] = work_queue.pop_front(); res = tmp_res; task = std::move(tmp_task); } } void EntitySystem::send_map(const RoseCommon::CRosePacket& packet) const { registry.view<const Component::Client>().each([&packet](auto entity, const auto &client_ptr) { (void)entity; if (auto client = client_ptr.client.lock()) { client->send(packet); } }); } void EntitySystem::send_nearby(RoseCommon::Entity entity, const RoseCommon::CRosePacket& packet) const { registry.view<const Component::Client>().each([entity, this, &packet](auto other, const auto &client_ptr) { if (!nearby.is_nearby(*this, entity, other)) return; if (auto client = client_ptr.client.lock()) { client->send(packet); } }); } void EntitySystem::send_nearby_except_me(RoseCommon::Entity entity, const RoseCommon::CRosePacket& packet) const { registry.view<const Component::Client>().each([entity, this, &packet](auto other, const auto &client_ptr) { if (other != entity) { if (!nearby.is_nearby(*this, entity, other)) return; if (auto client = client_ptr.client.lock()) { client->send(packet); } } }); } void EntitySystem::send_to(RoseCommon::Entity entity, const RoseCommon::CRosePacket& packet) const { if (const auto client_ptr = registry.try_get<const Component::Client>(entity)) { if (auto client = client_ptr->client.lock()) { client->send(packet); } } } void EntitySystem::delete_entity(RoseCommon::Entity entity) { add_task([entity](EntitySystem& entitySystem) { entitySystem.registry.destroy(entity); }); } void EntitySystem::update_position(RoseCommon::Entity entity, float x, float y) { if (entity == entt::null) return; auto* pos = try_get_component<Component::Position>(entity); float old_x = 0, old_y = 0; if (!pos) { pos = &add_component<Component::Position>(entity); pos->z = 0; } else { old_x = pos->x; old_y = pos->y; } pos->x = x; pos->y = y; nearby.update_position(entity, old_x, old_y, x, y); } std::vector<RoseCommon::Entity> EntitySystem::get_nearby(RoseCommon::Entity entity) const { return nearby.get_nearby(*this, entity); } RoseCommon::Entity EntitySystem::load_character(uint32_t charId, bool platinium, uint32_t sessionId, std::weak_ptr<CMapClient> client) { using namespace Component; auto conn = Core::connectionPool.getConnection(Core::osirose); Core::CharacterTable characters{}; Core::InventoryTable inventoryTable{}; Core::SkillTable skillsTable{}; auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters)) .from(characters).where(characters.id == charId)); if (static_cast<long>(charRes.front().count) != 1L) { return entt::null; } const auto& charRow = charRes.front(); entt::prototype prototype(registry); auto& basicInfo = prototype.set<BasicInfo>(); basicInfo.name = charRow.name; basicInfo.id = idManager.get_free_id(); basicInfo.tag = sessionId; basicInfo.teamId = basicInfo.id; basicInfo.job = charRow.job; basicInfo.statPoints = charRow.statPoints; basicInfo.skillPoints = charRow.skillPoints; basicInfo.pkFlag = charRow.pkFlag; basicInfo.stone = charRow.stone; basicInfo.charId = charId; auto& component_client = prototype.set<Client>(); component_client.client = client; auto& computedValues = prototype.set<ComputedValues>(); computedValues.command = RoseCommon::Command::STOP; computedValues.moveMode = RoseCommon::MoveMode::WALK; computedValues.runSpeed = 0; computedValues.atkSpeed = 0; computedValues.weightRate = 0; auto& faction = prototype.set<Faction>(); faction.id = charRow.factionid; faction.rank = charRow.factionRank; faction.fame = charRow.fame; faction.factionFame[0] = charRow.factionFame1; faction.factionFame[1] = charRow.factionFame2; faction.points[0] = charRow.factionPoints1; faction.points[1] = charRow.factionPoints2; faction.points[2] = charRow.factionPoints3; auto& characterGraphics = prototype.set<CharacterGraphics>(); characterGraphics.face = charRow.face; characterGraphics.hair = charRow.hair; characterGraphics.race = charRow.race; auto& guild = prototype.set<Guild>(); guild.id = charRow.clanid; guild.contribution = charRow.clanContribution; guild.rank = charRow.clanRank; prototype.set<Hotbar>(); auto invRes = conn(sqlpp::select(sqlpp::all_of(inventoryTable)).from(inventoryTable) .where(inventoryTable.charId == charId and inventoryTable.storage_type == "inventory" or inventoryTable.storage_type == "wishlist")); auto& wishlist = prototype.set<Wishlist>(); auto& inventory = prototype.set<Inventory>(); for (const auto& row : invRes) { const bool is_inventory = row.storage_type == "inventory"; const auto maxItems = is_inventory ? RoseCommon::MAX_ITEMS : RoseCommon::MAX_WISHLIST; if (row.slot >= maxItems) { continue; } Item item; item.isCreated = false; item.life = 1000; item.hasSocket = row.socket; item.isAppraised = true; item.refine = row.refine; item.count = row.amount; item.gemOpt = row.gemOpt; item.price = row.price; auto to_emplace = load_item(row.itemtype, row.itemid, item); if (is_inventory) { inventory.items[row.slot] = to_emplace; } else { wishlist.items[row.slot] = to_emplace; } } auto& level = prototype.set<Level>(); level.xp = charRow.exp; level.level = charRow.level; level.penaltyXp = charRow.penaltyExp; auto& life = prototype.set<Life>(); life.hp = charRow.maxHp / 3; // you only get 30% of your health when login in life.maxHp = charRow.maxHp; auto& magic = prototype.set<Magic>(); magic.mp = charRow.maxMp / 3; magic.maxMp = charRow.maxMp; auto& pos = prototype.set<Position>(); pos.x = charRow.x; pos.y = charRow.y; pos.z = 0; pos.spawn = charRow.reviveMap; pos.map = charRow.map; auto skillRes = conn(sqlpp::select(skillsTable.id, skillsTable.level).from(skillsTable).where(skillsTable.charId == charId)); auto& skills = prototype.set<Skills>(); for (const auto& [i, row] : Core::enumerate(skillRes)) { skills.skills[i].set_id(row.id); skills.skills[i].set_level(row.level); } auto& stamina = prototype.set<Stamina>(); stamina.stamina = charRow.stamina; auto& stats = prototype.set<Stats>(); stats.str = charRow.str; stats.dex = charRow.dex; stats.int_ = charRow.int_; stats.con = charRow.con; stats.charm = charRow.charm; stats.sense = charRow.sense; stats.bodySize = 100; stats.headSize = 100; prototype.set<StatusEffects>(); std::lock_guard<std::mutex> lock(access); return prototype(); } void EntitySystem::save_character(RoseCommon::Entity character) { add_task([character](EntitySystem& self) { auto conn = Core::connectionPool.getConnection(Core::osirose); Core::CharacterTable characters{}; using sqlpp::parameter; using namespace Component; const auto& basicInfo = self.get_component<BasicInfo>(character); const auto& faction = self.get_component<Faction>(character); const auto& characterGraphics = self.get_component<CharacterGraphics>(character); const auto& guild = self.get_component<Guild>(character); // TODO: save hotbar // TODO: save inventory const auto& level = self.get_component<Level>(character); const auto& life = self.get_component<Life>(character); const auto& magic = self.get_component<Magic>(character); const auto& pos = self.get_component<Position>(character); // TODO: save skills const auto& stamina = self.get_component<Stamina>(character); const auto& stats = self.get_component<Stats>(character); // TODO: save wishlist conn(sqlpp::update(characters).where(characters.id == basicInfo.charId).set( characters.name = basicInfo.name, characters.job = basicInfo.job, characters.statPoints = basicInfo.statPoints, characters.skillPoints = basicInfo.skillPoints, characters.pkFlag = basicInfo.pkFlag, characters.stone = basicInfo.stone, characters.factionid = faction.id, characters.factionRank = faction.rank, characters.fame = faction.fame, characters.factionFame1 = faction.factionFame[0], characters.factionFame2 = faction.factionFame[1], characters.factionPoints1 = faction.points[0], characters.factionPoints2 = faction.points[1], characters.factionPoints3 = faction.points[2], characters.face = characterGraphics.face, characters.hair = characterGraphics.hair, characters.race = characterGraphics.race, characters.clanid = guild.id, characters.clanContribution = guild.contribution, characters.clanRank = guild.rank, characters.exp = level.xp, characters.level = level.level, characters.penaltyExp = level.penaltyXp, characters.maxHp = life.maxHp, characters.maxMp = magic.maxMp, characters.x = pos.x, characters.y = pos.y, characters.reviveMap = pos.spawn, characters.map = pos.map, characters.stamina = stamina.stamina, characters.str = stats.str, characters.dex = stats.dex, characters.int_ = stats.int_, characters.con = stats.con, characters.charm = stats.charm, characters.sense = stats.sense )); }); } RoseCommon::Entity EntitySystem::create_item(uint8_t type, uint16_t id) { using namespace Component; entt::prototype prototype(registry); const auto &itemDb = RoseCommon::ItemDatabase::getInstance(); if (!itemDb.itemExists(type, id)) { return entt::null; } const auto& def = itemDb.getItemDef(type, id); auto& item = prototype.set<Item>(); item.isCreated = false; item.life = 1000; item.durability = 100; item.hasSocket = false; item.isAppraised = false; item.refine = 0; item.count = 0; item.gemOpt = 0; item.price = 0; prototype.set<RoseCommon::ItemDef>(def); std::lock_guard<std::mutex> lock(access); return prototype(); } RoseCommon::Entity EntitySystem::load_item(uint8_t type, uint16_t id, Component::Item item) { auto entity = create_item(type, id); if (entity == entt::null) { return entt::null; } registry.replace<Component::Item>(entity, item); return entity; } void EntitySystem::save_item(RoseCommon::Entity item, RoseCommon::Entity owner) const { // TODO: should be done as a task??? }
Update entity_system.cpp
Update entity_system.cpp
C++
apache-2.0
dev-osrose/osIROSE-new,RavenX8/osIROSE-new,dev-osrose/osIROSE-new,RavenX8/osIROSE-new,RavenX8/osIROSE-new,dev-osrose/osIROSE-new
443475f0debe3deeb22fbbf0138448f333113bd1
Parallel_RVD/Polygon.cpp
Parallel_RVD/Polygon.cpp
#include "Polygon.h" namespace P_RVD { void Polygon::initialize_from_mesh_facet( const Mesh* _mesh, t_index _facetIdx ) { clear(); Facet temp_facet = _mesh->meshFacets.getFacet(_facetIdx); Vertex* v1 = add_vertex( Vertex( _mesh->meshVertices.getPoint(temp_facet.m_v1), 1.0, _facetIdx ) ); Vertex* v2 = add_vertex( Vertex( _mesh->meshVertices.getPoint(temp_facet.m_v2), 1.0, _facetIdx ) ); Vertex* v3 = add_vertex( Vertex( _mesh->meshVertices.getPoint(temp_facet.m_v3), 1.0, _facetIdx ) ); } void Polygon::clip_by_plane(Polygon& _target, Points _points, t_index _i, t_index _j) { _target.clear(); if (getVertex_nb() == 0) { return; } //get the geometic position of the i and j. Vector3d position_i = _points.getPoint(_i); Vector3d position_j = _points.getPoint(_j); // Compute d = n . (2m), where n is the // normal vector of the bisector [i, j] // and m the middle point of the bisector. double d; d = (position_i + position_j).cross(position_i - position_j); //The predecessor of the first vertex is the last vertex t_index prev_index_vertex = getVertex_nb() - 1; const Vertex* prev_vertex = &(getVertex(prev_index_vertex)); const Vector3d prev_vertex_position = prev_vertex->getPosition(); //then we compute prev_vertex_position "cross" n //prev_l = prev_vertex_position . n double prev_l = prev_vertex_position.cross(position_i - position_j); P_RVD::Sign prev_status = P_RVD::geo_sgn(2.0 * prev_l - d); //traverse the Vertex in this Polygon for (t_index k = 0; k < getVertex_nb(); ++k) { const Vertex* vertex = &(getVertex(k)); const Vector3d vertex_position = vertex->getPosition(); double l = vertex_position.cross(position_i - position_j); P_RVD::Sign status = P_RVD::geo_sgn(2.0 * l - d); } return; } }
#include "Polygon.h" namespace P_RVD { void Polygon::initialize_from_mesh_facet( const Mesh* _mesh, t_index _facetIdx ) { clear(); Facet temp_facet = _mesh->meshFacets.getFacet(_facetIdx); Vertex* v1 = add_vertex( Vertex( _mesh->meshVertices.getPoint(temp_facet.m_v1), 1.0, _facetIdx ) ); Vertex* v2 = add_vertex( Vertex( _mesh->meshVertices.getPoint(temp_facet.m_v2), 1.0, _facetIdx ) ); Vertex* v3 = add_vertex( Vertex( _mesh->meshVertices.getPoint(temp_facet.m_v3), 1.0, _facetIdx ) ); } void Polygon::clip_by_plane(Polygon& _target, Points _points, t_index _i, t_index _j) { _target.clear(); if (getVertex_nb() == 0) { return; } //get the geometic position of the i and j. Vector3d position_i = _points.getPoint(_i); Vector3d position_j = _points.getPoint(_j); // Compute d = n . (2m), where n is the // normal vector of the bisector [i, j] // and m the middle point of the bisector. double d; d = (position_i + position_j).cross(position_i - position_j); //The predecessor of the first vertex is the last vertex t_index prev_index_vertex = getVertex_nb() - 1; const Vertex* prev_vertex = &(getVertex(prev_index_vertex)); Vector3d prev_vertex_position = prev_vertex->getPosition(); //then we compute prev_vertex_position "cross" n //prev_l = prev_vertex_position . n double prev_l = prev_vertex_position.cross(position_i - position_j); P_RVD::Sign prev_status = P_RVD::geo_sgn(2.0 * prev_l - d); //traverse the Vertex in this Polygon for (t_index k = 0; k < getVertex_nb(); ++k) { const Vertex* vertex = &(getVertex(k)); Vector3d vertex_position = vertex->getPosition(); double l = vertex_position.cross(position_i - position_j); //We compute: // side1(pi, pj, q) = sign(2*q.n - n.m) = sign(2*l - d) P_RVD::Sign status = P_RVD::geo_sgn(2.0 * l - d); // If status of edge extremities differ, // then there is an intersection. if (status != prev_status && (prev_status) != 0) { // create the intersection and update the Polygon Vertex I; Vector3d temp_position; //compute the position and weight double denom = 2.0 * (prev_l - l); double lambda1, lambda2; // Shit happens ! [Forrest Gump] if (::fabs(denom) < 1e-20) { lambda1 = 0.5; lambda2 = 0.5; } else { lambda1 = (d - 2.0 * l) / denom; // Note: lambda2 is also given // by (2.0*l2-d)/denom // (but 1.0 - lambda1 is a bit // faster to compute...) lambda2 = 1.0 - lambda1; } temp_position.x = lambda1 * prev_vertex_position.x + lambda2 * vertex_position.x; temp_position.y = lambda1 * prev_vertex_position.y + lambda2 * vertex_position.y; temp_position.z = lambda1 * prev_vertex_position.z + lambda2 * vertex_position.z; //Set the position of Vertex I.setPosition(temp_position); //Set the weight of Veretex I.setWeight(lambda1 * prev_vertex->getWeight() + lambda2 * vertex->getWeight()); //???? ûŪ if (status > 0) { I.copy_edge_from(*prev_vertex); I.setSeed(signed_t_index(_j)); } else { I.setEdgeType(Intersection); I.setSeed(vertex->getSeed()); } _target.add_vertex(I); } if (status > 0) { _target.add_vertex(*vertex); } prev_vertex = vertex; prev_vertex_position = vertex_position; prev_status = status; prev_l = l; prev_index_vertex = k; } return; } }
update clip_by_plane func
update clip_by_plane func
C++
mit
stormHan/Parallel_RVD,stormHan/Parallel_RVD
98dff45f2020c255061e0dab8971e4c8889a0063
src/tadiga_IGES_geometry.cc
src/tadiga_IGES_geometry.cc
// Copyright 2016-2017 John T. Foster, Katy L. Hanson // 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 "IGESControl_Reader.hxx" #include "TColStd_HSequenceOfTransient.hxx" #include "TopoDS_Shape.hxx" #include "TopoDS_Vertex.hxx" #include "TopoDS_Edge.hxx" #include "Teuchos_RCP.hpp" #include "tadiga_IGES_geometry.h" tadiga::IgesGeometry::IgesGeometry( const Teuchos::RCP<const Teuchos::Comm<int>>& kComm, const Teuchos::RCP<Teuchos::ParameterList>& kGeometryParameters) : kComm_(kComm) { const auto kFileName = kGeometryParameters->get<std::string>("File Name"); // Open IGES Reader from OpenCASCADE const auto kIgesReader = Teuchos::rcp(new IGESControl_Reader); const auto status = kIgesReader->ReadFile(kFileName.c_str()); // TODO([email protected]): Check the status of the file Handle(TColStd_HSequenceOfTransient) myFacesList = kIgesReader->GiveList("iges-faces"); Handle(TColStd_HSequenceOfTransient) myEdgesList = kIgesReader->GiveList("iges-type(110)"); // selects all IGES faces in the file and puts them into a list called // //MyList, const auto kIgesFaces = myFacesList->Length(); const auto kTransFaces = kIgesReader->TransferList(myFacesList); const auto kIgesEdges = myEdgesList->Length(); const auto kTransEdges = kIgesReader->TransferList(myEdgesList); // translates MyList, std::cout << "IGES Faces: " << kIgesFaces << " Transferred:" << kTransFaces << std::endl; std::cout << "IGES Edges: " << kIgesEdges << " Transferred:" << kTransEdges << std::endl; TopoDS_Shape sh = kIgesReader->OneShape(); };
// Copyright 2016-2017 John T. Foster, Katy L. Hanson // 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 "IGESControl_Reader.hxx" #include "TColStd_HSequenceOfTransient.hxx" #include "TopoDS_Shape.hxx" #include "TopoDS_Vertex.hxx" #include "TopoDS_Edge.hxx" #include "Teuchos_RCP.hpp" #include "tadiga_IGES_geometry.h" tadiga::IgesGeometry::IgesGeometry( const Teuchos::RCP<const Teuchos::Comm<int>>& kComm, const Teuchos::RCP<Teuchos::ParameterList>& kGeometryParameters) : kComm_(kComm) { const auto kFileName = kGeometryParameters->get<std::string>("File Name"); // Open IGES Reader from OpenCASCADE const auto kIgesReader = Teuchos::rcp(new IGESControl_Reader); const auto status = kIgesReader->ReadFile(kFileName.c_str()); // TODO([email protected]): Check the status of the file Handle(TColStd_HSequenceOfTransient) myFacesList = kIgesReader->GiveList("iges-faces"); Handle(TColStd_HSequenceOfTransient) myEdgesList = kIgesReader->GiveList("iges-type(110)"); Handle(TColStd_HSequenceOfTransient) myTabCylinderList = kIgesReader->GiveList("iges-type(122)"); Handle(TColStd_HSequenceOfTransient) myCompCurveList = kIgesReader->GiveList("iges-type(102)"); // selects all IGES faces in the file and puts them into a list called // //MyList, const auto kIgesFaces = myFacesList->Length(); const auto kTransFaces = kIgesReader->TransferList(myFacesList); const auto kIgesEdges = myEdgesList->Length(); const auto kTransEdges = kIgesReader->TransferList(myEdgesList); const auto kIgesTabCylinder = myTabCylinderList->Length(); const auto kTransTabCylinder = kIgesReader->TransferList(myTabCylinderList); // translates MyList, const auto kIgesCompCurve = myCompCurveList->Length(); const auto kTransCompCurve = kIgesReader->TransferList(myCompCurveList); std::cout << "IGES Faces: " << kIgesFaces << " Transferred:" << kTransFaces << std::endl; std::cout << "IGES Edges: " << kIgesEdges << " Transferred:" << kTransEdges << std::endl; std::cout << "IGES Tabulated Cylinder: " << kIgesTabCylinder << " Transferred:" << kTransTabCylinder << std::endl; std::cout << "IGES Composite Curve: " << kIgesCompCurve << " Transferred:" << kTransCompCurve << std::endl; TopoDS_Shape sh = kIgesReader->OneShape(); };
Add reader for Composite Curve and Tabulated Cylinder
Add reader for Composite Curve and Tabulated Cylinder
C++
apache-2.0
johntfoster/TaDIgA,johntfoster/TaDIgA
737cdf0b1668466e73dae60b36589b77b4f69bf6
groups/bsl/bslmf/bslmf_tag.t.cpp
groups/bsl/bslmf/bslmf_tag.t.cpp
// bslmf_tag.t.cpp -*-C++-*- #include <bslmf_tag.h> #include <stdlib.h> // 'atoi' #include <string.h> // 'strcmp' #include <iostream> using namespace BloombergLP; using namespace std; //============================================================================= // TEST PLAN //----------------------------------------------------------------------------- // Overview // -------- //----------------------------------------------------------------------------- // [ 1] bslmf::Tag //----------------------------------------------------------------------------- // [ 2] USAGE EXAMPLE //============================================================================= // STANDARD BDE ASSERT TEST MACRO //----------------------------------------------------------------------------- static int testStatus = 0; static void aSsErT(int c, const char *s, int i) { if (c) { cout << "Error " << __FILE__ << "(" << i << "): " << s << " (failed)" << endl; if (testStatus >= 0 && testStatus <= 100) ++testStatus; } } #define ASSERT(X) { aSsErT(!(X), #X, __LINE__); } //----------------------------------------------------------------------------- #define LOOP_ASSERT(I,X) { \ if (!(X)) { cout << #I << ": " << I << "\n"; aSsErT(1, #X, __LINE__);}} #define LOOP2_ASSERT(I,J,X) { \ if (!(X)) { cout << #I << ": " << I << "\t" << #J << ": " \ << J << "\n"; aSsErT(1, #X, __LINE__); } } //============================================================================= #define P(X) cout << #X " = " << (X) << endl; // Print identifier and value. #define Q(X) cout << "<| " #X " |>" << endl; // Quote identifier literally. #define P_(X) cout << #X " = " << (X) << ", " << flush; // P(X) without '\n' #define L_ __LINE__ // current Line number #define T_() cout << '\t' << flush; // Print tab w/o linefeed. //============================================================================= // GLOBAL TYPEDEFS/CONSTANTS FOR TESTING //----------------------------------------------------------------------------- // verify that the tag is evaluated at compile-time template <unsigned N> bslmf::Tag<N> tag() { ASSERT(0); return bslmf::Tag<N>(); } enum { C0 = 1 + BSLMF_TAG_TO_INT(tag<0>()), // 1 C1 = 1 + BSLMF_TAG_TO_INT(tag<1>()), // 2 C2 = 1 + BSLMF_TAG_TO_INT(tag<2>()) // 3 }; const unsigned U5 = -5; const unsigned C5 = BSLMF_TAG_TO_UINT(tag<static_cast<unsigned>(-5)>()); // (unsigned)-5 const int CM5 = BSLMF_TAG_TO_INT(tag<static_cast<unsigned>(-5)>()); // -5 // ============================================================================ // USAGE EXAMPLE // ---------------------------------------------------------------------------- ///Usage ///----- // The most common use of this structure is to perform static function // dispatching based on a compile-time calculation. Often the calculation is // nothing more than a simple predicate, allowing us to select one of two // functions. The following function, 'doSomething', uses a fast // implementation (e.g., 'memcpy') if the parameterized type allows for such // operations; otherwise it will use a more generic and slower implementation // (e.g., copy constructor). //.. template <class T> void doSomethingImp(T * /* t */, bslmf::Tag<0> *) { // slow but generic implementation } template <class T> void doSomethingImp(T * /* t */, bslmf::Tag<1> *) { // fast implementation (appropriate for bitwise-movable types) } template <class T, bool IsFast> void doSomething(T *t) { doSomethingImp(t, (bslmf::Tag<IsFast> *)0); } //.. // For some parameter types, the fast version of 'doSomethingImp' is not legal. // The power of this approach is that the compiler will compile just the // implementation selected by the tag argument. //.. void f() { int i; doSomething<int, true>(&i); // fast version selected for 'int' double m; doSomething<double, false>(&m); // slow version selected for 'double' } //.. // Note that an alternative design would be to use template partial // specialization instead of standard function overloading to avoid the // cost of passing a 'bslmf::Tag<N>' pointer. //============================================================================= // MAIN PROGRAM //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; int verbose = argc > 2; // int veryVerbose = argc > 3; cout << "TEST " << __FILE__ << " CASE " << test << endl; switch (test) { case 0: // Zero is always the leading case. case 2: { // -------------------------------------------------------------------- // TESTING USAGE EXAMPLE // The usage example provided in the component header file must // compile, link, and run on all platforms as shown. // // Plan: // Incorporate usage example from header into driver, remove leading // comment characters, and replace 'assert' with 'ASSERT'. // // Testing: // USAGE EXAMPLE // -------------------------------------------------------------------- if (verbose) cout << endl << "USAGE EXAMPLE" << endl << "=============" << endl; f(); // call function defined in Usage // // The value of the integral parameter supplied to an instantiation of // 'bslmf::Tag<N>' is "recoverable" by using the 'BSLMF_TAG_TO_INT' macro. // For example: //.. bslmf::Tag<7> tag; ASSERT( 7 == BSLMF_TAG_TO_INT(tag)); ASSERT(53 == BSLMF_TAG_TO_INT(bslmf::Tag<50 + 3>())); //.. // The 'BSLMF_TAG_TO_BOOL' macro can be used to determine if the parameter is // non-zero: //.. ASSERT( 1 == BSLMF_TAG_TO_BOOL(tag)); ASSERT( 0 == BSLMF_TAG_TO_BOOL(bslmf::Tag<0>())); //.. } break; case 1: { // -------------------------------------------------------------------- // Test Plan: // Instantiate 'bslmf::Tag' with various constant integral // values and verify that their 'VALUE' member is initialized // properly. // -------------------------------------------------------------------- if (verbose) cout << endl << "bslmf::Tag" << endl << "==========" << endl; ASSERT(1 == C0); ASSERT(2 == C1); ASSERT(3 == C2); ASSERT((unsigned)-5 == C5); ASSERT(-5 == (int)CM5); } break; default: { cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl; testStatus = -1; } } if (testStatus > 0) { cerr << "Error, non-zero test status = " << testStatus << "." << endl; } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2013 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ----------------------------------
// bslmf_tag.t.cpp -*-C++-*- #include <bslmf_tag.h> #include <stdlib.h> // 'atoi' #include <string.h> // 'strcmp' #include <iostream> using namespace BloombergLP; using namespace std; //============================================================================= // TEST PLAN //----------------------------------------------------------------------------- // Overview // -------- //----------------------------------------------------------------------------- // [ 1] bslmf::Tag //----------------------------------------------------------------------------- // [ 2] USAGE EXAMPLE //============================================================================= // STANDARD BDE ASSERT TEST MACRO //----------------------------------------------------------------------------- static int testStatus = 0; static void aSsErT(int c, const char *s, int i) { if (c) { cout << "Error " << __FILE__ << "(" << i << "): " << s << " (failed)" << endl; if (testStatus >= 0 && testStatus <= 100) ++testStatus; } } #define ASSERT(X) { aSsErT(!(X), #X, __LINE__); } //----------------------------------------------------------------------------- #define LOOP_ASSERT(I,X) { \ if (!(X)) { cout << #I << ": " << I << "\n"; aSsErT(1, #X, __LINE__);}} #define LOOP2_ASSERT(I,J,X) { \ if (!(X)) { cout << #I << ": " << I << "\t" << #J << ": " \ << J << "\n"; aSsErT(1, #X, __LINE__); } } //============================================================================= #define P(X) cout << #X " = " << (X) << endl; // Print identifier and value. #define Q(X) cout << "<| " #X " |>" << endl; // Quote identifier literally. #define P_(X) cout << #X " = " << (X) << ", " << flush; // P(X) without '\n' #define L_ __LINE__ // current Line number #define T_() cout << '\t' << flush; // Print tab w/o linefeed. //============================================================================= // GLOBAL TYPEDEFS/CONSTANTS FOR TESTING //----------------------------------------------------------------------------- // verify that the tag is evaluated at compile-time template <int N> bslmf::Tag<N> tag() { ASSERT(0); return bslmf::Tag<N>(); } enum { C0 = 1 + BSLMF_TAG_TO_INT(tag<0>()), // 1 C1 = 1 + BSLMF_TAG_TO_INT(tag<1>()), // 2 C2 = 1 + BSLMF_TAG_TO_INT(tag<2>()) // 3 }; const unsigned U5 = -5; const unsigned C5 = BSLMF_TAG_TO_UINT(tag<-5>()); // (unsigned)-5 const int CM5 = BSLMF_TAG_TO_INT(tag<-5>()); // -5 // ============================================================================ // USAGE EXAMPLE // ---------------------------------------------------------------------------- ///Usage ///----- // The most common use of this structure is to perform static function // dispatching based on a compile-time calculation. Often the calculation is // nothing more than a simple predicate, allowing us to select one of two // functions. The following function, 'doSomething', uses a fast // implementation (e.g., 'memcpy') if the parameterized type allows for such // operations; otherwise it will use a more generic and slower implementation // (e.g., copy constructor). //.. template <class T> void doSomethingImp(T * /* t */, bslmf::Tag<0> *) { // slow but generic implementation } template <class T> void doSomethingImp(T * /* t */, bslmf::Tag<1> *) { // fast implementation (appropriate for bitwise-movable types) } template <class T, bool IsFast> void doSomething(T *t) { doSomethingImp(t, (bslmf::Tag<IsFast> *)0); } //.. // For some parameter types, the fast version of 'doSomethingImp' is not legal. // The power of this approach is that the compiler will compile just the // implementation selected by the tag argument. //.. void f() { int i; doSomething<int, true>(&i); // fast version selected for 'int' double m; doSomething<double, false>(&m); // slow version selected for 'double' } //.. // Note that an alternative design would be to use template partial // specialization instead of standard function overloading to avoid the // cost of passing a 'bslmf::Tag<N>' pointer. //============================================================================= // MAIN PROGRAM //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; int verbose = argc > 2; // int veryVerbose = argc > 3; cout << "TEST " << __FILE__ << " CASE " << test << endl; switch (test) { case 0: // Zero is always the leading case. case 2: { // -------------------------------------------------------------------- // TESTING USAGE EXAMPLE // The usage example provided in the component header file must // compile, link, and run on all platforms as shown. // // Plan: // Incorporate usage example from header into driver, remove leading // comment characters, and replace 'assert' with 'ASSERT'. // // Testing: // USAGE EXAMPLE // -------------------------------------------------------------------- if (verbose) cout << endl << "USAGE EXAMPLE" << endl << "=============" << endl; f(); // call function defined in Usage // // The value of the integral parameter supplied to an instantiation of // 'bslmf::Tag<N>' is "recoverable" by using the 'BSLMF_TAG_TO_INT' macro. // For example: //.. bslmf::Tag<7> tag; ASSERT( 7 == BSLMF_TAG_TO_INT(tag)); ASSERT(53 == BSLMF_TAG_TO_INT(bslmf::Tag<50 + 3>())); //.. // The 'BSLMF_TAG_TO_BOOL' macro can be used to determine if the parameter is // non-zero: //.. ASSERT( 1 == BSLMF_TAG_TO_BOOL(tag)); ASSERT( 0 == BSLMF_TAG_TO_BOOL(bslmf::Tag<0>())); //.. } break; case 1: { // -------------------------------------------------------------------- // Test Plan: // Instantiate 'bslmf::Tag' with various constant integral // values and verify that their 'VALUE' member is initialized // properly. // -------------------------------------------------------------------- if (verbose) cout << endl << "bslmf::Tag" << endl << "==========" << endl; ASSERT(1 == C0); ASSERT(2 == C1); ASSERT(3 == C2); ASSERT((unsigned)-5 == C5); ASSERT(-5 == (int)CM5); } break; default: { cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl; testStatus = -1; } } if (testStatus > 0) { cerr << "Error, non-zero test status = " << testStatus << "." << endl; } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2013 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ----------------------------------
revert changes to tag
revert changes to tag
C++
apache-2.0
idispatch/bde,saxena84/bde,frutiger/bde,dbremner/bde,osubboo/bde,dharesign/bde,saxena84/bde,mversche/bde,dharesign/bde,bloomberg/bde,dbremner/bde,idispatch/bde,apaprocki/bde,bowlofstew/bde,che2/bde,bloomberg/bde,frutiger/bde,bowlofstew/bde,osubboo/bde,dharesign/bde,bloomberg/bde,bloomberg/bde,apaprocki/bde,che2/bde,mversche/bde,apaprocki/bde,dbremner/bde,dbremner/bde,frutiger/bde,bowlofstew/bde,bloomberg/bde,frutiger/bde,osubboo/bde,minhlongdo/bde,apaprocki/bde,saxena84/bde,saxena84/bde,che2/bde,minhlongdo/bde,che2/bde,minhlongdo/bde,idispatch/bde,bowlofstew/bde,osubboo/bde,mversche/bde,mversche/bde,apaprocki/bde,minhlongdo/bde,idispatch/bde,dharesign/bde
58497533448ce9a2ed5f6639144cdcb38891adf0
src/condor_sysapi/net_dev_info.cpp
src/condor_sysapi/net_dev_info.cpp
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_debug.h" #include "sysapi.h" #include "sysapi_externs.h" static bool net_devices_cached = false; static std::vector<NetworkDeviceInfo> net_devices_cache; #if WIN32 #include <Ws2ipdef.h> bool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices) { int i,num_interfaces=0,max_interfaces=20; LPINTERFACE_INFO interfaces=NULL; DWORD bytes_out=0; SOCKET sock; sock = socket(AF_INET, SOCK_DGRAM, 0); if( sock == INVALID_SOCKET ) { dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: socket() failed: (errno %d)\n", WSAGetLastError()); return false; } while( true ) { interfaces = new INTERFACE_INFO[max_interfaces]; int rc = WSAIoctl( sock, SIO_GET_INTERFACE_LIST, NULL, 0, interfaces, sizeof(INTERFACE_INFO)*max_interfaces, &bytes_out, NULL, NULL); if( rc == 0 ) { // success num_interfaces = bytes_out/sizeof(INTERFACE_INFO); break; } delete [] interfaces; int error = WSAGetLastError(); if( error == WSAEFAULT ) { // not enough space in buffer max_interfaces *= 2; continue; } dprintf(D_ALWAYS,"SIO_GET_INTERFACE_LIST failed: %d\n",error); closesocket(sock); return false; } for(i=0;i<num_interfaces;i++) { char const *ip = NULL; if( interfaces[i].iiAddress.Address.sa_family == AF_INET ) { ip = inet_ntoa(((struct sockaddr_in *)&interfaces[i].iiAddress)->sin_addr); } if( ip ) { NetworkDeviceInfo inf("",ip); devices.push_back(inf); } } delete [] interfaces; closesocket(sock); return true; } #elif HAVE_GETIFADDRS #include <sys/types.h> #include <sys/socket.h> #include <ifaddrs.h> bool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices) { struct ifaddrs *ifap_list=NULL; if( getifaddrs(&ifap_list) == -1 ) { dprintf(D_ALWAYS,"getifaddrs failed: errno=%d: %s\n",errno,strerror(errno)); return false; } struct ifaddrs *ifap=ifap_list; for(ifap=ifap_list; ifap; ifap=ifap->ifa_next) { char const *name = ifap->ifa_name; char const *ip = NULL; if( ifap->ifa_addr->sa_family == AF_INET ) { ip = inet_ntoa(((struct sockaddr_in *)ifap->ifa_addr)->sin_addr); } if( ip ) { NetworkDeviceInfo inf(name,ip); devices.push_back(inf); } } freeifaddrs(ifap_list); return true; } #elif defined(SIOCGIFCONF) #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <net/if.h> bool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices) { int sock = socket(AF_INET, SOCK_DGRAM, 0); if( sock == -1 ) { dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: socket() failed: (errno %d) %s\n", errno,strerror(errno)); return false; } struct ifconf ifc; memset(&ifc, 0, sizeof(ifc)); if( ioctl(sock, SIOCGIFCONF, &ifc) < 0 ) { dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: ioctlsocket() failed: (errno %d) %s\n", errno,strerror(errno)); return false; } // add some extra padding in buffer in case devices are added between above call and next ioctl ifc.ifc_req = (struct ifreq *)malloc(ifc.ifc_len + 10*sizeof(struct ifreq)); if( ifc.ifc_req == NULL ) { dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: out of memory\n"); return false; } if( ioctl(sock, SIOCGIFCONF, &ifc) < 0 ) { dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: ioctlsocket() failed after allocating buffer: (errno %d) %s\n", errno,strerror(errno)); free( ifc.ifc_req ); return false; } int i,num_interfaces = ifc.ifc_len/sizeof(struct ifreq); for(i=0; i<num_interfaces; i++) { struct ifreq *ifr = &ifc.ifc_req[i]; char const *name = ifr->ifr_name; char const *ip = NULL; if( ifr->ifr_addr.sa_family == AF_INET ) { ip = inet_ntoa(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr); } if( ip ) { NetworkDeviceInfo inf(name,ip); devices.push_back(inf); } } free( ifc.ifc_req ); return true; } #else #error sysapi_get_network_device_info() must be implemented for this platform #endif bool sysapi_get_network_device_info(std::vector<NetworkDeviceInfo> &devices) { if( net_devices_cached ) { devices = net_devices_cache; return true; } bool rc = sysapi_get_network_device_info_raw(devices); if( rc ) { net_devices_cached = true; net_devices_cache = devices; } return rc; } void sysapi_clear_network_device_info_cache() { net_devices_cached = false; }
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_debug.h" #include "sysapi.h" #include "sysapi_externs.h" static bool net_devices_cached = false; static std::vector<NetworkDeviceInfo> net_devices_cache; #if WIN32 #include <Ws2ipdef.h> bool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices) { int i,num_interfaces=0,max_interfaces=20; LPINTERFACE_INFO interfaces=NULL; DWORD bytes_out=0; SOCKET sock; sock = socket(AF_INET, SOCK_DGRAM, 0); if( sock == INVALID_SOCKET ) { dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: socket() failed: (errno %d)\n", WSAGetLastError()); return false; } while( true ) { interfaces = new INTERFACE_INFO[max_interfaces]; int rc = WSAIoctl( sock, SIO_GET_INTERFACE_LIST, NULL, 0, interfaces, sizeof(INTERFACE_INFO)*max_interfaces, &bytes_out, NULL, NULL); if( rc == 0 ) { // success num_interfaces = bytes_out/sizeof(INTERFACE_INFO); break; } delete [] interfaces; int error = WSAGetLastError(); if( error == WSAEFAULT ) { // not enough space in buffer max_interfaces *= 2; continue; } dprintf(D_ALWAYS,"SIO_GET_INTERFACE_LIST failed: %d\n",error); closesocket(sock); return false; } for(i=0;i<num_interfaces;i++) { char const *ip = NULL; if( interfaces[i].iiAddress.Address.sa_family == AF_INET ) { ip = inet_ntoa(((struct sockaddr_in *)&interfaces[i].iiAddress)->sin_addr); } if( ip ) { NetworkDeviceInfo inf("",ip); devices.push_back(inf); } } delete [] interfaces; closesocket(sock); return true; } #elif HAVE_GETIFADDRS #include <sys/types.h> #include <sys/socket.h> #include <ifaddrs.h> bool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices) { struct ifaddrs *ifap_list=NULL; if( getifaddrs(&ifap_list) == -1 ) { dprintf(D_ALWAYS,"getifaddrs failed: errno=%d: %s\n",errno,strerror(errno)); return false; } struct ifaddrs *ifap=ifap_list; for(ifap=ifap_list; ifap; ifap=ifap->ifa_next) { char const *name = ifap->ifa_name; char const *ip = NULL; if( ifap->ifa_addr && ifap->ifa_addr->sa_family == AF_INET ) { ip = inet_ntoa(((struct sockaddr_in *)ifap->ifa_addr)->sin_addr); } if( ip ) { NetworkDeviceInfo inf(name,ip); devices.push_back(inf); } } freeifaddrs(ifap_list); return true; } #elif defined(SIOCGIFCONF) #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <net/if.h> bool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices) { int sock = socket(AF_INET, SOCK_DGRAM, 0); if( sock == -1 ) { dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: socket() failed: (errno %d) %s\n", errno,strerror(errno)); return false; } struct ifconf ifc; memset(&ifc, 0, sizeof(ifc)); if( ioctl(sock, SIOCGIFCONF, &ifc) < 0 ) { dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: ioctlsocket() failed: (errno %d) %s\n", errno,strerror(errno)); return false; } // add some extra padding in buffer in case devices are added between above call and next ioctl ifc.ifc_req = (struct ifreq *)malloc(ifc.ifc_len + 10*sizeof(struct ifreq)); if( ifc.ifc_req == NULL ) { dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: out of memory\n"); return false; } if( ioctl(sock, SIOCGIFCONF, &ifc) < 0 ) { dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: ioctlsocket() failed after allocating buffer: (errno %d) %s\n", errno,strerror(errno)); free( ifc.ifc_req ); return false; } int i,num_interfaces = ifc.ifc_len/sizeof(struct ifreq); for(i=0; i<num_interfaces; i++) { struct ifreq *ifr = &ifc.ifc_req[i]; char const *name = ifr->ifr_name; char const *ip = NULL; if( ifr->ifr_addr.sa_family == AF_INET ) { ip = inet_ntoa(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr); } if( ip ) { NetworkDeviceInfo inf(name,ip); devices.push_back(inf); } } free( ifc.ifc_req ); return true; } #else #error sysapi_get_network_device_info() must be implemented for this platform #endif bool sysapi_get_network_device_info(std::vector<NetworkDeviceInfo> &devices) { if( net_devices_cached ) { devices = net_devices_cache; return true; } bool rc = sysapi_get_network_device_info_raw(devices); if( rc ) { net_devices_cached = true; net_devices_cache = devices; } return rc; } void sysapi_clear_network_device_info_cache() { net_devices_cached = false; }
Fix for crash in sysapi_get_network_device_info_raw. #1800
Fix for crash in sysapi_get_network_device_info_raw. #1800
C++
apache-2.0
htcondor/htcondor,htcondor/htcondor,djw8605/condor,htcondor/htcondor,clalancette/condor-dcloud,mambelli/osg-bosco-marco,djw8605/htcondor,mambelli/osg-bosco-marco,djw8605/condor,bbockelm/condor-network-accounting,zhangzhehust/htcondor,djw8605/htcondor,htcondor/htcondor,djw8605/condor,bbockelm/condor-network-accounting,clalancette/condor-dcloud,htcondor/htcondor,neurodebian/htcondor,djw8605/htcondor,bbockelm/condor-network-accounting,mambelli/osg-bosco-marco,zhangzhehust/htcondor,djw8605/condor,htcondor/htcondor,mambelli/osg-bosco-marco,mambelli/osg-bosco-marco,zhangzhehust/htcondor,zhangzhehust/htcondor,bbockelm/condor-network-accounting,djw8605/condor,mambelli/osg-bosco-marco,clalancette/condor-dcloud,bbockelm/condor-network-accounting,clalancette/condor-dcloud,zhangzhehust/htcondor,djw8605/condor,neurodebian/htcondor,bbockelm/condor-network-accounting,neurodebian/htcondor,neurodebian/htcondor,neurodebian/htcondor,htcondor/htcondor,djw8605/htcondor,zhangzhehust/htcondor,neurodebian/htcondor,htcondor/htcondor,neurodebian/htcondor,neurodebian/htcondor,djw8605/htcondor,mambelli/osg-bosco-marco,djw8605/htcondor,djw8605/htcondor,djw8605/condor,mambelli/osg-bosco-marco,neurodebian/htcondor,clalancette/condor-dcloud,clalancette/condor-dcloud,bbockelm/condor-network-accounting,djw8605/condor,zhangzhehust/htcondor,djw8605/htcondor,zhangzhehust/htcondor,clalancette/condor-dcloud,djw8605/htcondor,zhangzhehust/htcondor,bbockelm/condor-network-accounting
688506de24f04682f9d8563a7d20ab15ab85340b
lib/ExecutionEngine/JIT/JITEmitter.cpp
lib/ExecutionEngine/JIT/JITEmitter.cpp
//===-- Emitter.cpp - Write machine code to executable memory -------------===// // // This file defines a MachineCodeEmitter object that is used by Jello to write // machine code to memory and remember where relocatable values lie. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "jit" #include "VM.h" #include "Config/sys/mman.h" #include "llvm/CodeGen/MachineCodeEmitter.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/Target/TargetData.h" #include "llvm/Module.h" #include "Support/Debug.h" #include "Support/Statistic.h" #include <stdio.h> namespace { Statistic<> NumBytes("jello", "Number of bytes of machine code compiled"); VM *TheVM = 0; class Emitter : public MachineCodeEmitter { // CurBlock - The start of the current block of memory. CurByte - The // current byte being emitted to. unsigned char *CurBlock, *CurByte; // When outputting a function stub in the context of some other function, we // save CurBlock and CurByte here. unsigned char *SavedCurBlock, *SavedCurByte; // ConstantPoolAddresses - Contains the location for each entry in the // constant pool. std::vector<void*> ConstantPoolAddresses; public: Emitter(VM &vm) { TheVM = &vm; } virtual void startFunction(MachineFunction &F); virtual void finishFunction(MachineFunction &F); virtual void emitConstantPool(MachineConstantPool *MCP); virtual void startFunctionStub(const Function &F, unsigned StubSize); virtual void* finishFunctionStub(const Function &F); virtual void emitByte(unsigned char B); virtual void emitWord(unsigned W); virtual uint64_t getGlobalValueAddress(GlobalValue *V); virtual uint64_t getGlobalValueAddress(const std::string &Name); virtual uint64_t getConstantPoolEntryAddress(unsigned Entry); virtual uint64_t getCurrentPCValue(); // forceCompilationOf - Force the compilation of the specified function, and // return its address, because we REALLY need the address now. // // FIXME: This is JIT specific! // virtual uint64_t forceCompilationOf(Function *F); }; } MachineCodeEmitter *VM::createEmitter(VM &V) { return new Emitter(V); } #define _POSIX_MAPPED_FILES #include <unistd.h> #include <sys/mman.h> // FIXME: This should be rewritten to support a real memory manager for // executable memory pages! static void *getMemory(unsigned NumPages) { void *pa; if (NumPages == 0) return 0; static const long pageSize = sysconf(_SC_PAGESIZE); #if defined(i386) || defined(__i386__) || defined(__x86__) /* Linux and *BSD tend to have these flags named differently. */ #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS) # define MAP_ANONYMOUS MAP_ANON #endif /* defined(MAP_ANON) && !defined(MAP_ANONYMOUS) */ #define fd 0 #elif defined(sparc) || defined(__sparc__) || defined(__sparcv9) #define fd -1 #else std::cerr << "This architecture is not supported by the JIT!\n"; abort(); #endif pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANONYMOUS, fd, 0); if (pa == MAP_FAILED) { perror("mmap"); abort(); } return pa; } void Emitter::startFunction(MachineFunction &F) { CurBlock = (unsigned char *)getMemory(16); CurByte = CurBlock; // Start writing at the beginning of the fn. TheVM->addGlobalMapping(F.getFunction(), CurBlock); } void Emitter::finishFunction(MachineFunction &F) { ConstantPoolAddresses.clear(); NumBytes += CurByte-CurBlock; DEBUG(std::cerr << "Finished CodeGen of [" << (void*)CurBlock << "] Function: " << F.getFunction()->getName() << ": " << CurByte-CurBlock << " bytes of text\n"); } void Emitter::emitConstantPool(MachineConstantPool *MCP) { const std::vector<Constant*> &Constants = MCP->getConstants(); for (unsigned i = 0, e = Constants.size(); i != e; ++i) { // For now we just allocate some memory on the heap, this can be // dramatically improved. const Type *Ty = ((Value*)Constants[i])->getType(); void *Addr = malloc(TheVM->getTargetData().getTypeSize(Ty)); TheVM->InitializeMemory(Constants[i], Addr); ConstantPoolAddresses.push_back(Addr); } } void Emitter::startFunctionStub(const Function &F, unsigned StubSize) { static const long pageSize = sysconf(_SC_PAGESIZE); SavedCurBlock = CurBlock; SavedCurByte = CurByte; // FIXME: this is a huge waste of memory. CurBlock = (unsigned char *)getMemory((StubSize+pageSize-1)/pageSize); CurByte = CurBlock; // Start writing at the beginning of the fn. } void *Emitter::finishFunctionStub(const Function &F) { NumBytes += CurByte-CurBlock; DEBUG(std::cerr << "Finished CodeGen of [0x" << std::hex << (unsigned)(intptr_t)CurBlock << std::dec << "] Function stub for: " << F.getName() << ": " << CurByte-CurBlock << " bytes of text\n"); std::swap(CurBlock, SavedCurBlock); CurByte = SavedCurByte; return SavedCurBlock; } void Emitter::emitByte(unsigned char B) { *CurByte++ = B; // Write the byte to memory } void Emitter::emitWord(unsigned W) { // FIXME: This won't work if the endianness of the host and target don't // agree! (For a JIT this can't happen though. :) *(unsigned*)CurByte = W; CurByte += sizeof(unsigned); } uint64_t Emitter::getGlobalValueAddress(GlobalValue *V) { // Try looking up the function to see if it is already compiled, if not return // 0. return (intptr_t)TheVM->getPointerToGlobalIfAvailable(V); } uint64_t Emitter::getGlobalValueAddress(const std::string &Name) { return (intptr_t)TheVM->getPointerToNamedFunction(Name); } // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry // in the constant pool that was last emitted with the 'emitConstantPool' // method. // uint64_t Emitter::getConstantPoolEntryAddress(unsigned ConstantNum) { assert(ConstantNum < ConstantPoolAddresses.size() && "Invalid ConstantPoolIndex!"); return (intptr_t)ConstantPoolAddresses[ConstantNum]; } // getCurrentPCValue - This returns the address that the next emitted byte // will be output to. // uint64_t Emitter::getCurrentPCValue() { return (intptr_t)CurByte; } uint64_t Emitter::forceCompilationOf(Function *F) { return (intptr_t)TheVM->getPointerToFunction(F); } // getPointerToNamedFunction - This function is used as a global wrapper to // VM::getPointerToNamedFunction for the purpose of resolving symbols when // bugpoint is debugging the JIT. In that scenario, we are loading an .so and // need to resolve function(s) that are being mis-codegenerated, so we need to // resolve their addresses at runtime, and this is the way to do it. extern "C" { void *getPointerToNamedFunction(const char *Name) { Module &M = TheVM->getModule(); if (Function *F = M.getNamedFunction(Name)) return TheVM->getPointerToFunction(F); return TheVM->getPointerToNamedFunction(Name); } }
//===-- Emitter.cpp - Write machine code to executable memory -------------===// // // This file defines a MachineCodeEmitter object that is used by Jello to write // machine code to memory and remember where relocatable values lie. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "jit" #include "VM.h" #include "Config/sys/mman.h" #include "llvm/CodeGen/MachineCodeEmitter.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/Target/TargetData.h" #include "llvm/Module.h" #include "Support/Debug.h" #include "Support/Statistic.h" #include <stdio.h> namespace { Statistic<> NumBytes("jello", "Number of bytes of machine code compiled"); VM *TheVM = 0; /// JITMemoryManager - Manage memory for the JIT code generation in a logical, /// sane way. This splits a large block of MAP_NORESERVE'd memory into two /// sections, one for function stubs, one for the functions themselves. We /// have to do this because we may need to emit a function stub while in the /// middle of emitting a function, and we don't know how large the function we /// are emitting is. This never bothers to release the memory, because when /// we are ready to destroy the JIT, the program exits. class JITMemoryManager { unsigned char *MemBase; // Base of block of memory, start of stub mem unsigned char *FunctionBase; // Start of the function body area unsigned char *CurStubPtr, *CurFunctionPtr; public: JITMemoryManager(); inline unsigned char *allocateStub(unsigned StubSize); inline unsigned char *startFunctionBody(); inline void endFunctionBody(unsigned char *FunctionEnd); }; } #define _POSIX_MAPPED_FILES #include <unistd.h> #include <sys/mman.h> // getMemory - Return a pointer to the specified number of bytes, which is // mapped as executable readable and writable. static void *getMemory(unsigned NumBytes) { if (NumBytes == 0) return 0; static const long pageSize = sysconf(_SC_PAGESIZE); unsigned NumPages = (NumBytes+pageSize-1)/pageSize; #if defined(i386) || defined(__i386__) || defined(__x86__) /* Linux and *BSD tend to have these flags named differently. */ #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS) # define MAP_ANONYMOUS MAP_ANON #endif /* defined(MAP_ANON) && !defined(MAP_ANONYMOUS) */ #define fd 0 #elif defined(sparc) || defined(__sparc__) || defined(__sparcv9) #define fd -1 #else std::cerr << "This architecture is not supported by the JIT!\n"; abort(); #endif unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS; #ifdef MAP_NORESERVE mmapFlags |= MAP_NORESERVE; #endif void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANONYMOUS, fd, 0); if (pa == MAP_FAILED) { perror("mmap"); abort(); } return pa; } JITMemoryManager::JITMemoryManager() { // Allocate a 16M block of memory... MemBase = (unsigned char*)getMemory(16 << 20); FunctionBase = MemBase + 512*1024; // Use 512k for stubs // Allocate stubs backwards from the function base, allocate functions forward // from the function base. CurStubPtr = CurFunctionPtr = FunctionBase; } unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) { CurStubPtr -= StubSize; if (CurStubPtr < MemBase) { std::cerr << "JIT ran out of memory for function stubs!\n"; abort(); } return CurStubPtr; } unsigned char *JITMemoryManager::startFunctionBody() { // Round up to an even multiple of 4 bytes, this should eventually be target // specific. return (unsigned char*)(((intptr_t)CurFunctionPtr + 3) & ~3); } void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) { assert(FunctionEnd > CurFunctionPtr); CurFunctionPtr = FunctionEnd; } namespace { /// Emitter - The JIT implementation of the MachineCodeEmiter, which is used /// to output functions to memory for execution. class Emitter : public MachineCodeEmitter { JITMemoryManager MemMgr; // CurBlock - The start of the current block of memory. CurByte - The // current byte being emitted to. unsigned char *CurBlock, *CurByte; // When outputting a function stub in the context of some other function, we // save CurBlock and CurByte here. unsigned char *SavedCurBlock, *SavedCurByte; // ConstantPoolAddresses - Contains the location for each entry in the // constant pool. std::vector<void*> ConstantPoolAddresses; public: Emitter(VM &vm) { TheVM = &vm; } virtual void startFunction(MachineFunction &F); virtual void finishFunction(MachineFunction &F); virtual void emitConstantPool(MachineConstantPool *MCP); virtual void startFunctionStub(const Function &F, unsigned StubSize); virtual void* finishFunctionStub(const Function &F); virtual void emitByte(unsigned char B); virtual void emitWord(unsigned W); virtual uint64_t getGlobalValueAddress(GlobalValue *V); virtual uint64_t getGlobalValueAddress(const std::string &Name); virtual uint64_t getConstantPoolEntryAddress(unsigned Entry); virtual uint64_t getCurrentPCValue(); // forceCompilationOf - Force the compilation of the specified function, and // return its address, because we REALLY need the address now. // // FIXME: This is JIT specific! // virtual uint64_t forceCompilationOf(Function *F); }; } MachineCodeEmitter *VM::createEmitter(VM &V) { return new Emitter(V); } void Emitter::startFunction(MachineFunction &F) { CurByte = CurBlock = MemMgr.startFunctionBody(); TheVM->addGlobalMapping(F.getFunction(), CurBlock); } void Emitter::finishFunction(MachineFunction &F) { MemMgr.endFunctionBody(CurByte); ConstantPoolAddresses.clear(); NumBytes += CurByte-CurBlock; DEBUG(std::cerr << "Finished CodeGen of [" << (void*)CurBlock << "] Function: " << F.getFunction()->getName() << ": " << CurByte-CurBlock << " bytes of text\n"); } void Emitter::emitConstantPool(MachineConstantPool *MCP) { const std::vector<Constant*> &Constants = MCP->getConstants(); for (unsigned i = 0, e = Constants.size(); i != e; ++i) { // For now we just allocate some memory on the heap, this can be // dramatically improved. const Type *Ty = ((Value*)Constants[i])->getType(); void *Addr = malloc(TheVM->getTargetData().getTypeSize(Ty)); TheVM->InitializeMemory(Constants[i], Addr); ConstantPoolAddresses.push_back(Addr); } } void Emitter::startFunctionStub(const Function &F, unsigned StubSize) { SavedCurBlock = CurBlock; SavedCurByte = CurByte; CurByte = CurBlock = MemMgr.allocateStub(StubSize); } void *Emitter::finishFunctionStub(const Function &F) { NumBytes += CurByte-CurBlock; DEBUG(std::cerr << "Finished CodeGen of [0x" << std::hex << (unsigned)(intptr_t)CurBlock << std::dec << "] Function stub for: " << F.getName() << ": " << CurByte-CurBlock << " bytes of text\n"); std::swap(CurBlock, SavedCurBlock); CurByte = SavedCurByte; return SavedCurBlock; } void Emitter::emitByte(unsigned char B) { *CurByte++ = B; // Write the byte to memory } void Emitter::emitWord(unsigned W) { // This won't work if the endianness of the host and target don't agree! (For // a JIT this can't happen though. :) *(unsigned*)CurByte = W; CurByte += sizeof(unsigned); } uint64_t Emitter::getGlobalValueAddress(GlobalValue *V) { // Try looking up the function to see if it is already compiled, if not return // 0. return (intptr_t)TheVM->getPointerToGlobalIfAvailable(V); } uint64_t Emitter::getGlobalValueAddress(const std::string &Name) { return (intptr_t)TheVM->getPointerToNamedFunction(Name); } // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry // in the constant pool that was last emitted with the 'emitConstantPool' // method. // uint64_t Emitter::getConstantPoolEntryAddress(unsigned ConstantNum) { assert(ConstantNum < ConstantPoolAddresses.size() && "Invalid ConstantPoolIndex!"); return (intptr_t)ConstantPoolAddresses[ConstantNum]; } // getCurrentPCValue - This returns the address that the next emitted byte // will be output to. // uint64_t Emitter::getCurrentPCValue() { return (intptr_t)CurByte; } uint64_t Emitter::forceCompilationOf(Function *F) { return (intptr_t)TheVM->getPointerToFunction(F); } // getPointerToNamedFunction - This function is used as a global wrapper to // VM::getPointerToNamedFunction for the purpose of resolving symbols when // bugpoint is debugging the JIT. In that scenario, we are loading an .so and // need to resolve function(s) that are being mis-codegenerated, so we need to // resolve their addresses at runtime, and this is the way to do it. extern "C" { void *getPointerToNamedFunction(const char *Name) { Module &M = TheVM->getModule(); if (Function *F = M.getNamedFunction(Name)) return TheVM->getPointerToFunction(F); return TheVM->getPointerToNamedFunction(Name); } }
Implement a _REAL_ memory manager for the code generated by the JIT. This speeds up program execution by 15% pretty consistently for large programs
Implement a _REAL_ memory manager for the code generated by the JIT. This speeds up program execution by 15% pretty consistently for large programs git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@7845 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-2-clause
dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap
589458da18f1b5e037e79b51872dd7fd30469e5d
src/test/multisig_tests.cpp
src/test/multisig_tests.cpp
// Copyright (c) 2011-2013 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "key.h" #include "keystore.h" #include "main.h" #include "script/script.h" #include "script/script_error.h" #include "script/interpreter.h" #include "script/sign.h" #include "uint256.h" #ifdef ENABLE_WALLET #include "wallet_ismine.h" #endif #include <boost/assign/std/vector.hpp> #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> using namespace std; using namespace boost::assign; typedef vector<unsigned char> valtype; BOOST_AUTO_TEST_SUITE(multisig_tests) CScript sign_multisig(CScript scriptPubKey, vector<CKey> keys, CTransaction transaction, int whichIn) { uint256 hash = SignatureHash(scriptPubKey, transaction, whichIn, SIGHASH_ALL); CScript result; result << OP_0; // CHECKMULTISIG bug workaround BOOST_FOREACH(const CKey &key, keys) { vector<unsigned char> vchSig; BOOST_CHECK(key.Sign(hash, vchSig)); vchSig.push_back((unsigned char)SIGHASH_ALL); result << vchSig; } return result; } BOOST_AUTO_TEST_CASE(multisig_verify) { unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC; ScriptError err; CKey key[4]; for (int i = 0; i < 4; i++) key[i].MakeNewKey(true); CScript a_and_b; a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CScript a_or_b; a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CScript escrow; escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; CMutableTransaction txFrom; // Funding transaction txFrom.vout.resize(3); txFrom.vout[0].scriptPubKey = a_and_b; txFrom.vout[1].scriptPubKey = a_or_b; txFrom.vout[2].scriptPubKey = escrow; CMutableTransaction txTo[3]; // Spending transaction for (int i = 0; i < 3; i++) { txTo[i].vin.resize(1); txTo[i].vout.resize(1); txTo[i].vin[0].prevout.n = i; txTo[i].vin[0].prevout.hash = txFrom.GetHash(); txTo[i].vout[0].nValue = 1; } vector<CKey> keys; CScript s; // Test a AND b: keys.clear(); keys += key[0],key[1]; // magic operator+= from boost.assign s = sign_multisig(a_and_b, keys, txTo[0], 0); BOOST_CHECK(VerifyScript(s, a_and_b, flags, SignatureChecker(txTo[0], 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); for (int i = 0; i < 4; i++) { keys.clear(); keys += key[i]; s = sign_multisig(a_and_b, keys, txTo[0], 0); BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, flags, SignatureChecker(txTo[0], 0), &err), strprintf("a&b 1: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err)); keys.clear(); keys += key[1],key[i]; s = sign_multisig(a_and_b, keys, txTo[0], 0); BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, flags, SignatureChecker(txTo[0], 0), &err), strprintf("a&b 2: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } // Test a OR b: for (int i = 0; i < 4; i++) { keys.clear(); keys += key[i]; s = sign_multisig(a_or_b, keys, txTo[1], 0); if (i == 0 || i == 1) { BOOST_CHECK_MESSAGE(VerifyScript(s, a_or_b, flags, SignatureChecker(txTo[1], 0), &err), strprintf("a|b: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } else { BOOST_CHECK_MESSAGE(!VerifyScript(s, a_or_b, flags, SignatureChecker(txTo[1], 0), &err), strprintf("a|b: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } } s.clear(); s << OP_0 << OP_0; BOOST_CHECK(!VerifyScript(s, a_or_b, flags, SignatureChecker(txTo[1], 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_SIG_DER, ScriptErrorString(err)); s.clear(); s << OP_0 << OP_1; BOOST_CHECK(!VerifyScript(s, a_or_b, flags, SignatureChecker(txTo[1], 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_SIG_DER, ScriptErrorString(err)); for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { keys.clear(); keys += key[i],key[j]; s = sign_multisig(escrow, keys, txTo[2], 0); if (i < j && i < 3 && j < 3) { BOOST_CHECK_MESSAGE(VerifyScript(s, escrow, flags, SignatureChecker(txTo[2], 0), &err), strprintf("escrow 1: %d %d", i, j)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } else { BOOST_CHECK_MESSAGE(!VerifyScript(s, escrow, flags, SignatureChecker(txTo[2], 0), &err), strprintf("escrow 2: %d %d", i, j)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } } } BOOST_AUTO_TEST_CASE(multisig_IsStandard) { CKey key[4]; for (int i = 0; i < 4; i++) key[i].MakeNewKey(true); txnouttype whichType; CScript a_and_b; a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(::IsStandard(a_and_b, whichType)); CScript a_or_b; a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(::IsStandard(a_or_b, whichType)); CScript escrow; escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; BOOST_CHECK(::IsStandard(escrow, whichType)); CScript one_of_four; one_of_four << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << ToByteVector(key[3].GetPubKey()) << OP_4 << OP_CHECKMULTISIG; BOOST_CHECK(!::IsStandard(one_of_four, whichType)); CScript malformed[6]; malformed[0] << OP_3 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; malformed[1] << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; malformed[2] << OP_0 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; malformed[3] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_0 << OP_CHECKMULTISIG; malformed[4] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_CHECKMULTISIG; malformed[5] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()); for (int i = 0; i < 6; i++) BOOST_CHECK(!::IsStandard(malformed[i], whichType)); } BOOST_AUTO_TEST_CASE(multisig_Solver1) { // Tests Solver() that returns lists of keys that are // required to satisfy a ScriptPubKey // // Also tests IsMine() and ExtractDestination() // // Note: ExtractDestination for the multisignature transactions // always returns false for this release, even if you have // one key that would satisfy an (a|b) or 2-of-3 keys needed // to spend an escrow transaction. // CBasicKeyStore keystore, emptykeystore, partialkeystore; CKey key[3]; CTxDestination keyaddr[3]; for (int i = 0; i < 3; i++) { key[i].MakeNewKey(true); keystore.AddKey(key[i]); keyaddr[i] = key[i].GetPubKey().GetID(); } partialkeystore.AddKey(key[0]); { vector<valtype> solutions; txnouttype whichType; CScript s; s << ToByteVector(key[0].GetPubKey()) << OP_CHECKSIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK(solutions.size() == 1); CTxDestination addr; BOOST_CHECK(ExtractDestination(s, addr)); BOOST_CHECK(addr == keyaddr[0]); #ifdef ENABLE_WALLET BOOST_CHECK(IsMine(keystore, s)); BOOST_CHECK(!IsMine(emptykeystore, s)); #endif } { vector<valtype> solutions; txnouttype whichType; CScript s; s << OP_DUP << OP_HASH160 << ToByteVector(key[0].GetPubKey().GetID()) << OP_EQUALVERIFY << OP_CHECKSIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK(solutions.size() == 1); CTxDestination addr; BOOST_CHECK(ExtractDestination(s, addr)); BOOST_CHECK(addr == keyaddr[0]); #ifdef ENABLE_WALLET BOOST_CHECK(IsMine(keystore, s)); BOOST_CHECK(!IsMine(emptykeystore, s)); #endif } { vector<valtype> solutions; txnouttype whichType; CScript s; s << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK_EQUAL(solutions.size(), 4U); CTxDestination addr; BOOST_CHECK(!ExtractDestination(s, addr)); #ifdef ENABLE_WALLET BOOST_CHECK(IsMine(keystore, s)); BOOST_CHECK(!IsMine(emptykeystore, s)); BOOST_CHECK(!IsMine(partialkeystore, s)); #endif } { vector<valtype> solutions; txnouttype whichType; CScript s; s << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK_EQUAL(solutions.size(), 4U); vector<CTxDestination> addrs; int nRequired; BOOST_CHECK(ExtractDestinations(s, whichType, addrs, nRequired)); BOOST_CHECK(addrs[0] == keyaddr[0]); BOOST_CHECK(addrs[1] == keyaddr[1]); BOOST_CHECK(nRequired == 1); #ifdef ENABLE_WALLET BOOST_CHECK(IsMine(keystore, s)); BOOST_CHECK(!IsMine(emptykeystore, s)); BOOST_CHECK(!IsMine(partialkeystore, s)); #endif } { vector<valtype> solutions; txnouttype whichType; CScript s; s << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK(solutions.size() == 5); } } BOOST_AUTO_TEST_CASE(multisig_Sign) { // Test SignSignature() (and therefore the version of Solver() that signs transactions) CBasicKeyStore keystore; CKey key[4]; for (int i = 0; i < 4; i++) { key[i].MakeNewKey(true); keystore.AddKey(key[i]); } CScript a_and_b; a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CScript a_or_b; a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CScript escrow; escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; CMutableTransaction txFrom; // Funding transaction txFrom.vout.resize(3); txFrom.vout[0].scriptPubKey = a_and_b; txFrom.vout[1].scriptPubKey = a_or_b; txFrom.vout[2].scriptPubKey = escrow; CMutableTransaction txTo[3]; // Spending transaction for (int i = 0; i < 3; i++) { txTo[i].vin.resize(1); txTo[i].vout.resize(1); txTo[i].vin[0].prevout.n = i; txTo[i].vin[0].prevout.hash = txFrom.GetHash(); txTo[i].vout[0].nValue = 1; } for (int i = 0; i < 3; i++) { BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i)); } } BOOST_AUTO_TEST_SUITE_END()
// Copyright (c) 2011-2013 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "key.h" #include "keystore.h" #include "main.h" #include "script/script.h" #include "script/script_error.h" #include "script/interpreter.h" #include "script/sign.h" #include "uint256.h" #ifdef ENABLE_WALLET #include "wallet_ismine.h" #endif #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> using namespace std; typedef vector<unsigned char> valtype; BOOST_AUTO_TEST_SUITE(multisig_tests) CScript sign_multisig(CScript scriptPubKey, vector<CKey> keys, CTransaction transaction, int whichIn) { uint256 hash = SignatureHash(scriptPubKey, transaction, whichIn, SIGHASH_ALL); CScript result; result << OP_0; // CHECKMULTISIG bug workaround BOOST_FOREACH(const CKey &key, keys) { vector<unsigned char> vchSig; BOOST_CHECK(key.Sign(hash, vchSig)); vchSig.push_back((unsigned char)SIGHASH_ALL); result << vchSig; } return result; } BOOST_AUTO_TEST_CASE(multisig_verify) { unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC; ScriptError err; CKey key[4]; for (int i = 0; i < 4; i++) key[i].MakeNewKey(true); CScript a_and_b; a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CScript a_or_b; a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CScript escrow; escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; CMutableTransaction txFrom; // Funding transaction txFrom.vout.resize(3); txFrom.vout[0].scriptPubKey = a_and_b; txFrom.vout[1].scriptPubKey = a_or_b; txFrom.vout[2].scriptPubKey = escrow; CMutableTransaction txTo[3]; // Spending transaction for (int i = 0; i < 3; i++) { txTo[i].vin.resize(1); txTo[i].vout.resize(1); txTo[i].vin[0].prevout.n = i; txTo[i].vin[0].prevout.hash = txFrom.GetHash(); txTo[i].vout[0].nValue = 1; } vector<CKey> keys; CScript s; // Test a AND b: keys.assign(1,key[0]); keys.push_back(key[1]); s = sign_multisig(a_and_b, keys, txTo[0], 0); BOOST_CHECK(VerifyScript(s, a_and_b, flags, SignatureChecker(txTo[0], 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); for (int i = 0; i < 4; i++) { keys.assign(1,key[i]); s = sign_multisig(a_and_b, keys, txTo[0], 0); BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, flags, SignatureChecker(txTo[0], 0), &err), strprintf("a&b 1: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err)); keys.assign(1,key[1]); keys.push_back(key[i]); s = sign_multisig(a_and_b, keys, txTo[0], 0); BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, flags, SignatureChecker(txTo[0], 0), &err), strprintf("a&b 2: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } // Test a OR b: for (int i = 0; i < 4; i++) { keys.assign(1,key[i]); s = sign_multisig(a_or_b, keys, txTo[1], 0); if (i == 0 || i == 1) { BOOST_CHECK_MESSAGE(VerifyScript(s, a_or_b, flags, SignatureChecker(txTo[1], 0), &err), strprintf("a|b: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } else { BOOST_CHECK_MESSAGE(!VerifyScript(s, a_or_b, flags, SignatureChecker(txTo[1], 0), &err), strprintf("a|b: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } } s.clear(); s << OP_0 << OP_0; BOOST_CHECK(!VerifyScript(s, a_or_b, flags, SignatureChecker(txTo[1], 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_SIG_DER, ScriptErrorString(err)); s.clear(); s << OP_0 << OP_1; BOOST_CHECK(!VerifyScript(s, a_or_b, flags, SignatureChecker(txTo[1], 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_SIG_DER, ScriptErrorString(err)); for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { keys.assign(1,key[i]); keys.push_back(key[j]); s = sign_multisig(escrow, keys, txTo[2], 0); if (i < j && i < 3 && j < 3) { BOOST_CHECK_MESSAGE(VerifyScript(s, escrow, flags, SignatureChecker(txTo[2], 0), &err), strprintf("escrow 1: %d %d", i, j)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } else { BOOST_CHECK_MESSAGE(!VerifyScript(s, escrow, flags, SignatureChecker(txTo[2], 0), &err), strprintf("escrow 2: %d %d", i, j)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } } } BOOST_AUTO_TEST_CASE(multisig_IsStandard) { CKey key[4]; for (int i = 0; i < 4; i++) key[i].MakeNewKey(true); txnouttype whichType; CScript a_and_b; a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(::IsStandard(a_and_b, whichType)); CScript a_or_b; a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(::IsStandard(a_or_b, whichType)); CScript escrow; escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; BOOST_CHECK(::IsStandard(escrow, whichType)); CScript one_of_four; one_of_four << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << ToByteVector(key[3].GetPubKey()) << OP_4 << OP_CHECKMULTISIG; BOOST_CHECK(!::IsStandard(one_of_four, whichType)); CScript malformed[6]; malformed[0] << OP_3 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; malformed[1] << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; malformed[2] << OP_0 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; malformed[3] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_0 << OP_CHECKMULTISIG; malformed[4] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_CHECKMULTISIG; malformed[5] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()); for (int i = 0; i < 6; i++) BOOST_CHECK(!::IsStandard(malformed[i], whichType)); } BOOST_AUTO_TEST_CASE(multisig_Solver1) { // Tests Solver() that returns lists of keys that are // required to satisfy a ScriptPubKey // // Also tests IsMine() and ExtractDestination() // // Note: ExtractDestination for the multisignature transactions // always returns false for this release, even if you have // one key that would satisfy an (a|b) or 2-of-3 keys needed // to spend an escrow transaction. // CBasicKeyStore keystore, emptykeystore, partialkeystore; CKey key[3]; CTxDestination keyaddr[3]; for (int i = 0; i < 3; i++) { key[i].MakeNewKey(true); keystore.AddKey(key[i]); keyaddr[i] = key[i].GetPubKey().GetID(); } partialkeystore.AddKey(key[0]); { vector<valtype> solutions; txnouttype whichType; CScript s; s << ToByteVector(key[0].GetPubKey()) << OP_CHECKSIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK(solutions.size() == 1); CTxDestination addr; BOOST_CHECK(ExtractDestination(s, addr)); BOOST_CHECK(addr == keyaddr[0]); #ifdef ENABLE_WALLET BOOST_CHECK(IsMine(keystore, s)); BOOST_CHECK(!IsMine(emptykeystore, s)); #endif } { vector<valtype> solutions; txnouttype whichType; CScript s; s << OP_DUP << OP_HASH160 << ToByteVector(key[0].GetPubKey().GetID()) << OP_EQUALVERIFY << OP_CHECKSIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK(solutions.size() == 1); CTxDestination addr; BOOST_CHECK(ExtractDestination(s, addr)); BOOST_CHECK(addr == keyaddr[0]); #ifdef ENABLE_WALLET BOOST_CHECK(IsMine(keystore, s)); BOOST_CHECK(!IsMine(emptykeystore, s)); #endif } { vector<valtype> solutions; txnouttype whichType; CScript s; s << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK_EQUAL(solutions.size(), 4U); CTxDestination addr; BOOST_CHECK(!ExtractDestination(s, addr)); #ifdef ENABLE_WALLET BOOST_CHECK(IsMine(keystore, s)); BOOST_CHECK(!IsMine(emptykeystore, s)); BOOST_CHECK(!IsMine(partialkeystore, s)); #endif } { vector<valtype> solutions; txnouttype whichType; CScript s; s << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK_EQUAL(solutions.size(), 4U); vector<CTxDestination> addrs; int nRequired; BOOST_CHECK(ExtractDestinations(s, whichType, addrs, nRequired)); BOOST_CHECK(addrs[0] == keyaddr[0]); BOOST_CHECK(addrs[1] == keyaddr[1]); BOOST_CHECK(nRequired == 1); #ifdef ENABLE_WALLET BOOST_CHECK(IsMine(keystore, s)); BOOST_CHECK(!IsMine(emptykeystore, s)); BOOST_CHECK(!IsMine(partialkeystore, s)); #endif } { vector<valtype> solutions; txnouttype whichType; CScript s; s << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK(solutions.size() == 5); } } BOOST_AUTO_TEST_CASE(multisig_Sign) { // Test SignSignature() (and therefore the version of Solver() that signs transactions) CBasicKeyStore keystore; CKey key[4]; for (int i = 0; i < 4; i++) { key[i].MakeNewKey(true); keystore.AddKey(key[i]); } CScript a_and_b; a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CScript a_or_b; a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CScript escrow; escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; CMutableTransaction txFrom; // Funding transaction txFrom.vout.resize(3); txFrom.vout[0].scriptPubKey = a_and_b; txFrom.vout[1].scriptPubKey = a_or_b; txFrom.vout[2].scriptPubKey = escrow; CMutableTransaction txTo[3]; // Spending transaction for (int i = 0; i < 3; i++) { txTo[i].vin.resize(1); txTo[i].vout.resize(1); txTo[i].vin[0].prevout.n = i; txTo[i].vin[0].prevout.hash = txFrom.GetHash(); txTo[i].vout[0].nValue = 1; } for (int i = 0; i < 3; i++) { BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i)); } } BOOST_AUTO_TEST_SUITE_END()
drop boost::assign altogether here
namespace: drop boost::assign altogether here Standard functions are even simpler
C++
mit
syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin
29354a1586013d5be341aaf4d89635b87298c853
data_structures/coordinate.cpp
data_structures/coordinate.cpp
/* Copyright (c) 2015, Project OSRM, Dennis Luxen, others 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. 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 "coordinate_calculation.hpp" #include "../Util/mercator.hpp" #include "../Util/simple_logger.hpp" #include <boost/assert.hpp> #include <osrm/coordinate.hpp> #include <cmath> #ifndef NDEBUG #include <bitset> #endif #include <limits> FixedPointCoordinate::FixedPointCoordinate() : lat(std::numeric_limits<int>::min()), lon(std::numeric_limits<int>::min()) { } FixedPointCoordinate::FixedPointCoordinate(int lat, int lon) : lat(lat), lon(lon) { #ifndef NDEBUG if (0 != (std::abs(lat) >> 30)) { std::bitset<32> y_coordinate_vector(lat); SimpleLogger().Write(logDEBUG) << "broken lat: " << lat << ", bits: " << y_coordinate_vector; } if (0 != (std::abs(lon) >> 30)) { std::bitset<32> x_coordinate_vector(lon); SimpleLogger().Write(logDEBUG) << "broken lon: " << lon << ", bits: " << x_coordinate_vector; } #endif } bool FixedPointCoordinate::is_valid() const { if (lat > 90 * COORDINATE_PRECISION || lat < -90 * COORDINATE_PRECISION || lon > 180 * COORDINATE_PRECISION || lon < -180 * COORDINATE_PRECISION) { return false; } return true; } bool FixedPointCoordinate::operator==(const FixedPointCoordinate &other) const { return lat == other.lat && lon == other.lon; } void FixedPointCoordinate::output(std::ostream &out) const { out << "(" << lat / COORDINATE_PRECISION << "," << lon / COORDINATE_PRECISION << ")"; } float FixedPointCoordinate::bearing(const FixedPointCoordinate &other) const { return coordinate_calculation::bearing(*this, other); }
/* Copyright (c) 2015, Project OSRM, Dennis Luxen, others 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. 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 "coordinate_calculation.hpp" #include "../Util/mercator.hpp" #ifndef NDEBUG #include "../Util/simple_logger.hpp" #endif #include <boost/assert.hpp> #include <osrm/coordinate.hpp> #include <cmath> #ifndef NDEBUG #include <bitset> #endif #include <limits> FixedPointCoordinate::FixedPointCoordinate() : lat(std::numeric_limits<int>::min()), lon(std::numeric_limits<int>::min()) { } FixedPointCoordinate::FixedPointCoordinate(int lat, int lon) : lat(lat), lon(lon) { #ifndef NDEBUG if (0 != (std::abs(lat) >> 30)) { std::bitset<32> y_coordinate_vector(lat); SimpleLogger().Write(logDEBUG) << "broken lat: " << lat << ", bits: " << y_coordinate_vector; } if (0 != (std::abs(lon) >> 30)) { std::bitset<32> x_coordinate_vector(lon); SimpleLogger().Write(logDEBUG) << "broken lon: " << lon << ", bits: " << x_coordinate_vector; } #endif } bool FixedPointCoordinate::is_valid() const { if (lat > 90 * COORDINATE_PRECISION || lat < -90 * COORDINATE_PRECISION || lon > 180 * COORDINATE_PRECISION || lon < -180 * COORDINATE_PRECISION) { return false; } return true; } bool FixedPointCoordinate::operator==(const FixedPointCoordinate &other) const { return lat == other.lat && lon == other.lon; } void FixedPointCoordinate::output(std::ostream &out) const { out << "(" << lat / COORDINATE_PRECISION << "," << lon / COORDINATE_PRECISION << ")"; } float FixedPointCoordinate::bearing(const FixedPointCoordinate &other) const { return coordinate_calculation::bearing(other, *this); }
fix bearing computation
fix bearing computation
C++
bsd-2-clause
ammeurer/osrm-backend,oxidase/osrm-backend,arnekaiser/osrm-backend,oxidase/osrm-backend,KnockSoftware/osrm-backend,KnockSoftware/osrm-backend,neilbu/osrm-backend,arnekaiser/osrm-backend,bjtaylor1/osrm-backend,agruss/osrm-backend,Tristramg/osrm-backend,Conggge/osrm-backend,Project-OSRM/osrm-backend,prembasumatary/osrm-backend,chaupow/osrm-backend,atsuyim/osrm-backend,deniskoronchik/osrm-backend,frodrigo/osrm-backend,bjtaylor1/osrm-backend,Conggge/osrm-backend,bitsteller/osrm-backend,KnockSoftware/osrm-backend,raymond0/osrm-backend,ramyaragupathy/osrm-backend,felixguendling/osrm-backend,bjtaylor1/osrm-backend,Project-OSRM/osrm-backend,skyborla/osrm-backend,raymond0/osrm-backend,nagyistoce/osrm-backend,neilbu/osrm-backend,antoinegiret/osrm-geovelo,Tristramg/osrm-backend,nagyistoce/osrm-backend,ammeurer/osrm-backend,neilbu/osrm-backend,hydrays/osrm-backend,tkhaxton/osrm-backend,nagyistoce/osrm-backend,atsuyim/osrm-backend,neilbu/osrm-backend,jpizarrom/osrm-backend,KnockSoftware/osrm-backend,ammeurer/osrm-backend,felixguendling/osrm-backend,chaupow/osrm-backend,duizendnegen/osrm-backend,hydrays/osrm-backend,ammeurer/osrm-backend,yuryleb/osrm-backend,raymond0/osrm-backend,ramyaragupathy/osrm-backend,bitsteller/osrm-backend,oxidase/osrm-backend,tkhaxton/osrm-backend,prembasumatary/osrm-backend,alex85k/Project-OSRM,raymond0/osrm-backend,frodrigo/osrm-backend,Tristramg/osrm-backend,hydrays/osrm-backend,atsuyim/osrm-backend,duizendnegen/osrm-backend,jpizarrom/osrm-backend,antoinegiret/osrm-geovelo,prembasumatary/osrm-backend,Conggge/osrm-backend,bjtaylor1/osrm-backend,ammeurer/osrm-backend,jpizarrom/osrm-backend,agruss/osrm-backend,Project-OSRM/osrm-backend,beemogmbh/osrm-backend,deniskoronchik/osrm-backend,antoinegiret/osrm-geovelo,felixguendling/osrm-backend,deniskoronchik/osrm-backend,skyborla/osrm-backend,tkhaxton/osrm-backend,agruss/osrm-backend,frodrigo/osrm-backend,arnekaiser/osrm-backend,arnekaiser/osrm-backend,alex85k/Project-OSRM,oxidase/osrm-backend,beemogmbh/osrm-backend,duizendnegen/osrm-backend,alex85k/Project-OSRM,beemogmbh/osrm-backend,bitsteller/osrm-backend,ammeurer/osrm-backend,duizendnegen/osrm-backend,Project-OSRM/osrm-backend,yuryleb/osrm-backend,skyborla/osrm-backend,beemogmbh/osrm-backend,hydrays/osrm-backend,yuryleb/osrm-backend,deniskoronchik/osrm-backend,frodrigo/osrm-backend,ammeurer/osrm-backend,Conggge/osrm-backend,chaupow/osrm-backend,yuryleb/osrm-backend,ramyaragupathy/osrm-backend
0f8ef5c2dd9a3364383d19a5241c4ca54d5289e4
src/SUAPI-CppWrapper/model/AttributeDictionary.cpp
src/SUAPI-CppWrapper/model/AttributeDictionary.cpp
// // AttributeDictionary.cpp // // Sketchup C++ Wrapper for C API // MIT License // // Copyright (c) 2017 Tom Kaneko // // 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 <cassert> #include <stdexcept> #include <algorithm> #include "SUAPI-CppWrapper/model/AttributeDictionary.hpp" #include "SUAPI-CppWrapper/model/TypedValue.hpp" #include "SUAPI-CppWrapper/String.hpp" namespace CW { extern size_t SU_VERSION_MAJOR; /****************** * Private Static methods *******************/ SUAttributeDictionaryRef AttributeDictionary::create_attribute_dictionary(const std::string& name) { if (SU_VERSION_MAJOR < 18) { throw std::logic_error("AttributeDictionary::create_attribute_dictionary(): Cannot use function prior to SU version 2018"); } SUAttributeDictionaryRef dict = SU_INVALID; SUResult res = SUAttributeDictionaryCreate(&dict, name.c_str()); assert(res == SU_ERROR_NONE); return dict; } SUAttributeDictionaryRef AttributeDictionary::copy_reference(const AttributeDictionary& other) { if (SU_VERSION_MAJOR < 18) { throw std::logic_error("AttributeDictionary::create_attribute_dictionary(): Cannot use function prior to SU version 2018"); } if (other.m_attached || !other) { return other.m_dict; } // The other Attributedictionary has not been attached to the model, so copy its properties to a new object SUAttributeDictionaryRef new_dict = create_attribute_dictionary(other.get_name()); return new_dict; } /***************************** * Constructor / Destructors ** ******************************/ AttributeDictionary::AttributeDictionary(): Entity(SU_INVALID), m_dict(SU_INVALID) {} AttributeDictionary::AttributeDictionary(std::string name): AttributeDictionary(create_attribute_dictionary(name), false) {} AttributeDictionary::AttributeDictionary(SUAttributeDictionaryRef dict_ref, bool attached): Entity(SUAttributeDictionaryToEntity(dict_ref), attached), m_dict(dict_ref) {} /** Copy constructor */ AttributeDictionary::AttributeDictionary(const AttributeDictionary& other): Entity(other, SUAttributeDictionaryToEntity(copy_reference(other))), m_dict(SUAttributeDictionaryFromEntity(m_entity)) { if (!other.m_attached && SUIsValid(other.m_dict)) { // Create a copy of the keys and values std::vector<std::string> keys = other.get_keys(); for (size_t i=0; i < keys.size(); i++) { this->set_attribute(keys[i], other.get_value(keys[i])); } } } AttributeDictionary::~AttributeDictionary() { if (SU_VERSION_MAJOR >= 18) { if (!m_attached && SUIsValid(m_dict)) { SUResult res = SUAttributeDictionaryRelease(&m_dict); assert(res == SU_ERROR_NONE); } } } /****************** * Public Methods ** *******************/ /** Copy assignment operator */ AttributeDictionary& AttributeDictionary::operator=(const AttributeDictionary& other) { if (SU_VERSION_MAJOR >= 18 && !m_attached && SUIsValid(m_dict)) { SUResult res = SUAttributeDictionaryRelease(&m_dict); assert(res == SU_ERROR_NONE); } m_dict = copy_reference(other); m_entity = SUAttributeDictionaryToEntity(m_dict); Entity::operator=(other); return *this; } SUAttributeDictionaryRef AttributeDictionary::ref() const { return m_dict; } AttributeDictionary::operator SUAttributeDictionaryRef() const { return m_dict; } AttributeDictionary::operator SUAttributeDictionaryRef*() { return &m_dict; } TypedValue AttributeDictionary::get_attribute(const std::string &key, const TypedValue &default_value) const { if (!(*this)) { throw std::logic_error("CW::AttributeDictionary::get_attribute(): AttributeDictionary is null"); } TypedValue value_out; SUTypedValueRef *val = value_out; const char* key_char = key.c_str(); SUResult res = SUAttributeDictionaryGetValue(m_dict, &key_char[0], val); if (res == SU_ERROR_NO_DATA) { return default_value; } if (res != SU_ERROR_NONE) { assert(false); //throw std::logic_error("CW::AttributeDictionary::get_attribute(): index range is between 0 and 15"); } return value_out; } bool AttributeDictionary::set_attribute(const std::string &key, const TypedValue &value) { if (!(*this)) { throw std::logic_error("CW::AttributeDictionary::set_attribute(): AttributeDictionary is null"); } SUTypedValueRef val = value.ref(); const char* key_char = key.c_str(); SUResult res = SUAttributeDictionarySetValue(m_dict, &key_char[0], val); if (res == SU_ERROR_NONE) { return true; } else { return false; } } std::vector<std::string> AttributeDictionary::get_keys() const { if (!(*this)) { throw std::logic_error("CW::AttributeDictionary::get_keys(): AttributeDictionary is null"); } size_t num_keys = 0; SUResult res = SUAttributeDictionaryGetNumKeys(m_dict, &num_keys); assert(res == SU_ERROR_NONE); std::vector<SUStringRef> keys_ref(num_keys, SU_INVALID); //for (size_t i=0; i < num_keys; i++) { // SUStringCreate(&keys_ref[i]); //} SUAttributeDictionaryGetKeys(m_dict, num_keys, keys_ref.data(), &num_keys); std::vector<std::string> keys(num_keys); std::transform(keys_ref.begin(), keys_ref.end(), keys.begin(), [](const SUStringRef& value) { return String(value).std_string(); }); return keys; } TypedValue AttributeDictionary::get_value(const std::string &key) const { return get_attribute(key, TypedValue()); } std::string AttributeDictionary::get_name() const { String string; SUStringRef *string_ref = string; SUResult res = SUAttributeDictionaryGetName(m_dict, string_ref); assert(res == SU_ERROR_NONE); return string; } bool AttributeDictionary::operator !() const { if (SUIsValid(m_dict)) { return false; } return true; } } /* namespace CW */
// // AttributeDictionary.cpp // // Sketchup C++ Wrapper for C API // MIT License // // Copyright (c) 2017 Tom Kaneko // // 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 <cassert> #include <stdexcept> #include <algorithm> #include "SUAPI-CppWrapper/model/AttributeDictionary.hpp" #include "SUAPI-CppWrapper/model/TypedValue.hpp" #include "SUAPI-CppWrapper/String.hpp" namespace CW { extern size_t SU_VERSION_MAJOR; /****************** * Private Static methods *******************/ SUAttributeDictionaryRef AttributeDictionary::create_attribute_dictionary(const std::string& name) { if (SU_VERSION_MAJOR < 18) { throw std::logic_error("AttributeDictionary::create_attribute_dictionary(): Cannot use function prior to SU version 2018"); } SUAttributeDictionaryRef dict = SU_INVALID; SUResult res = SUAttributeDictionaryCreate(&dict, name.c_str()); assert(res == SU_ERROR_NONE); return dict; } SUAttributeDictionaryRef AttributeDictionary::copy_reference(const AttributeDictionary& other) { if (SU_VERSION_MAJOR < 18) { throw std::logic_error("AttributeDictionary::create_attribute_dictionary(): Cannot use function prior to SU version 2018"); } if (other.m_attached || !other) { return other.m_dict; } // The other Attributedictionary has not been attached to the model, so copy its properties to a new object SUAttributeDictionaryRef new_dict = create_attribute_dictionary(other.get_name()); return new_dict; } /***************************** * Constructor / Destructors ** ******************************/ AttributeDictionary::AttributeDictionary(): Entity(SU_INVALID), m_dict(SU_INVALID) {} AttributeDictionary::AttributeDictionary(std::string name): AttributeDictionary(create_attribute_dictionary(name), false) {} AttributeDictionary::AttributeDictionary(SUAttributeDictionaryRef dict_ref, bool attached): Entity(SUAttributeDictionaryToEntity(dict_ref), attached), m_dict(dict_ref) {} /** Copy constructor */ AttributeDictionary::AttributeDictionary(const AttributeDictionary& other): Entity(other, SUAttributeDictionaryToEntity(copy_reference(other))), m_dict(SUAttributeDictionaryFromEntity(m_entity)) { if (!other.m_attached && SUIsValid(other.m_dict)) { // Create a copy of the keys and values std::vector<std::string> keys = other.get_keys(); for (size_t i=0; i < keys.size(); i++) { this->set_attribute(keys[i], other.get_value(keys[i])); } } } AttributeDictionary::~AttributeDictionary() { if (SU_VERSION_MAJOR >= 18) { if (!m_attached && SUIsValid(m_dict)) { SUResult res = SUAttributeDictionaryRelease(&m_dict); assert(res == SU_ERROR_NONE); } } } /****************** * Public Methods ** *******************/ /** Copy assignment operator */ AttributeDictionary& AttributeDictionary::operator=(const AttributeDictionary& other) { if (SU_VERSION_MAJOR >= 18 && !m_attached && SUIsValid(m_dict)) { SUResult res = SUAttributeDictionaryRelease(&m_dict); assert(res == SU_ERROR_NONE); } m_dict = copy_reference(other); m_entity = SUAttributeDictionaryToEntity(m_dict); Entity::operator=(other); return *this; } SUAttributeDictionaryRef AttributeDictionary::ref() const { return m_dict; } AttributeDictionary::operator SUAttributeDictionaryRef() const { return m_dict; } AttributeDictionary::operator SUAttributeDictionaryRef*() { return &m_dict; } TypedValue AttributeDictionary::get_attribute(const std::string &key, const TypedValue &default_value) const { if (!(*this)) { throw std::logic_error("CW::AttributeDictionary::get_attribute(): AttributeDictionary is null"); } TypedValue value_out; SUTypedValueRef *val = value_out; const char* key_char = key.c_str(); SUResult res = SUAttributeDictionaryGetValue(m_dict, &key_char[0], val); if (res == SU_ERROR_NO_DATA) { return default_value; } if (res != SU_ERROR_NONE) { assert(false); //throw std::logic_error("CW::AttributeDictionary::get_attribute(): index range is between 0 and 15"); } return value_out; } bool AttributeDictionary::set_attribute(const std::string &key, const TypedValue &value) { if (!(*this)) { throw std::logic_error("CW::AttributeDictionary::set_attribute(): AttributeDictionary is null"); } SUTypedValueRef val = value.ref(); const char* key_char = key.c_str(); SUResult res = SUAttributeDictionarySetValue(m_dict, &key_char[0], val); if (res == SU_ERROR_NONE) { return true; } else { return false; } } std::vector<std::string> AttributeDictionary::get_keys() const { if (!(*this)) { throw std::logic_error("CW::AttributeDictionary::get_keys(): AttributeDictionary is null"); } size_t num_keys = 0; SUResult res = SUAttributeDictionaryGetNumKeys(m_dict, &num_keys); assert(res == SU_ERROR_NONE); std::vector<SUStringRef> keys_ref(num_keys, SU_INVALID); std::for_each(keys_ref.begin(), keys_ref.end(), [](SUStringRef& value) { SUResult res = SUStringCreate(&value); assert(res == SU_ERROR_NONE); }); res = SUAttributeDictionaryGetKeys(m_dict, num_keys, keys_ref.data(), &num_keys); assert(res == SU_ERROR_NONE); std::vector<std::string> keys(num_keys); std::transform(keys_ref.begin(), keys_ref.end(), keys.begin(), [](const SUStringRef& value) { return String(value).std_string(); }); return keys; } TypedValue AttributeDictionary::get_value(const std::string &key) const { return get_attribute(key, TypedValue()); } std::string AttributeDictionary::get_name() const { String string; SUStringRef *string_ref = string; SUResult res = SUAttributeDictionaryGetName(m_dict, string_ref); assert(res == SU_ERROR_NONE); return string; } bool AttributeDictionary::operator !() const { if (SUIsValid(m_dict)) { return false; } return true; } } /* namespace CW */
Put back SUStringCreate() to fix issue on https://github.com/TommyKaneko/Sketchup-API-C-Wrapper/commit/ffc704c243d8bba272c4064b46276227f5a27c0b#commitcomment-27730440
Put back SUStringCreate() to fix issue on https://github.com/TommyKaneko/Sketchup-API-C-Wrapper/commit/ffc704c243d8bba272c4064b46276227f5a27c0b#commitcomment-27730440
C++
mit
TommyKaneko/Sketchup-API-C-Wrapper,TommyKaneko/Sketchup-API-C-Wrapper
236f99e0a5edbff86a9768cd04e8e2331021a51c
src/application.qt.objectview/ObjectViewPlugin.cpp
src/application.qt.objectview/ObjectViewPlugin.cpp
#include "ObjectViewPlugin.h" #include <application.qt/PluginContainer.h> #include "ui_objectview.h" #include <application.qt/DataBinding.h> #include <core/StringTools.h> using namespace std; using namespace nspace; void ObjectViewPlugin::objectDoubleClicked(QListWidgetItem * qobject){ auto data= qobject->data(Qt::UserRole); void * value =data.value<void*>(); Object * object = static_cast<Object*>(value); _objectPropertyView->setCurrentObject(object); } void ObjectViewPlugin::install(PluginContainer & container){ PluginWindow * window = new PluginWindow(); QWidget * w = new QWidget(); _ui= new Ui_ObjectView(); _ui->setupUi(w); _objectPropertyView = new ObjectPropertyView(); QGridLayout * gridLayout = _ui->gridLayout; QSplitter * splitter = _ui->splitter; auto binding = new LineEditDataBinding(); binding->setSource(this); binding->setTarget(_ui->searchTextBox); binding->setPropertyName("SearchString"); //gridLayout->addWidget(_objectPropertyView,0,1,2,1); splitter->addWidget(_objectPropertyView); connect(_ui->listWidget, SIGNAL(itemDoubleClicked(QListWidgetItem *)),this, SLOT(objectDoubleClicked(QListWidgetItem*))); window->setWidget(w); container.setPluginWindow(window); container.toggleWindow(true); } void ObjectViewPlugin::itemAdded(Object * , Objects){ } void ObjectViewPlugin::itemRemoved(Object * , Objects){ } void ObjectViewPlugin::onPropertyChanged(const std::string &name){ if(name!="SearchString"){return;} updateObjectList(); } void ObjectViewPlugin::updateListView(){ if(_ui)_ui->listWidget->clear(); Objects().foreachElement([this](Object * object){ string n = nspace::name(object); QListWidgetItem * item=new QListWidgetItem(tr(n.c_str())); QVariant variant = QVariant::fromValue<void*>(object); item->setData(Qt::UserRole,variant); if(_ui)_ui->listWidget->addItem(item); }); } void ObjectViewPlugin::updateObjectList(){ auto search = getSearchString(); if(search==""){ Objects()=*this; }else{ Objects()=subset([&search](Object * object){ return nspace::stringtools::containsIgnoreCase(nspace::name(object),search); }); } updateListView(); }
#include "ObjectViewPlugin.h" #include <application.qt/PluginContainer.h> #include "ui_objectview.h" #include <application.qt/DataBinding.h> #include <core/StringTools.h> using namespace std; using namespace nspace; void ObjectViewPlugin::objectDoubleClicked(QListWidgetItem * qobject){ auto data= qobject->data(Qt::UserRole); void * value =data.value<void*>(); Object * object = static_cast<Object*>(value); _objectPropertyView->setCurrentObject(object); } void ObjectViewPlugin::install(PluginContainer & container){ PluginWindow * window = new PluginWindow(); window->setWindowTitle(tr("Object View")); QWidget * w = new QWidget(); _ui= new Ui_ObjectView(); _ui->setupUi(w); _objectPropertyView = new ObjectPropertyView(); QGridLayout * gridLayout = _ui->gridLayout; QSplitter * splitter = _ui->splitter; auto binding = new LineEditDataBinding(); binding->setSource(this); binding->setTarget(_ui->searchTextBox); binding->setPropertyName("SearchString"); //gridLayout->addWidget(_objectPropertyView,0,1,2,1); splitter->addWidget(_objectPropertyView); connect(_ui->listWidget, SIGNAL(itemDoubleClicked(QListWidgetItem *)),this, SLOT(objectDoubleClicked(QListWidgetItem*))); window->setWidget(w); container.setPluginWindow(window); container.toggleWindow(true); } void ObjectViewPlugin::itemAdded(Object * , Objects){ } void ObjectViewPlugin::itemRemoved(Object * , Objects){ } void ObjectViewPlugin::onPropertyChanged(const std::string &name){ if(name!="SearchString"){return;} updateObjectList(); } void ObjectViewPlugin::updateListView(){ if(_ui)_ui->listWidget->clear(); Objects().foreachElement([this](Object * object){ string n = nspace::name(object); QListWidgetItem * item=new QListWidgetItem(tr(n.c_str())); QVariant variant = QVariant::fromValue<void*>(object); item->setData(Qt::UserRole,variant); if(_ui)_ui->listWidget->addItem(item); }); } void ObjectViewPlugin::updateObjectList(){ auto search = getSearchString(); if(search==""){ Objects()=*this; }else{ Objects()=subset([&search](Object * object){ return nspace::stringtools::containsIgnoreCase(nspace::name(object),search); }); } updateListView(); }
set name of plugin window
set name of plugin window git-svn-id: df10b4d4b9a50ecd05a5547a4432f768b32f36aa@466 c65b9dfa-2e9b-4d30-9b60-b5bbc3021b56
C++
mit
toeb/sine,toeb/sine,toeb/sine,toeb/sine
c677e00d7c85d1fe0131f5b20af3a32c4567c43a
src/application/interface/analog/Potentiometer.cpp
src/application/interface/analog/Potentiometer.cpp
/* Copyright 2015-2019 Igor Petrovic 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 "Analog.h" #include "core/src/general/Misc.h" #include "interface/CInfo.h" void Analog::checkPotentiometerValue(analogType_t analogType, uint8_t analogID, uint32_t value) { uint16_t maxLimit; uint16_t stepDiff; if ((analogType == aType_NRPN_14) || (analogType == aType_PitchBend)) { maxLimit = MIDI_14_BIT_VALUE_MAX; stepDiff = ANALOG_STEP_MIN_DIFF_14_BIT; } else { maxLimit = MIDI_7_BIT_VALUE_MAX; stepDiff = ANALOG_STEP_MIN_DIFF_7_BIT; } //if the first read value is 0, mark it as increasing since the lastAnalogueValue is initialized to value 0 for all pots potDirection_t direction = value >= lastAnalogueValue[analogID] ? potDirection_t::increasing : potDirection_t::decreasing; if (lastDirection[analogID] != potDirection_t::initial) { //don't perform these checks on initial value readout //when potentiometer changes direction, use double step difference to avoid jumping of values if (direction != lastDirection[analogID]) stepDiff *= 2; if (abs(static_cast<uint16_t>(value) - lastAnalogueValue[analogID]) < stepDiff) return; } auto midiValue = mapRange(value, static_cast<uint32_t>(ADC_MIN_VALUE), static_cast<uint32_t>(ADC_MAX_VALUE), static_cast<uint32_t>(0), static_cast<uint32_t>(maxLimit)); auto oldMIDIvalue = mapRange(static_cast<uint32_t>(lastAnalogueValue[analogID]), static_cast<uint32_t>(ADC_MIN_VALUE), static_cast<uint32_t>(ADC_MAX_VALUE), static_cast<uint32_t>(0), static_cast<uint32_t>(maxLimit)); //this will allow value 0 as the first sent value if ((midiValue == oldMIDIvalue) && (lastDirection[analogID] != potDirection_t::initial)) return; lastDirection[analogID] = direction; uint16_t lowerLimit = database.read(DB_BLOCK_ANALOG, dbSection_analog_lowerLimit, analogID); uint16_t upperLimit = database.read(DB_BLOCK_ANALOG, dbSection_analog_upperLimit, analogID); uint16_t midiID = database.read(DB_BLOCK_ANALOG, dbSection_analog_midiID, analogID); uint8_t channel = database.read(DB_BLOCK_ANALOG, dbSection_analog_midiChannel, analogID); encDec_14bit_t encDec_14bit; if ( (analogType == aType_potentiometer_cc) || (analogType == aType_potentiometer_note) || (analogType == aType_NRPN_7) ) { //use 7-bit MIDI ID and limits encDec_14bit.value = midiID; encDec_14bit.split14bit(); midiID = encDec_14bit.low; encDec_14bit.value = lowerLimit; encDec_14bit.split14bit(); lowerLimit = encDec_14bit.low; encDec_14bit.value = upperLimit; encDec_14bit.split14bit(); upperLimit = encDec_14bit.low; } // else // { // //14-bit values are already read // } auto scaledMIDIvalue = mapRange(midiValue, static_cast<uint32_t>(0), static_cast<uint32_t>(maxLimit), static_cast<uint32_t>(lowerLimit), static_cast<uint32_t>(upperLimit)); //invert MIDI data if configured if (database.read(DB_BLOCK_ANALOG, dbSection_analog_invert, analogID)) scaledMIDIvalue = maxLimit - scaledMIDIvalue; switch(analogType) { case aType_potentiometer_cc: case aType_potentiometer_note: if (analogType == aType_potentiometer_cc) { midi.sendControlChange(midiID, scaledMIDIvalue, channel); #ifdef DISPLAY_SUPPORTED display.displayMIDIevent(displayEventOut, midiMessageControlChange_display, midiID, scaledMIDIvalue, channel+1); #endif } else { midi.sendNoteOn(midiID, scaledMIDIvalue, channel); #ifdef DISPLAY_SUPPORTED display.displayMIDIevent(displayEventOut, midiMessageNoteOn_display, midiID, scaledMIDIvalue, channel+1); #endif } break; case aType_NRPN_7: case aType_NRPN_14: //when nrpn is used, MIDI ID is split into two messages //first message contains higher byte encDec_14bit.value = midiID; encDec_14bit.split14bit(); midi.sendControlChange(99, encDec_14bit.high, channel); midi.sendControlChange(98, encDec_14bit.low, channel); if (analogType == aType_NRPN_7) { midi.sendControlChange(6, scaledMIDIvalue, channel); } else { //send 14-bit NRPN value in another two messages //first message contains higher byte encDec_14bit.value = scaledMIDIvalue; encDec_14bit.split14bit(); midi.sendControlChange(6, encDec_14bit.high, channel); midi.sendControlChange(38, encDec_14bit.low, channel); } #ifdef DISPLAY_SUPPORTED display.displayMIDIevent(displayEventOut, midiMessageNRPN_display, midiID, scaledMIDIvalue, channel+1); #endif break; case aType_PitchBend: midi.sendPitchBend(scaledMIDIvalue, channel); #ifdef DISPLAY_SUPPORTED display.displayMIDIevent(displayEventOut, midiMessagePitchBend_display, midiID, scaledMIDIvalue, channel+1); #endif break; default: return; } if (cinfoHandler != nullptr) (*cinfoHandler)(DB_BLOCK_ANALOG, analogID); //update values lastAnalogueValue[analogID] = value; }
/* Copyright 2015-2019 Igor Petrovic 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 "Analog.h" #include "core/src/general/Misc.h" #include "interface/CInfo.h" void Analog::checkPotentiometerValue(analogType_t analogType, uint8_t analogID, uint32_t value) { uint16_t maxLimit; uint16_t stepDiff; if ((analogType == aType_NRPN_14) || (analogType == aType_PitchBend)) { maxLimit = MIDI_14_BIT_VALUE_MAX; stepDiff = ANALOG_STEP_MIN_DIFF_14_BIT; } else { maxLimit = MIDI_7_BIT_VALUE_MAX; stepDiff = ANALOG_STEP_MIN_DIFF_7_BIT; } //if the first read value is 0, mark it as increasing since the lastAnalogueValue is initialized to value 0 for all pots potDirection_t direction = value >= lastAnalogueValue[analogID] ? potDirection_t::increasing : potDirection_t::decreasing; //don't perform these checks on initial value readout if (lastDirection[analogID] != potDirection_t::initial) { //when potentiometer changes direction, use double step difference to avoid jumping of values //but only in 14bit mode if (direction != lastDirection[analogID]) { if ((analogType == aType_NRPN_14) || (analogType == aType_PitchBend)) stepDiff *= 2; } if (abs(static_cast<uint16_t>(value) - lastAnalogueValue[analogID]) < stepDiff) return; } auto midiValue = mapRange(value, static_cast<uint32_t>(ADC_MIN_VALUE), static_cast<uint32_t>(ADC_MAX_VALUE), static_cast<uint32_t>(0), static_cast<uint32_t>(maxLimit)); auto oldMIDIvalue = mapRange(static_cast<uint32_t>(lastAnalogueValue[analogID]), static_cast<uint32_t>(ADC_MIN_VALUE), static_cast<uint32_t>(ADC_MAX_VALUE), static_cast<uint32_t>(0), static_cast<uint32_t>(maxLimit)); //this will allow value 0 as the first sent value if ((midiValue == oldMIDIvalue) && (lastDirection[analogID] != potDirection_t::initial)) return; lastDirection[analogID] = direction; uint16_t lowerLimit = database.read(DB_BLOCK_ANALOG, dbSection_analog_lowerLimit, analogID); uint16_t upperLimit = database.read(DB_BLOCK_ANALOG, dbSection_analog_upperLimit, analogID); uint16_t midiID = database.read(DB_BLOCK_ANALOG, dbSection_analog_midiID, analogID); uint8_t channel = database.read(DB_BLOCK_ANALOG, dbSection_analog_midiChannel, analogID); encDec_14bit_t encDec_14bit; if ( (analogType == aType_potentiometer_cc) || (analogType == aType_potentiometer_note) || (analogType == aType_NRPN_7) ) { //use 7-bit MIDI ID and limits encDec_14bit.value = midiID; encDec_14bit.split14bit(); midiID = encDec_14bit.low; encDec_14bit.value = lowerLimit; encDec_14bit.split14bit(); lowerLimit = encDec_14bit.low; encDec_14bit.value = upperLimit; encDec_14bit.split14bit(); upperLimit = encDec_14bit.low; } // else // { // //14-bit values are already read // } auto scaledMIDIvalue = mapRange(midiValue, static_cast<uint32_t>(0), static_cast<uint32_t>(maxLimit), static_cast<uint32_t>(lowerLimit), static_cast<uint32_t>(upperLimit)); //invert MIDI data if configured if (database.read(DB_BLOCK_ANALOG, dbSection_analog_invert, analogID)) scaledMIDIvalue = maxLimit - scaledMIDIvalue; switch(analogType) { case aType_potentiometer_cc: case aType_potentiometer_note: if (analogType == aType_potentiometer_cc) { midi.sendControlChange(midiID, scaledMIDIvalue, channel); #ifdef DISPLAY_SUPPORTED display.displayMIDIevent(displayEventOut, midiMessageControlChange_display, midiID, scaledMIDIvalue, channel+1); #endif } else { midi.sendNoteOn(midiID, scaledMIDIvalue, channel); #ifdef DISPLAY_SUPPORTED display.displayMIDIevent(displayEventOut, midiMessageNoteOn_display, midiID, scaledMIDIvalue, channel+1); #endif } break; case aType_NRPN_7: case aType_NRPN_14: //when nrpn is used, MIDI ID is split into two messages //first message contains higher byte encDec_14bit.value = midiID; encDec_14bit.split14bit(); midi.sendControlChange(99, encDec_14bit.high, channel); midi.sendControlChange(98, encDec_14bit.low, channel); if (analogType == aType_NRPN_7) { midi.sendControlChange(6, scaledMIDIvalue, channel); } else { //send 14-bit NRPN value in another two messages //first message contains higher byte encDec_14bit.value = scaledMIDIvalue; encDec_14bit.split14bit(); midi.sendControlChange(6, encDec_14bit.high, channel); midi.sendControlChange(38, encDec_14bit.low, channel); } #ifdef DISPLAY_SUPPORTED display.displayMIDIevent(displayEventOut, midiMessageNRPN_display, midiID, scaledMIDIvalue, channel+1); #endif break; case aType_PitchBend: midi.sendPitchBend(scaledMIDIvalue, channel); #ifdef DISPLAY_SUPPORTED display.displayMIDIevent(displayEventOut, midiMessagePitchBend_display, midiID, scaledMIDIvalue, channel+1); #endif break; default: return; } if (cinfoHandler != nullptr) (*cinfoHandler)(DB_BLOCK_ANALOG, analogID); //update values lastAnalogueValue[analogID] = value; }
use double raw adc value diff requirement only in 14bit mode
use double raw adc value diff requirement only in 14bit mode
C++
apache-2.0
paradajz/OpenDeck,paradajz/OpenDeck,paradajz/OpenDeck,paradajz/OpenDeck,paradajz/OpenDeck,paradajz/OpenDeck
b3e0c67998c9460ebd1d371dc0065e85c8a1763b
bench/bench_gemm.cpp
bench/bench_gemm.cpp
// g++-4.4 bench_gemm.cpp -I .. -O2 -DNDEBUG -lrt -fopenmp && OMP_NUM_THREADS=2 ./a.out // icpc bench_gemm.cpp -I .. -O3 -DNDEBUG -lrt -openmp && OMP_NUM_THREADS=2 ./a.out #include <Eigen/Core> #include <iostream> #include <bench/BenchTimer.h> using namespace std; using namespace Eigen; #ifndef SCALAR #define SCALAR float #endif typedef SCALAR Scalar; typedef Matrix<Scalar,Dynamic,Dynamic> M; #ifdef HAVE_BLAS extern "C" { #include <bench/btl/libs/C_BLAS/blas.h> } static float fone = 1; static float fzero = 0; static double done = 1; static double szero = 0; static char notrans = 'N'; static char trans = 'T'; static char nonunit = 'N'; static char lower = 'L'; static char right = 'R'; static int intone = 1; void blas_gemm(const MatrixXf& a, const MatrixXf& b, MatrixXf& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); sgemm_(&notrans,&notrans,&M,&N,&K,&fone, const_cast<float*>(a.data()),&lda, const_cast<float*>(b.data()),&ldb,&fone, c.data(),&ldc); } void blas_gemm(const MatrixXd& a, const MatrixXd& b, MatrixXd& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); dgemm_(&notrans,&notrans,&M,&N,&K,&done, const_cast<double*>(a.data()),&lda, const_cast<double*>(b.data()),&ldb,&done, c.data(),&ldc); } #endif void gemm(const M& a, const M& b, M& c) { c.noalias() += a * b; } int main(int argc, char ** argv) { int rep = 1; // number of repetitions per try int tries = 5; // number of tries, we keep the best int s = argc==2 ? std::atoi(argv[1]) : 2048; std::cout << "Matrix size = " << s << "\n"; int m = s; int n = s; int p = s; M a(m,n); a.setRandom(); M b(n,p); b.setRandom(); M c(m,p); c.setOnes(); M r = c; // check the parallel product is correct #ifdef EIGEN_HAS_OPENMP int procs = omp_get_max_threads(); if(procs>1) { #ifdef HAVE_BLAS blas_gemm(a,b,r); #else omp_set_num_threads(1); r.noalias() += a * b; omp_set_num_threads(procs); #endif c.noalias() += a * b; if(!r.isApprox(c)) std::cerr << "Warning, your parallel product is crap!\n\n"; } #endif #ifdef HAVE_BLAS BenchTimer tblas; BENCH(tblas, tries, rep, blas_gemm(a,b,c)); std::cout << "blas cpu " << tblas.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tblas.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tblas.total(CPU_TIMER) << "s)\n"; std::cout << "blas real " << tblas.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tblas.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tblas.total(REAL_TIMER) << "s)\n"; #endif BenchTimer tmt; BENCH(tmt, tries, rep, gemm(a,b,c)); std::cout << "eigen cpu " << tmt.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmt.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tmt.total(CPU_TIMER) << "s)\n"; std::cout << "eigen real " << tmt.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmt.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tmt.total(REAL_TIMER) << "s)\n"; #ifdef EIGEN_HAS_OPENMP if(procs>1) { BenchTimer tmono; //omp_set_num_threads(1); Eigen::setNbThreads(1); BENCH(tmono, tries, rep, gemm(a,b,c)); std::cout << "eigen mono cpu " << tmono.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmono.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tmono.total(CPU_TIMER) << "s)\n"; std::cout << "eigen mono real " << tmono.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmono.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tmono.total(REAL_TIMER) << "s)\n"; std::cout << "mt speed up x" << tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER) << " => " << (100.0*tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER))/procs << "%\n"; } #endif return 0; }
// g++-4.4 bench_gemm.cpp -I .. -O2 -DNDEBUG -lrt -fopenmp && OMP_NUM_THREADS=2 ./a.out // icpc bench_gemm.cpp -I .. -O3 -DNDEBUG -lrt -openmp && OMP_NUM_THREADS=2 ./a.out #include <Eigen/Core> #include <iostream> #include <bench/BenchTimer.h> using namespace std; using namespace Eigen; #ifndef SCALAR #define SCALAR float #endif typedef SCALAR Scalar; typedef Matrix<Scalar,Dynamic,Dynamic> M; #ifdef HAVE_BLAS extern "C" { #include <bench/btl/libs/C_BLAS/blas.h> } static float fone = 1; static float fzero = 0; static double done = 1; static double szero = 0; static char notrans = 'N'; static char trans = 'T'; static char nonunit = 'N'; static char lower = 'L'; static char right = 'R'; static int intone = 1; void blas_gemm(const MatrixXf& a, const MatrixXf& b, MatrixXf& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); sgemm_(&notrans,&notrans,&M,&N,&K,&fone, const_cast<float*>(a.data()),&lda, const_cast<float*>(b.data()),&ldb,&fone, c.data(),&ldc); } void blas_gemm(const MatrixXd& a, const MatrixXd& b, MatrixXd& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); dgemm_(&notrans,&notrans,&M,&N,&K,&done, const_cast<double*>(a.data()),&lda, const_cast<double*>(b.data()),&ldb,&done, c.data(),&ldc); } #endif void gemm(const M& a, const M& b, M& c) { c.noalias() += a * b; } int main(int argc, char ** argv) { int rep = 1; // number of repetitions per try int tries = 5; // number of tries, we keep the best int s = 2048; int cache_size = -1; bool need_help = false; for (int i=1; i<argc; ++i) { if(argv[i][0]=='s') s = atoi(argv[i]+1); else if(argv[i][0]=='c') cache_size = atoi(argv[i]+1); else need_help = true; } if(need_help) { std::cout << argv[0] << " s<matrix size> c<cache size> \n"; return 1; } if(cache_size>0) setCpuCacheSizes(cache_size,32*cache_size); std::cout << "Matrix size = " << s << "\n"; std::ptrdiff_t cm, cn, ck; getBlockingSizes<Scalar>(ck, cm, cn); std::cout << "blocking size = " << cm << " x " << ck << "\n"; int m = s; int n = s; int p = s; M a(m,n); a.setRandom(); M b(n,p); b.setRandom(); M c(m,p); c.setOnes(); M r = c; // check the parallel product is correct #ifdef EIGEN_HAS_OPENMP int procs = omp_get_max_threads(); if(procs>1) { #ifdef HAVE_BLAS blas_gemm(a,b,r); #else omp_set_num_threads(1); r.noalias() += a * b; omp_set_num_threads(procs); #endif c.noalias() += a * b; if(!r.isApprox(c)) std::cerr << "Warning, your parallel product is crap!\n\n"; } #endif #ifdef HAVE_BLAS BenchTimer tblas; BENCH(tblas, tries, rep, blas_gemm(a,b,c)); std::cout << "blas cpu " << tblas.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tblas.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tblas.total(CPU_TIMER) << "s)\n"; std::cout << "blas real " << tblas.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tblas.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tblas.total(REAL_TIMER) << "s)\n"; #endif BenchTimer tmt; BENCH(tmt, tries, rep, gemm(a,b,c)); std::cout << "eigen cpu " << tmt.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmt.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tmt.total(CPU_TIMER) << "s)\n"; std::cout << "eigen real " << tmt.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmt.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tmt.total(REAL_TIMER) << "s)\n"; #ifdef EIGEN_HAS_OPENMP if(procs>1) { BenchTimer tmono; //omp_set_num_threads(1); Eigen::setNbThreads(1); BENCH(tmono, tries, rep, gemm(a,b,c)); std::cout << "eigen mono cpu " << tmono.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmono.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tmono.total(CPU_TIMER) << "s)\n"; std::cout << "eigen mono real " << tmono.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmono.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tmono.total(REAL_TIMER) << "s)\n"; std::cout << "mt speed up x" << tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER) << " => " << (100.0*tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER))/procs << "%\n"; } #endif return 0; }
add the possibility to set the cache size at runtime
add the possibility to set the cache size at runtime
C++
bsd-3-clause
robustrobotics/eigen,robustrobotics/eigen,robustrobotics/eigen,robustrobotics/eigen
1b90e950bd3d679effca0343c5aa0db690bfbba1
lib/Runtime/PlatformAgnostic/Platform/Common/HiResTimer.cpp
lib/Runtime/PlatformAgnostic/Platform/Common/HiResTimer.cpp
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "Common.h" #include <time.h> #include <sys/time.h> #include "ChakraPlatform.h" namespace PlatformAgnostic { namespace DateTime { // This method is expected to return UTC time (See MSDN GetSystemTime) inline static double GetSystemTimeREAL() { #ifndef __APPLE__ struct timespec fast_time; // method below returns UTC time. So, nothing else is needed // we use clock_gettime first due to expectation of better accuracy if (clock_gettime(CLOCK_REALTIME, &fast_time) == 0) { return (fast_time.tv_sec * DateTimeTicks_PerSecond) + (int32_t) (fast_time.tv_nsec / 1e6); } #endif // in case of clock_gettime fails we use the implementation below struct tm utc_tm; struct timeval timeval; time_t time_now = time(NULL); // gettimeofday return value needs to be converted to UTC time // see call below for gmtime_r int timeofday_retval = gettimeofday(&timeval,NULL); if (gmtime_r(&time_now, &utc_tm) == NULL) { AssertMsg(false, "gmtime() failed"); } size_t milliseconds = 0; if(timeofday_retval != -1) { milliseconds = timeval.tv_usec / DateTimeTicks_PerSecond; int old_sec = utc_tm.tm_sec; int new_sec = timeval.tv_sec % 60; // C99 0-60 (1sec leap) // just in case we reached the next // second in the interval between time() and gettimeofday() if(old_sec != new_sec) { milliseconds = 999; } } milliseconds = (utc_tm.tm_hour * DateTimeTicks_PerHour) + (utc_tm.tm_min * DateTimeTicks_PerMinute) + (utc_tm.tm_sec * DateTimeTicks_PerSecond) + milliseconds; return Js::DateUtilities::TvFromDate(1900 + utc_tm.tm_year, utc_tm.tm_mon, utc_tm.tm_mday - 1, milliseconds); } // Important! When you update 5ms below to any other number, also update test/Date/xplatInterval.js 0->5 range #define INTERVAL_FOR_TICK_BACKUP 5 double HiResTimer::GetSystemTime() { ULONGLONG current = GetTickCount64(); ULONGLONG diff = current - data.cacheTick; if (diff <= data.previousDifference || diff >= INTERVAL_FOR_TICK_BACKUP) // max *ms to respond system time changes { double currentTime = GetSystemTimeREAL(); // in case the system time wasn't updated backwards, and cache is still beyond... if (currentTime >= data.cacheSysTime && currentTime < data.cacheSysTime + INTERVAL_FOR_TICK_BACKUP) { data.previousDifference = (ULONGLONG) -1; // Make sure next request won't use cache return data.cacheSysTime + INTERVAL_FOR_TICK_BACKUP; // wait for real time } data.previousDifference = 0; data.cacheSysTime = currentTime; data.cacheTick = current; return currentTime; } // tick count is circular. So, make sure tick wasn't cycled since the last request data.previousDifference = diff; return data.cacheSysTime + (double)diff; } #undef INTERVAL_FOR_TICK_BACKUP double HiResTimer::Now() { return GetSystemTime(); } } // namespace DateTime } // namespace PlatformAgnostic
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "Common.h" #include <time.h> #include <sys/time.h> #include "ChakraPlatform.h" namespace PlatformAgnostic { namespace DateTime { // This method is expected to return UTC time (See MSDN GetSystemTime) inline static double GetSystemTimeREAL() { #ifdef HAVE_WORKING_CLOCK_GETTIME struct timespec fast_time; // method below returns UTC time. So, nothing else is needed // we use clock_gettime first due to expectation of better accuracy if (clock_gettime(CLOCK_REALTIME, &fast_time) == 0) { return (fast_time.tv_sec * DateTimeTicks_PerSecond) + (int32_t) (fast_time.tv_nsec / 1e6); } #endif // in case of clock_gettime fails we use the implementation below struct tm utc_tm; struct timeval timeval; time_t time_now = time(NULL); // gettimeofday return value needs to be converted to UTC time // see call below for gmtime_r int timeofday_retval = gettimeofday(&timeval,NULL); if (gmtime_r(&time_now, &utc_tm) == NULL) { AssertMsg(false, "gmtime() failed"); } size_t milliseconds = 0; if(timeofday_retval != -1) { milliseconds = timeval.tv_usec / DateTimeTicks_PerSecond; int old_sec = utc_tm.tm_sec; int new_sec = timeval.tv_sec % 60; // C99 0-60 (1sec leap) // just in case we reached the next // second in the interval between time() and gettimeofday() if(old_sec != new_sec) { milliseconds = 999; } } milliseconds = (utc_tm.tm_hour * DateTimeTicks_PerHour) + (utc_tm.tm_min * DateTimeTicks_PerMinute) + (utc_tm.tm_sec * DateTimeTicks_PerSecond) + milliseconds; return Js::DateUtilities::TvFromDate(1900 + utc_tm.tm_year, utc_tm.tm_mon, utc_tm.tm_mday - 1, milliseconds); } // Important! When you update 5ms below to any other number, also update test/Date/xplatInterval.js 0->5 range #define INTERVAL_FOR_TICK_BACKUP 5 double HiResTimer::GetSystemTime() { ULONGLONG current = GetTickCount64(); ULONGLONG diff = current - data.cacheTick; if (diff <= data.previousDifference || diff >= INTERVAL_FOR_TICK_BACKUP) // max *ms to respond system time changes { double currentTime = GetSystemTimeREAL(); // in case the system time wasn't updated backwards, and cache is still beyond... if (currentTime >= data.cacheSysTime && currentTime < data.cacheSysTime + INTERVAL_FOR_TICK_BACKUP) { data.previousDifference = (ULONGLONG) -1; // Make sure next request won't use cache return data.cacheSysTime + INTERVAL_FOR_TICK_BACKUP; // wait for real time } data.previousDifference = 0; data.cacheSysTime = currentTime; data.cacheTick = current; return currentTime; } // tick count is circular. So, make sure tick wasn't cycled since the last request data.previousDifference = diff; return data.cacheSysTime + (double)diff; } #undef INTERVAL_FOR_TICK_BACKUP double HiResTimer::Now() { return GetSystemTime(); } } // namespace DateTime } // namespace PlatformAgnostic
use clock_gettime when it's available
osx: use clock_gettime when it's available Recent OSX distros have clock_gettime support. Use it when it's available (~3 times faster to what we do to replace that)
C++
mit
mrkmarron/ChakraCore,Microsoft/ChakraCore,mrkmarron/ChakraCore,Microsoft/ChakraCore,mrkmarron/ChakraCore,Microsoft/ChakraCore,mrkmarron/ChakraCore,Microsoft/ChakraCore,mrkmarron/ChakraCore,mrkmarron/ChakraCore,Microsoft/ChakraCore,Microsoft/ChakraCore,mrkmarron/ChakraCore
1d53aefe781709f4d1c551a82eb12c3bc1378568
src/trace_processor/trace_database_integrationtest.cc
src/trace_processor/trace_database_integrationtest.cc
/* * Copyright (C) 2018 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 <map> #include <random> #include <string> #include "gtest/gtest.h" #include "perfetto/base/logging.h" #include "perfetto/base/scoped_file.h" #include "perfetto/trace_processor/trace_processor.h" #include "src/base/test/utils.h" #include "src/trace_processor/json_trace_parser.h" namespace perfetto { namespace trace_processor { namespace { class TraceProcessorIntegrationTest : public ::testing::Test { public: TraceProcessorIntegrationTest() : processor_(TraceProcessor::CreateInstance(Config())) {} protected: bool LoadTrace(const char* name, int min_chunk_size = 1) { base::ScopedFstream f(fopen(base::GetTestDataPath(name).c_str(), "rb")); std::minstd_rand0 rnd_engine(0); std::uniform_int_distribution<> dist(min_chunk_size, 1024); while (!feof(*f)) { size_t chunk_size = static_cast<size_t>(dist(rnd_engine)); std::unique_ptr<uint8_t[]> buf(new uint8_t[chunk_size]); auto rsize = fread(reinterpret_cast<char*>(buf.get()), 1, chunk_size, *f); if (!processor_->Parse(std::move(buf), rsize)) return false; } processor_->NotifyEndOfFile(); return true; } TraceProcessor::Iterator Query(const std::string& query) { return processor_->ExecuteQuery(query.c_str()); } private: std::unique_ptr<TraceProcessor> processor_; }; TEST_F(TraceProcessorIntegrationTest, AndroidSchedAndPs) { ASSERT_TRUE(LoadTrace("android_sched_and_ps.pb")); auto it = Query( "select count(*), max(ts) - min(ts) from sched " "where dur != 0 and utid != 0"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 139787); ASSERT_EQ(it.Get(1).type, SqlValue::kLong); ASSERT_EQ(it.Get(1).long_value, 19684308497); ASSERT_FALSE(it.Next()); } TEST_F(TraceProcessorIntegrationTest, Sfgate) { ASSERT_TRUE(LoadTrace("sfgate.json", strlen("{\"traceEvents\":["))); auto it = Query("select count(*), max(ts) - min(ts) from slices where utid != 0"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 39828); ASSERT_EQ(it.Get(1).type, SqlValue::kLong); ASSERT_EQ(it.Get(1).long_value, 40532506000); ASSERT_FALSE(it.Next()); } TEST_F(TraceProcessorIntegrationTest, UnsortedTrace) { ASSERT_TRUE(LoadTrace("unsorted_trace.json", strlen("{\"traceEvents\":["))); auto it = Query("select ts, depth from slices order by ts"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 50000); ASSERT_EQ(it.Get(1).type, SqlValue::kLong); ASSERT_EQ(it.Get(1).long_value, 0); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 100000); ASSERT_EQ(it.Get(1).type, SqlValue::kLong); ASSERT_EQ(it.Get(1).long_value, 1); ASSERT_FALSE(it.Next()); } TEST_F(TraceProcessorIntegrationTest, TraceBounds) { ASSERT_TRUE(LoadTrace("android_sched_and_ps.pb")); auto it = Query("select start_ts, end_ts from trace_bounds"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 81473009948313); ASSERT_EQ(it.Get(1).type, SqlValue::kLong); ASSERT_EQ(it.Get(1).long_value, 81492700784311); ASSERT_FALSE(it.Next()); } // TODO(hjd): Add trace to test_data. TEST_F(TraceProcessorIntegrationTest, DISABLED_AndroidBuildTrace) { ASSERT_TRUE(LoadTrace("android_build_trace.json", strlen("[\n{"))); } } // namespace } // namespace trace_processor } // namespace perfetto
/* * Copyright (C) 2018 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 <map> #include <random> #include <string> #include "gtest/gtest.h" #include "perfetto/base/logging.h" #include "perfetto/base/scoped_file.h" #include "perfetto/trace_processor/trace_processor.h" #include "src/base/test/utils.h" #include "src/trace_processor/json_trace_parser.h" namespace perfetto { namespace trace_processor { namespace { class TraceProcessorIntegrationTest : public ::testing::Test { public: TraceProcessorIntegrationTest() : processor_(TraceProcessor::CreateInstance(Config())) {} protected: bool LoadTrace(const char* name, int min_chunk_size = 512) { base::ScopedFstream f(fopen(base::GetTestDataPath(name).c_str(), "rb")); std::minstd_rand0 rnd_engine(0); std::uniform_int_distribution<> dist(min_chunk_size, 1024); while (!feof(*f)) { size_t chunk_size = static_cast<size_t>(dist(rnd_engine)); std::unique_ptr<uint8_t[]> buf(new uint8_t[chunk_size]); auto rsize = fread(reinterpret_cast<char*>(buf.get()), 1, chunk_size, *f); if (!processor_->Parse(std::move(buf), rsize)) return false; } processor_->NotifyEndOfFile(); return true; } TraceProcessor::Iterator Query(const std::string& query) { return processor_->ExecuteQuery(query.c_str()); } private: std::unique_ptr<TraceProcessor> processor_; }; TEST_F(TraceProcessorIntegrationTest, AndroidSchedAndPs) { ASSERT_TRUE(LoadTrace("android_sched_and_ps.pb")); auto it = Query( "select count(*), max(ts) - min(ts) from sched " "where dur != 0 and utid != 0"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 139787); ASSERT_EQ(it.Get(1).type, SqlValue::kLong); ASSERT_EQ(it.Get(1).long_value, 19684308497); ASSERT_FALSE(it.Next()); } TEST_F(TraceProcessorIntegrationTest, Sfgate) { ASSERT_TRUE(LoadTrace("sfgate.json", strlen("{\"traceEvents\":["))); auto it = Query("select count(*), max(ts) - min(ts) from slices where utid != 0"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 39828); ASSERT_EQ(it.Get(1).type, SqlValue::kLong); ASSERT_EQ(it.Get(1).long_value, 40532506000); ASSERT_FALSE(it.Next()); } TEST_F(TraceProcessorIntegrationTest, UnsortedTrace) { ASSERT_TRUE(LoadTrace("unsorted_trace.json", strlen("{\"traceEvents\":["))); auto it = Query("select ts, depth from slices order by ts"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 50000); ASSERT_EQ(it.Get(1).type, SqlValue::kLong); ASSERT_EQ(it.Get(1).long_value, 0); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 100000); ASSERT_EQ(it.Get(1).type, SqlValue::kLong); ASSERT_EQ(it.Get(1).long_value, 1); ASSERT_FALSE(it.Next()); } TEST_F(TraceProcessorIntegrationTest, TraceBounds) { ASSERT_TRUE(LoadTrace("android_sched_and_ps.pb")); auto it = Query("select start_ts, end_ts from trace_bounds"); ASSERT_TRUE(it.Next()); ASSERT_EQ(it.Get(0).type, SqlValue::kLong); ASSERT_EQ(it.Get(0).long_value, 81473009948313); ASSERT_EQ(it.Get(1).type, SqlValue::kLong); ASSERT_EQ(it.Get(1).long_value, 81492700784311); ASSERT_FALSE(it.Next()); } // TODO(hjd): Add trace to test_data. TEST_F(TraceProcessorIntegrationTest, DISABLED_AndroidBuildTrace) { ASSERT_TRUE(LoadTrace("android_build_trace.json", strlen("[\n{"))); } } // namespace } // namespace trace_processor } // namespace perfetto
bump min chunk size in trace processor
trace_processor: bump min chunk size in trace processor We need to parse at least a full packet for trace processor's guessing code to work correctly. This fixes the integration tests passing on GCC. Change-Id: I07fc43802141d00518bcad5af5a7be2ae29e7c64
C++
apache-2.0
google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto
82549062c0a5e8809cd12e52c013b01df5bdb918
clangd/index/FileIndex.cpp
clangd/index/FileIndex.cpp
//===--- FileIndex.cpp - Indexes for files. ------------------------ C++-*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "FileIndex.h" #include "../Logger.h" #include "SymbolCollector.h" #include "clang/Index/IndexingAction.h" #include "clang/Lex/Preprocessor.h" namespace clang { namespace clangd { std::pair<SymbolSlab, SymbolOccurrenceSlab> indexAST(ASTContext &AST, std::shared_ptr<Preprocessor> PP, llvm::Optional<llvm::ArrayRef<Decl *>> TopLevelDecls, llvm::ArrayRef<std::string> URISchemes) { SymbolCollector::Options CollectorOpts; // FIXME(ioeric): we might also want to collect include headers. We would need // to make sure all includes are canonicalized (with CanonicalIncludes), which // is not trivial given the current way of collecting symbols: we only have // AST at this point, but we also need preprocessor callbacks (e.g. // CommentHandler for IWYU pragma) to canonicalize includes. CollectorOpts.CollectIncludePath = false; CollectorOpts.CountReferences = false; if (!URISchemes.empty()) CollectorOpts.URISchemes = URISchemes; CollectorOpts.Origin = SymbolOrigin::Dynamic; index::IndexingOptions IndexOpts; // We only need declarations, because we don't count references. IndexOpts.SystemSymbolFilter = index::IndexingOptions::SystemSymbolFilterKind::DeclarationsOnly; IndexOpts.IndexFunctionLocals = false; std::vector<Decl *> DeclsToIndex; if (TopLevelDecls) DeclsToIndex.assign(TopLevelDecls->begin(), TopLevelDecls->end()); else DeclsToIndex.assign(AST.getTranslationUnitDecl()->decls().begin(), AST.getTranslationUnitDecl()->decls().end()); // We only collect occurrences when indexing main AST. // FIXME: this is a hacky way to detect whether we are indexing preamble AST // or main AST, we should make it explicitly. bool IsIndexMainAST = TopLevelDecls.hasValue(); if (IsIndexMainAST) CollectorOpts.OccurrenceFilter = AllOccurrenceKinds; SymbolCollector Collector(std::move(CollectorOpts)); Collector.setPreprocessor(PP); index::indexTopLevelDecls(AST, DeclsToIndex, Collector, IndexOpts); const auto &SM = AST.getSourceManager(); const auto *MainFileEntry = SM.getFileEntryForID(SM.getMainFileID()); std::string FileName = MainFileEntry ? MainFileEntry->getName() : ""; auto Syms = Collector.takeSymbols(); auto Occurrences = Collector.takeOccurrences(); vlog("index {0}AST for {1}: \n" " symbol slab: {2} symbols, {3} bytes\n" " occurrence slab: {4} symbols, {5} bytes", IsIndexMainAST ? "Main" : "Preamble", FileName, Syms.size(), Syms.bytes(), Occurrences.size(), Occurrences.bytes()); return {std::move(Syms), std::move(Occurrences)}; } FileIndex::FileIndex(std::vector<std::string> URISchemes) : URISchemes(std::move(URISchemes)) { reset(FSymbols.buildMemIndex()); } void FileSymbols::update(PathRef Path, std::unique_ptr<SymbolSlab> Slab, std::unique_ptr<SymbolOccurrenceSlab> Occurrences) { std::lock_guard<std::mutex> Lock(Mutex); if (!Slab) FileToSlabs.erase(Path); else FileToSlabs[Path] = std::move(Slab); if (!Occurrences) FileToOccurrenceSlabs.erase(Path); else FileToOccurrenceSlabs[Path] = std::move(Occurrences); } std::unique_ptr<SymbolIndex> FileSymbols::buildMemIndex() { std::vector<std::shared_ptr<SymbolSlab>> Slabs; std::vector<std::shared_ptr<SymbolOccurrenceSlab>> OccurrenceSlabs; { std::lock_guard<std::mutex> Lock(Mutex); for (const auto &FileAndSlab : FileToSlabs) Slabs.push_back(FileAndSlab.second); for (const auto &FileAndOccurrenceSlab : FileToOccurrenceSlabs) OccurrenceSlabs.push_back(FileAndOccurrenceSlab.second); } std::vector<const Symbol *> AllSymbols; for (const auto &Slab : Slabs) for (const auto &Sym : *Slab) AllSymbols.push_back(&Sym); MemIndex::OccurrenceMap AllOccurrences; for (const auto &OccurrenceSlab : OccurrenceSlabs) for (const auto &Sym : *OccurrenceSlab) { auto &Entry = AllOccurrences[Sym.first]; for (const auto &Occ : Sym.second) Entry.push_back(&Occ); } // Index must keep the slabs alive. return llvm::make_unique<MemIndex>( llvm::make_pointee_range(AllSymbols), std::move(AllOccurrences), std::make_pair(std::move(Slabs), std::move(OccurrenceSlabs))); } void FileIndex::update(PathRef Path, ASTContext *AST, std::shared_ptr<Preprocessor> PP, llvm::Optional<llvm::ArrayRef<Decl *>> TopLevelDecls) { if (!AST) { FSymbols.update(Path, nullptr, nullptr); } else { assert(PP); auto Slab = llvm::make_unique<SymbolSlab>(); auto OccurrenceSlab = llvm::make_unique<SymbolOccurrenceSlab>(); auto IndexResults = indexAST(*AST, PP, TopLevelDecls, URISchemes); std::tie(*Slab, *OccurrenceSlab) = indexAST(*AST, PP, TopLevelDecls, URISchemes); FSymbols.update(Path, std::move(Slab), std::move(OccurrenceSlab)); } reset(FSymbols.buildMemIndex()); } } // namespace clangd } // namespace clang
//===--- FileIndex.cpp - Indexes for files. ------------------------ C++-*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "FileIndex.h" #include "../Logger.h" #include "SymbolCollector.h" #include "clang/Index/IndexingAction.h" #include "clang/Lex/Preprocessor.h" namespace clang { namespace clangd { std::pair<SymbolSlab, SymbolOccurrenceSlab> indexAST(ASTContext &AST, std::shared_ptr<Preprocessor> PP, llvm::Optional<llvm::ArrayRef<Decl *>> TopLevelDecls, llvm::ArrayRef<std::string> URISchemes) { SymbolCollector::Options CollectorOpts; // FIXME(ioeric): we might also want to collect include headers. We would need // to make sure all includes are canonicalized (with CanonicalIncludes), which // is not trivial given the current way of collecting symbols: we only have // AST at this point, but we also need preprocessor callbacks (e.g. // CommentHandler for IWYU pragma) to canonicalize includes. CollectorOpts.CollectIncludePath = false; CollectorOpts.CountReferences = false; if (!URISchemes.empty()) CollectorOpts.URISchemes = URISchemes; CollectorOpts.Origin = SymbolOrigin::Dynamic; index::IndexingOptions IndexOpts; // We only need declarations, because we don't count references. IndexOpts.SystemSymbolFilter = index::IndexingOptions::SystemSymbolFilterKind::DeclarationsOnly; IndexOpts.IndexFunctionLocals = false; std::vector<Decl *> DeclsToIndex; if (TopLevelDecls) DeclsToIndex.assign(TopLevelDecls->begin(), TopLevelDecls->end()); else DeclsToIndex.assign(AST.getTranslationUnitDecl()->decls().begin(), AST.getTranslationUnitDecl()->decls().end()); // We only collect occurrences when indexing main AST. // FIXME: this is a hacky way to detect whether we are indexing preamble AST // or main AST, we should make it explicitly. bool IsIndexMainAST = TopLevelDecls.hasValue(); if (IsIndexMainAST) CollectorOpts.OccurrenceFilter = AllOccurrenceKinds; SymbolCollector Collector(std::move(CollectorOpts)); Collector.setPreprocessor(PP); index::indexTopLevelDecls(AST, DeclsToIndex, Collector, IndexOpts); const auto &SM = AST.getSourceManager(); const auto *MainFileEntry = SM.getFileEntryForID(SM.getMainFileID()); std::string FileName = MainFileEntry ? MainFileEntry->getName() : ""; auto Syms = Collector.takeSymbols(); auto Occurrences = Collector.takeOccurrences(); vlog("index {0}AST for {1}: \n" " symbol slab: {2} symbols, {3} bytes\n" " occurrence slab: {4} symbols, {5} bytes", IsIndexMainAST ? "Main" : "Preamble", FileName, Syms.size(), Syms.bytes(), Occurrences.size(), Occurrences.bytes()); return {std::move(Syms), std::move(Occurrences)}; } FileIndex::FileIndex(std::vector<std::string> URISchemes) : URISchemes(std::move(URISchemes)) { reset(FSymbols.buildMemIndex()); } void FileSymbols::update(PathRef Path, std::unique_ptr<SymbolSlab> Slab, std::unique_ptr<SymbolOccurrenceSlab> Occurrences) { std::lock_guard<std::mutex> Lock(Mutex); if (!Slab) FileToSlabs.erase(Path); else FileToSlabs[Path] = std::move(Slab); if (!Occurrences) FileToOccurrenceSlabs.erase(Path); else FileToOccurrenceSlabs[Path] = std::move(Occurrences); } std::unique_ptr<SymbolIndex> FileSymbols::buildMemIndex() { std::vector<std::shared_ptr<SymbolSlab>> Slabs; std::vector<std::shared_ptr<SymbolOccurrenceSlab>> OccurrenceSlabs; { std::lock_guard<std::mutex> Lock(Mutex); for (const auto &FileAndSlab : FileToSlabs) Slabs.push_back(FileAndSlab.second); for (const auto &FileAndOccurrenceSlab : FileToOccurrenceSlabs) OccurrenceSlabs.push_back(FileAndOccurrenceSlab.second); } std::vector<const Symbol *> AllSymbols; for (const auto &Slab : Slabs) for (const auto &Sym : *Slab) AllSymbols.push_back(&Sym); MemIndex::OccurrenceMap AllOccurrences; for (const auto &OccurrenceSlab : OccurrenceSlabs) for (const auto &Sym : *OccurrenceSlab) { auto &Entry = AllOccurrences[Sym.first]; for (const auto &Occ : Sym.second) Entry.push_back(&Occ); } // Index must keep the slabs alive. return llvm::make_unique<MemIndex>( llvm::make_pointee_range(AllSymbols), std::move(AllOccurrences), std::make_pair(std::move(Slabs), std::move(OccurrenceSlabs))); } void FileIndex::update(PathRef Path, ASTContext *AST, std::shared_ptr<Preprocessor> PP, llvm::Optional<llvm::ArrayRef<Decl *>> TopLevelDecls) { if (!AST) { FSymbols.update(Path, nullptr, nullptr); } else { assert(PP); auto Slab = llvm::make_unique<SymbolSlab>(); auto OccurrenceSlab = llvm::make_unique<SymbolOccurrenceSlab>(); std::tie(*Slab, *OccurrenceSlab) = indexAST(*AST, PP, TopLevelDecls, URISchemes); FSymbols.update(Path, std::move(Slab), std::move(OccurrenceSlab)); } reset(FSymbols.buildMemIndex()); } } // namespace clangd } // namespace clang
Fix index-twice regression from r341242
[clangd] Fix index-twice regression from r341242 git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@341337 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra
17135310cf49b3523effed4e7f56af09661b5067
src/location/places/qplacesearchrequest.cpp
src/location/places/qplacesearchrequest.cpp
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtLocation module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** 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. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qplacesearchrequest.h" #include "qgeocoordinate.h" #include "qgeoboundingarea.h" #include <QtCore/QSharedData> #include <QtCore/QList> QT_BEGIN_NAMESPACE class QPlaceSearchRequestPrivate : public QSharedData { public: QPlaceSearchRequestPrivate(); QPlaceSearchRequestPrivate(const QPlaceSearchRequestPrivate &other); ~QPlaceSearchRequestPrivate(); QPlaceSearchRequestPrivate &operator=(const QPlaceSearchRequestPrivate &other); bool operator==(const QPlaceSearchRequestPrivate &other) const; void clear(); QString searchTerm; QList<QPlaceCategory> categories; QGeoBoundingArea *searchArea; int dymNumber; QtLocation::VisibilityScope visibilityScope; QPlaceSearchRequest::RelevanceHint relevanceHint; int limit; int offset; }; QPlaceSearchRequestPrivate::QPlaceSearchRequestPrivate() : QSharedData(), searchArea(0), dymNumber(0), visibilityScope(QtLocation::UnspecifiedVisibility), relevanceHint(QPlaceSearchRequest::UnspecifiedHint), limit(-1), offset(0) { } QPlaceSearchRequestPrivate::QPlaceSearchRequestPrivate(const QPlaceSearchRequestPrivate &other) : QSharedData(other), searchTerm(other.searchTerm), categories(other.categories), dymNumber(other.dymNumber), visibilityScope(other.visibilityScope), relevanceHint(other.relevanceHint), limit(other.limit), offset(other.offset) { if (other.searchArea) searchArea = other.searchArea->clone(); else searchArea = 0; } QPlaceSearchRequestPrivate::~QPlaceSearchRequestPrivate() { delete searchArea; } QPlaceSearchRequestPrivate &QPlaceSearchRequestPrivate::operator=(const QPlaceSearchRequestPrivate &other) { searchTerm = other.searchTerm; categories = other.categories; if (other.searchArea) searchArea = other.searchArea->clone(); else searchArea = 0; dymNumber = other.dymNumber; visibilityScope = other.visibilityScope; relevanceHint = other.relevanceHint; limit = other.limit; offset = other.offset; return *this; } bool QPlaceSearchRequestPrivate::operator==(const QPlaceSearchRequestPrivate &other) const { bool searchAreaMatch = false; if ((searchArea == 0) && (other.searchArea == 0)) { searchAreaMatch = true; } else if (searchArea && other.searchArea) { if (*searchArea == *(other.searchArea)) searchAreaMatch = true; else searchAreaMatch = false; } else { searchAreaMatch = false; } return ( searchTerm == other.searchTerm && categories == other.categories && dymNumber == other.dymNumber && searchAreaMatch && visibilityScope == other.visibilityScope && relevanceHint == other.relevanceHint && limit == other.limit && offset == other.offset ); } void QPlaceSearchRequestPrivate::clear() { limit = -1; offset = 0; searchTerm.clear(); categories.clear(); delete searchArea; searchArea = 0; dymNumber = 0; visibilityScope = QtLocation::UnspecifiedVisibility; relevanceHint = QPlaceSearchRequest::UnspecifiedHint; } /*! \class QPlaceSearchRequest \inmodule QtLocation \ingroup QtLocation-places \ingroup QtLocation-places-requests \since QtLocation 5.0 \brief The QPlaceSearchRequest class represents the set of parameters for a search request. A typical search request may look like the following: \snippet snippets/places/requesthandler.h Search request Note that specifying a search center can be done by setting a circular search area that has a center but no radius. The default radius is set to -1, which indicates an undefined radius. The provider will interpret this as being free to choose its own default radius. The QPlaceSearchRequest will assume ownership of the bounding area and will be responsible for its destruction. The QPlaceSearchRequest is primarily used with the QPlaceManager to \l {QPlaceManager::search()} {search for places}, however it is also used to provide parameters for \l {QPlaceManager::searchSuggestions()}{generating search term suggestions} and \l {QPlaceManager::recommendations()} {retreiving recommendations}. Note that depending on usage, some parameters may not be relevant, e.g. the relevance hint is not important for search term suggestions. However in general, most of the parameters are useful for each of these operations, eg for a recommendation, a search area and categories can be useful in narrowing down recommendation candidates. Also be aware that providers may vary by which parameters they support e.g. some providers may not support paging while others do, some providers may honor relevance hints while others may completely ignore them, see \l {Information about plugins}. */ /*! \enum QPlaceSearchRequest::RelevanceHint Defines hints to help rank place results. \value UnspecifiedHint No explicit hint has been specified. \value DistanceHint Distance to a search center is relevant for the user. Closer places are more highly weighted. This hint is only useful if a circular bounding area is used in the query. \value LexicalPlaceNameHint Alphabetic ordering of places according to name is relevant to the user. */ /*! Default constructor. Constructs an new request object. */ QPlaceSearchRequest::QPlaceSearchRequest() : d_ptr(new QPlaceSearchRequestPrivate()) { } /*! Constructs a copy of \a other. */ QPlaceSearchRequest::QPlaceSearchRequest(const QPlaceSearchRequest &other) : d_ptr(other.d_ptr) { } /*! Destroys the request object. */ QPlaceSearchRequest::~QPlaceSearchRequest() { } /*! Assigns \a other to this search request and returns a reference to this search request. */ QPlaceSearchRequest &QPlaceSearchRequest::operator= (const QPlaceSearchRequest & other) { d_ptr = other.d_ptr; return *this; } /*! Returns true if \a other is equal to this search request, otherwise returns false. */ bool QPlaceSearchRequest::operator== (const QPlaceSearchRequest &other) const { Q_D(const QPlaceSearchRequest); return *d == *other.d_func(); } /*! Returns true if \a other is not equal to this search request, otherwise returns false. */ bool QPlaceSearchRequest::operator!= (const QPlaceSearchRequest &other) const { Q_D(const QPlaceSearchRequest); return !(*d == *other.d_func()); } /*! Returns the search term. */ QString QPlaceSearchRequest::searchTerm() const { Q_D(const QPlaceSearchRequest); return d->searchTerm; } /*! Sets the search \a term. */ void QPlaceSearchRequest::setSearchTerm(const QString &term) { Q_D(QPlaceSearchRequest); d->searchTerm = term; } /*! Return the categories to be used in the search request. Places need only to belong to one of the categories to be considered a match by the request. */ QList<QPlaceCategory> QPlaceSearchRequest::categories() const { Q_D(const QPlaceSearchRequest); return d->categories; } /*! Sets the search request to search by a single \a category \sa setCategories() */ void QPlaceSearchRequest::setCategory(const QPlaceCategory &category) { Q_D(QPlaceSearchRequest); d->categories.clear(); if (!category.categoryId().isEmpty()) d->categories.append(category); } /*! Sets the search request to search from the list of given \a categories. Any places returned during the search will match at least one of the \a categories. \sa setCategory() */ void QPlaceSearchRequest::setCategories(const QList<QPlaceCategory> &categories) { Q_D(QPlaceSearchRequest); d->categories = categories; } /*! Returns search area. The default search area is a null pointer. */ QGeoBoundingArea *QPlaceSearchRequest::searchArea() const { Q_D(const QPlaceSearchRequest); return d->searchArea; } /*! Sets the search request to search within the given \a area. Ownership of the \a area is transferred to the request, who is now responsible for pointer deletion. If a new \a area is being assigned, the old area is deleted. */ void QPlaceSearchRequest::setSearchArea(QGeoBoundingArea *area) { Q_D(QPlaceSearchRequest); if (d->searchArea != area) delete d->searchArea; d->searchArea = area; } /*! Returns the maximum number of search term corrections that may be returned. */ int QPlaceSearchRequest::maximumCorrections() const { Q_D(const QPlaceSearchRequest); return d->dymNumber; } /*! Sets maximum \a number of search term corrections that may be returned. */ void QPlaceSearchRequest::setMaximumCorrections(int number) { Q_D(QPlaceSearchRequest); d->dymNumber = number; } /*! Returns the visibility scope used when searching for places. The default value is QtLocation::UnspecifiedVisibility meaning that no explicit scope has been assigned. Places of any scope may be returned during the search. */ QtLocation::VisibilityScope QPlaceSearchRequest::visibilityScope() const { Q_D(const QPlaceSearchRequest); return d->visibilityScope; } /*! Sets the visibiliy \a scope used when searching for places. */ void QPlaceSearchRequest::setVisibilityScope(QtLocation::VisibilityScope scope) { Q_D(QPlaceSearchRequest); d->visibilityScope = scope; } /*! Returns the relevance hint of the request. The hint is given to the provider to help but not dictate the ranking of results. eg providng a distance hint may give closer places a higher ranking but it doesn't necessarily mean that he results will be ordered strictly according to distance. */ QPlaceSearchRequest::RelevanceHint QPlaceSearchRequest::relevanceHint() const { Q_D(const QPlaceSearchRequest); return d->relevanceHint; } /*! Sets the relevance \a hint to be used when searching for a place. */ void QPlaceSearchRequest::setRelevanceHint(QPlaceSearchRequest::RelevanceHint hint) { Q_D(QPlaceSearchRequest); d->relevanceHint = hint; } /*! Returns the maximum number of search results to retrieve. A negative value for limit means that it is undefined. It is left up to the backend provider to choose an appropriate number of results to return. The default limit is -1. */ int QPlaceSearchRequest::limit() const { Q_D(const QPlaceSearchRequest); return d->limit; } /*! Set the maximum number of search results to retrieve to \a limit. */ void QPlaceSearchRequest::setLimit(int limit) { Q_D(QPlaceSearchRequest); d->limit = limit; } /*! Returns the offset index of the first item that is to be retrieved. The default offset is 0. */ int QPlaceSearchRequest::offset() const { Q_D(const QPlaceSearchRequest); return d->offset; } /*! Sets the starting index of the first item to be retrieved to \a offset. */ void QPlaceSearchRequest::setOffset(int offset) { Q_D(QPlaceSearchRequest); d->offset = offset; } /*! Clears the search request. */ void QPlaceSearchRequest::clear() { Q_D(QPlaceSearchRequest); d->clear(); } inline QPlaceSearchRequestPrivate* QPlaceSearchRequest::d_func() { return static_cast<QPlaceSearchRequestPrivate *>(d_ptr.data()); } inline const QPlaceSearchRequestPrivate* QPlaceSearchRequest::d_func() const { return static_cast<const QPlaceSearchRequestPrivate *>(d_ptr.constData()); } QT_END_NAMESPACE
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtLocation module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** 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. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qplacesearchrequest.h" #include "qgeocoordinate.h" #include "qgeoboundingarea.h" #include <QtCore/QSharedData> #include <QtCore/QList> QT_BEGIN_NAMESPACE class QPlaceSearchRequestPrivate : public QSharedData { public: QPlaceSearchRequestPrivate(); QPlaceSearchRequestPrivate(const QPlaceSearchRequestPrivate &other); ~QPlaceSearchRequestPrivate(); QPlaceSearchRequestPrivate &operator=(const QPlaceSearchRequestPrivate &other); bool operator==(const QPlaceSearchRequestPrivate &other) const; void clear(); QString searchTerm; QList<QPlaceCategory> categories; QGeoBoundingArea *searchArea; int dymNumber; QtLocation::VisibilityScope visibilityScope; QPlaceSearchRequest::RelevanceHint relevanceHint; int limit; int offset; }; QPlaceSearchRequestPrivate::QPlaceSearchRequestPrivate() : QSharedData(), searchArea(0), dymNumber(0), visibilityScope(QtLocation::UnspecifiedVisibility), relevanceHint(QPlaceSearchRequest::UnspecifiedHint), limit(-1), offset(0) { } QPlaceSearchRequestPrivate::QPlaceSearchRequestPrivate(const QPlaceSearchRequestPrivate &other) : QSharedData(other), searchTerm(other.searchTerm), categories(other.categories), dymNumber(other.dymNumber), visibilityScope(other.visibilityScope), relevanceHint(other.relevanceHint), limit(other.limit), offset(other.offset) { if (other.searchArea) searchArea = other.searchArea->clone(); else searchArea = 0; } QPlaceSearchRequestPrivate::~QPlaceSearchRequestPrivate() { delete searchArea; } QPlaceSearchRequestPrivate &QPlaceSearchRequestPrivate::operator=(const QPlaceSearchRequestPrivate &other) { if (this != &other) { searchTerm = other.searchTerm; categories = other.categories; if (other.searchArea) searchArea = other.searchArea->clone(); else searchArea = 0; dymNumber = other.dymNumber; visibilityScope = other.visibilityScope; relevanceHint = other.relevanceHint; limit = other.limit; offset = other.offset; } return *this; } bool QPlaceSearchRequestPrivate::operator==(const QPlaceSearchRequestPrivate &other) const { bool searchAreaMatch = false; if ((searchArea == 0) && (other.searchArea == 0)) { searchAreaMatch = true; } else if (searchArea && other.searchArea) { if (*searchArea == *(other.searchArea)) searchAreaMatch = true; else searchAreaMatch = false; } else { searchAreaMatch = false; } return ( searchTerm == other.searchTerm && categories == other.categories && dymNumber == other.dymNumber && searchAreaMatch && visibilityScope == other.visibilityScope && relevanceHint == other.relevanceHint && limit == other.limit && offset == other.offset ); } void QPlaceSearchRequestPrivate::clear() { limit = -1; offset = 0; searchTerm.clear(); categories.clear(); delete searchArea; searchArea = 0; dymNumber = 0; visibilityScope = QtLocation::UnspecifiedVisibility; relevanceHint = QPlaceSearchRequest::UnspecifiedHint; } /*! \class QPlaceSearchRequest \inmodule QtLocation \ingroup QtLocation-places \ingroup QtLocation-places-requests \since QtLocation 5.0 \brief The QPlaceSearchRequest class represents the set of parameters for a search request. A typical search request may look like the following: \snippet snippets/places/requesthandler.h Search request Note that specifying a search center can be done by setting a circular search area that has a center but no radius. The default radius is set to -1, which indicates an undefined radius. The provider will interpret this as being free to choose its own default radius. The QPlaceSearchRequest will assume ownership of the bounding area and will be responsible for its destruction. The QPlaceSearchRequest is primarily used with the QPlaceManager to \l {QPlaceManager::search()} {search for places}, however it is also used to provide parameters for \l {QPlaceManager::searchSuggestions()}{generating search term suggestions} and \l {QPlaceManager::recommendations()} {retreiving recommendations}. Note that depending on usage, some parameters may not be relevant, e.g. the relevance hint is not important for search term suggestions. However in general, most of the parameters are useful for each of these operations, eg for a recommendation, a search area and categories can be useful in narrowing down recommendation candidates. Also be aware that providers may vary by which parameters they support e.g. some providers may not support paging while others do, some providers may honor relevance hints while others may completely ignore them, see \l {Information about plugins}. */ /*! \enum QPlaceSearchRequest::RelevanceHint Defines hints to help rank place results. \value UnspecifiedHint No explicit hint has been specified. \value DistanceHint Distance to a search center is relevant for the user. Closer places are more highly weighted. This hint is only useful if a circular bounding area is used in the query. \value LexicalPlaceNameHint Alphabetic ordering of places according to name is relevant to the user. */ /*! Default constructor. Constructs an new request object. */ QPlaceSearchRequest::QPlaceSearchRequest() : d_ptr(new QPlaceSearchRequestPrivate()) { } /*! Constructs a copy of \a other. */ QPlaceSearchRequest::QPlaceSearchRequest(const QPlaceSearchRequest &other) : d_ptr(other.d_ptr) { } /*! Destroys the request object. */ QPlaceSearchRequest::~QPlaceSearchRequest() { } /*! Assigns \a other to this search request and returns a reference to this search request. */ QPlaceSearchRequest &QPlaceSearchRequest::operator= (const QPlaceSearchRequest & other) { d_ptr = other.d_ptr; return *this; } /*! Returns true if \a other is equal to this search request, otherwise returns false. */ bool QPlaceSearchRequest::operator== (const QPlaceSearchRequest &other) const { Q_D(const QPlaceSearchRequest); return *d == *other.d_func(); } /*! Returns true if \a other is not equal to this search request, otherwise returns false. */ bool QPlaceSearchRequest::operator!= (const QPlaceSearchRequest &other) const { Q_D(const QPlaceSearchRequest); return !(*d == *other.d_func()); } /*! Returns the search term. */ QString QPlaceSearchRequest::searchTerm() const { Q_D(const QPlaceSearchRequest); return d->searchTerm; } /*! Sets the search \a term. */ void QPlaceSearchRequest::setSearchTerm(const QString &term) { Q_D(QPlaceSearchRequest); d->searchTerm = term; } /*! Return the categories to be used in the search request. Places need only to belong to one of the categories to be considered a match by the request. */ QList<QPlaceCategory> QPlaceSearchRequest::categories() const { Q_D(const QPlaceSearchRequest); return d->categories; } /*! Sets the search request to search by a single \a category \sa setCategories() */ void QPlaceSearchRequest::setCategory(const QPlaceCategory &category) { Q_D(QPlaceSearchRequest); d->categories.clear(); if (!category.categoryId().isEmpty()) d->categories.append(category); } /*! Sets the search request to search from the list of given \a categories. Any places returned during the search will match at least one of the \a categories. \sa setCategory() */ void QPlaceSearchRequest::setCategories(const QList<QPlaceCategory> &categories) { Q_D(QPlaceSearchRequest); d->categories = categories; } /*! Returns search area. The default search area is a null pointer. */ QGeoBoundingArea *QPlaceSearchRequest::searchArea() const { Q_D(const QPlaceSearchRequest); return d->searchArea; } /*! Sets the search request to search within the given \a area. Ownership of the \a area is transferred to the request, who is now responsible for pointer deletion. If a new \a area is being assigned, the old area is deleted. */ void QPlaceSearchRequest::setSearchArea(QGeoBoundingArea *area) { Q_D(QPlaceSearchRequest); if (d->searchArea != area) delete d->searchArea; d->searchArea = area; } /*! Returns the maximum number of search term corrections that may be returned. */ int QPlaceSearchRequest::maximumCorrections() const { Q_D(const QPlaceSearchRequest); return d->dymNumber; } /*! Sets maximum \a number of search term corrections that may be returned. */ void QPlaceSearchRequest::setMaximumCorrections(int number) { Q_D(QPlaceSearchRequest); d->dymNumber = number; } /*! Returns the visibility scope used when searching for places. The default value is QtLocation::UnspecifiedVisibility meaning that no explicit scope has been assigned. Places of any scope may be returned during the search. */ QtLocation::VisibilityScope QPlaceSearchRequest::visibilityScope() const { Q_D(const QPlaceSearchRequest); return d->visibilityScope; } /*! Sets the visibiliy \a scope used when searching for places. */ void QPlaceSearchRequest::setVisibilityScope(QtLocation::VisibilityScope scope) { Q_D(QPlaceSearchRequest); d->visibilityScope = scope; } /*! Returns the relevance hint of the request. The hint is given to the provider to help but not dictate the ranking of results. eg providng a distance hint may give closer places a higher ranking but it doesn't necessarily mean that he results will be ordered strictly according to distance. */ QPlaceSearchRequest::RelevanceHint QPlaceSearchRequest::relevanceHint() const { Q_D(const QPlaceSearchRequest); return d->relevanceHint; } /*! Sets the relevance \a hint to be used when searching for a place. */ void QPlaceSearchRequest::setRelevanceHint(QPlaceSearchRequest::RelevanceHint hint) { Q_D(QPlaceSearchRequest); d->relevanceHint = hint; } /*! Returns the maximum number of search results to retrieve. A negative value for limit means that it is undefined. It is left up to the backend provider to choose an appropriate number of results to return. The default limit is -1. */ int QPlaceSearchRequest::limit() const { Q_D(const QPlaceSearchRequest); return d->limit; } /*! Set the maximum number of search results to retrieve to \a limit. */ void QPlaceSearchRequest::setLimit(int limit) { Q_D(QPlaceSearchRequest); d->limit = limit; } /*! Returns the offset index of the first item that is to be retrieved. The default offset is 0. */ int QPlaceSearchRequest::offset() const { Q_D(const QPlaceSearchRequest); return d->offset; } /*! Sets the starting index of the first item to be retrieved to \a offset. */ void QPlaceSearchRequest::setOffset(int offset) { Q_D(QPlaceSearchRequest); d->offset = offset; } /*! Clears the search request. */ void QPlaceSearchRequest::clear() { Q_D(QPlaceSearchRequest); d->clear(); } inline QPlaceSearchRequestPrivate* QPlaceSearchRequest::d_func() { return static_cast<QPlaceSearchRequestPrivate *>(d_ptr.data()); } inline const QPlaceSearchRequestPrivate* QPlaceSearchRequest::d_func() const { return static_cast<const QPlaceSearchRequestPrivate *>(d_ptr.constData()); } QT_END_NAMESPACE
Fix assignment in QPlaceSearchRequest.
Fix assignment in QPlaceSearchRequest. Check for equality. Change-Id: I12b9d16d4b94235bbcb9eb70a3a8713b196280a1 Reviewed-by: Aaron McCarthy <[email protected]>
C++
lgpl-2.1
kobolabs/qtlocation,amccarthy/qtlocation,amccarthy/qtlocation,kobolabs/qtlocation,amccarthy/qtlocation,kobolabs/qtlocation
6e999add60efc09186320d621d5f4c6452cc02f3
src/contrib/mlir/pass/mlir_subgraph_extraction.cpp
src/contrib/mlir/pass/mlir_subgraph_extraction.cpp
//***************************************************************************** // Copyright 2017-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. //***************************************************************************** // NOTE: This file follows nGraph format style and naming convention since it // exposes a public API to the rest of nGraph codebase. #include "mlir_subgraph_extraction.hpp" #include "ngraph/assertion.hpp" #include "ngraph/graph_util.hpp" #include "ngraph/node.hpp" #include "ngraph/op/add.hpp" #include "ngraph/op/argmax.hpp" #include "ngraph/op/argmin.hpp" #include "ngraph/op/concat.hpp" #include "ngraph/op/divide.hpp" #include "ngraph/op/dot.hpp" #include "ngraph/op/experimental/compiled_kernel.hpp" #include "ngraph/op/gather.hpp" #include "ngraph/op/get_output_element.hpp" #include "ngraph/op/greater.hpp" #include "ngraph/op/less.hpp" #include "ngraph/op/maximum.hpp" #include "ngraph/op/minimum.hpp" #include "ngraph/op/multiply.hpp" #include "ngraph/op/negative.hpp" #include "ngraph/op/relu.hpp" #include "ngraph/op/subtract.hpp" using namespace ngraph::descriptor; using namespace ngraph::op; using namespace ngraph::pass; #define TI(x) std::type_index(typeid(x)) // Maximum depth to check for cycles. If exceeded, we conservatively assume a cycle. #define MAX_CYCLE_DEPTH 100 int MLIRSubgraphExtractionPass::MLIRSubgraph::m_curr_graph_id = 0; template <typename T> void MLIRSubgraphExtractionPass::MLIRSubgraph::add_inputs(T& inputs) { // inputs list are not exclusive, avoid duplication for (auto node : inputs) { if (m_input_nodes.find(node) == m_input_nodes.end()) { m_input_nodes.insert(node); } } } template <typename T> void MLIRSubgraphExtractionPass::MLIRSubgraph::add_outputs(T& outputs) { m_output_nodes.insert(outputs.begin(), outputs.end()); } void MLIRSubgraphExtractionPass::MLIRSubgraph::add_node(std::shared_ptr<Node> node) { NGRAPH_CHECK(m_nodes.find(node) == m_nodes.end(), "node added to graph before"); m_nodes.insert(node); m_pass.m_node_to_graph[node] = get_id(); } void MLIRSubgraphExtractionPass::MLIRSubgraph::merge(MLIRSubgraph& sg2) { NGRAPH_CHECK(&sg2 != this, "Cannot merge a sub-graph into itself"); // Associate nodes of second sub-graph to first one auto sg_nodes = sg2.get_nodes(); for (auto node : sg_nodes) { NGRAPH_DEBUG << *node; NGRAPH_CHECK(m_pass.get_subgraph_id(node) == sg2.get_id(), "Node does not belong to sub-graph"); m_pass.m_node_to_graph[node] = get_id(); } // nodes of sub-graphs are exclusive m_nodes.insert(sg2.get_nodes().begin(), sg2.get_nodes().end()); // merge inputs add_inputs(sg2.get_inputs()); // Remove sub-graph from map m_pass.m_id_to_graph.erase(sg2.get_id()); } // The sub-graph construction algorithm is as follows // For each node, check its predecessors, if // - all predecessors in sub-graphs belong to the same sub-graph (graph ID), then extend the sub-graph to include the current node. // Predecessors outside sub-graphs are marked as input to the sub-graph. // - predecessors in sub-graphs belong to different sub-graphs, then merge all the sub-graphs into one, and add current node to it. // Predecessors outside sub-graphs are marked as input to the sub-graph. // // If the node has any external inputs, then it's possible that the input may come from one of the predecessor sub-graphs (cycle). // If a cycle is found, always start a new sub-graph. // // For each sub-graph found build a CompiledKernel(CK) node around it as follows // - all inputs edges to the sub-graph are cloned as inputs to CK node as well. // - all outputs edges from the sub-graph are removed and added as outputs to CK node instead. // - CK will internally have lists record graph nodes, and graph output nodes. bool MLIRSubgraphExtractionPass::run_on_function(std::shared_ptr<Function> func) { NGRAPH_DEBUG << "[CK Extract] Construct sub-graphs" << std::endl; for (auto op : func->get_ordered_ops()) { NodeVector inputs; std::unordered_set<int> subgraph_ids; // unsupported ops, skip if (!is_supported_mlir_op(op)) { continue; } if (TI(Parameter) == TI(*op) || TI(Result) == TI(*op)) { continue; } NGRAPH_DEBUG << "[CK Extract] Processing " << *op << std::endl; // supported op for (auto pred : op->get_arguments()) { int pred_subgraph_id = get_subgraph_id(pred); if (pred_subgraph_id == -1) { // predecessor doesn't belong to any sub-graph, it is an input inputs.push_back(pred); } else { // record sub-graph id of the predecessor subgraph_ids.insert(pred_subgraph_id); } } if (subgraph_ids.size() == 0) { NGRAPH_DEBUG << "[CK Extract] Start new sub-graph " << std::endl; // we couldn't find any predecessor sub-graphs to extend with this node // create a new sub-graph MLIRSubgraph sg = MLIRSubgraph::create(this); sg.add_inputs(inputs); sg.add_node(op); add_subgraph(sg); } else { // we have sub-graphs. // check if adding this node to the sub-graph will create a cycle in the DAG NGRAPH_DEBUG << "[CK Extract] Extending sub-graph. Check for cycles " << std::endl; if (!check_cycles(op, subgraph_ids)) { NGRAPH_DEBUG << "[CK Extract] Merging subgraphs"; // merge sub-graphs if needed std::unordered_set<int>::iterator it = subgraph_ids.begin(); int sg_id = *it; MLIRSubgraph& first_subgraph = get_subgraph(sg_id); NGRAPH_CHECK(first_subgraph.get_id() == sg_id); while (++it != subgraph_ids.end()) { sg_id = *it; MLIRSubgraph& subgraph = get_subgraph(sg_id); NGRAPH_CHECK(subgraph.get_id() == sg_id); first_subgraph.merge(subgraph); } first_subgraph.add_node(op); first_subgraph.add_inputs(inputs); } else { // we have a cycle, start a new sub-graph MLIRSubgraph sg = MLIRSubgraph::create(this); NGRAPH_DEBUG << "[CK Extract] Cycle found. Start a new subgraph"; // use all predecessors as graph inputs NodeVector inputs = op->get_arguments(); sg.add_inputs(inputs); sg.add_node(op); add_subgraph(sg); } } NGRAPH_DEBUG << "[CK Extract] Node Processed " << *op << std::endl; } NGRAPH_DEBUG << "[CK Extract] Get subgraphs output nodes" << std::endl; // get output nodes for each sub-graph. Do this before attaching CK nodes since we will // remove output edges from the sub-graphs. for (IDGraphMap::iterator it = m_id_to_graph.begin(); it != m_id_to_graph.end(); it++) { MLIRSubgraph& sg = it->second; auto& nodes = sg.get_nodes(); NodeVector outputs = std::move(get_subgraph_outputs(NodeVector(nodes.begin(), nodes.end()), {} /*exclusions*/, false /* ignore unused */, false /* ignore output duplicates */)); sg.add_outputs(outputs); } NGRAPH_DEBUG << "[CK Extract] Construct CK nodes" << std::endl; // attach CK node to each sub-graph. for (auto it : m_id_to_graph) { MLIRSubgraph sg = it.second; auto& inputs = sg.get_inputs(); auto& outputs = sg.get_outputs(); auto& nodes = sg.get_nodes(); NodeVector inputs_vector(inputs.begin(), inputs.end()); NodeVector outputs_vector(outputs.begin(), outputs.end()); // must store nodes in topological order auto nodes_list = subgraph_topological_sort(nodes); NodeVector nodes_vector(nodes_list.begin(), nodes_list.end()); auto ck = std::make_shared<CompiledKernel>(nodes_vector, outputs_vector, inputs_vector); NGRAPH_DEBUG << "[CK Extract] Graph ID = " << sg.get_id() << std::endl; NGRAPH_DEBUG << "[CK Extract] Graph Nodes: " << std::endl; for (auto node : nodes) { NGRAPH_DEBUG << "[CK Extract] " << *node << std::endl; } NGRAPH_DEBUG << "[CK Extract] Input Nodes: " << std::endl; for (auto node : inputs) { NGRAPH_DEBUG << "[CK Extract] " << *node << std::endl; } NGRAPH_DEBUG << "[CK Extract] Output Nodes: " << std::endl; for (auto node : outputs) { NGRAPH_DEBUG << "[CK Extract] " << *node << std::endl; } // Connect CompiledKernel to output nodes by replacing the output descriptors of the output // nodes. for (size_t i = 0, end = outputs_vector.size(); i < end; ++i) { auto& output_descs = outputs_vector[i]->get_outputs(); NGRAPH_CHECK(output_descs.size() == 1, "Unexpected multiple output descriptors"); auto& out_desc = output_descs[0]; // 'replace_output' invalidates iterator of the original container. Use a copy instead. const std::vector<descriptor::Input*> input_descs = out_desc.get_inputs(); for (descriptor::Input* in_desc : input_descs) { in_desc->replace_output(ck, i); } } } return true; } #define TI(x) std::type_index(typeid(x)) bool MLIRSubgraphExtractionPass::is_supported_mlir_op(std::shared_ptr<Node> node) { if (TI(Parameter) == TI(*node) || TI(Result) == TI(*node)) { return true; } // supported by backend ? if (m_supported_ops.find(TI(*node)) == m_supported_ops.end()) { return false; } // check on invariants expected by MLIR backend if (TI(ngraph::op::Divide) == TI(*node)) { auto* div = static_cast<ngraph::op::Divide*>(node.get()); if (div->is_pythondiv()) { // Python specific division rounding is not supported yet. return false; } return true; } // Dot is 2D only if (TI(ngraph::op::Dot) == TI(*node)) { if (node->get_input_shape(0).size() != 2 || node->get_input_shape(1).size() != 2) { return false; } else { return true; } } if (TI(ngraph::op::ArgMin) == TI(*node) || TI(ngraph::op::ArgMax) == TI(*node)) { // TODO: Remove this when MLIR has float point cmp support if (!node->input(0).get_element_type().is_integral()) { return false; } else { return true; } } if (TI(ngraph::op::Maximum) == TI(*node) || TI(ngraph::op::Minimum) == TI(*node)) { // TODO: Remove this when MLIR has float point cmp support if (!node->input(0).get_element_type().is_integral()) { return false; } else { return true; } } if (TI(ngraph::op::Greater) == TI(*node) || TI(ngraph::op::Less) == TI(*node)) { // TODO: Remove this when MLIR has float point cmp support if (!node->input(0).get_element_type().is_integral()) { return false; } else { return true; } } if (TI(ngraph::op::Negative) == TI(*node)) { return true; } return true; } bool MLIRSubgraphExtractionPass::check_cycles(std::shared_ptr<Node> node, std::unordered_set<int>& subgraph_ids, bool inside_subgraphs, unsigned depth) { // Going too deep, bail out. if (depth >= MAX_CYCLE_DEPTH) return true; // root node is always inside merged sub-graphs. if (depth != 0) { if (subgraph_ids.find(get_subgraph_id(node)) != subgraph_ids.end()) { // This node is inside a sub-graph. If we are coming from outside the sub-graphs, then we formed a cycle. if (!inside_subgraphs) { return true; } } else { inside_subgraphs = false; } } for (auto& input : node->get_arguments()) { if (check_cycles(input, subgraph_ids, inside_subgraphs, ++depth)) return true; } return false; } const std::set<std::type_index> MLIRSubgraphExtractionPass::m_supported_ops{ #define MLIR_OP(OP) TI(ngraph::op::OP), #include "contrib/mlir/ops_supported.inc" };
//***************************************************************************** // Copyright 2017-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. //***************************************************************************** // NOTE: This file follows nGraph format style and naming convention since it // exposes a public API to the rest of nGraph codebase. #include "mlir_subgraph_extraction.hpp" #include "ngraph/assertion.hpp" #include "ngraph/graph_util.hpp" #include "ngraph/node.hpp" #include "ngraph/op/add.hpp" #include "ngraph/op/argmax.hpp" #include "ngraph/op/argmin.hpp" #include "ngraph/op/concat.hpp" #include "ngraph/op/divide.hpp" #include "ngraph/op/dot.hpp" #include "ngraph/op/experimental/compiled_kernel.hpp" #include "ngraph/op/gather.hpp" #include "ngraph/op/get_output_element.hpp" #include "ngraph/op/greater.hpp" #include "ngraph/op/less.hpp" #include "ngraph/op/maximum.hpp" #include "ngraph/op/minimum.hpp" #include "ngraph/op/multiply.hpp" #include "ngraph/op/negative.hpp" #include "ngraph/op/relu.hpp" #include "ngraph/op/subtract.hpp" using namespace ngraph::descriptor; using namespace ngraph::op; using namespace ngraph::pass; #define TI(x) std::type_index(typeid(x)) // Maximum depth to check for cycles. If exceeded, we conservatively assume a cycle. #define MAX_CYCLE_DEPTH 100 int MLIRSubgraphExtractionPass::MLIRSubgraph::m_curr_graph_id = 0; template <typename T> void MLIRSubgraphExtractionPass::MLIRSubgraph::add_inputs(T& inputs) { // inputs list are not exclusive, avoid duplication for (auto node : inputs) { if (m_input_nodes.find(node) == m_input_nodes.end()) { m_input_nodes.insert(node); } } } template <typename T> void MLIRSubgraphExtractionPass::MLIRSubgraph::add_outputs(T& outputs) { m_output_nodes.insert(outputs.begin(), outputs.end()); } void MLIRSubgraphExtractionPass::MLIRSubgraph::add_node(std::shared_ptr<Node> node) { NGRAPH_CHECK(m_nodes.find(node) == m_nodes.end(), "node added to graph before"); m_nodes.insert(node); m_pass.m_node_to_graph[node] = get_id(); } void MLIRSubgraphExtractionPass::MLIRSubgraph::merge(MLIRSubgraph& sg2) { NGRAPH_CHECK(&sg2 != this, "Cannot merge a sub-graph into itself"); // Associate nodes of second sub-graph to first one auto sg_nodes = sg2.get_nodes(); for (auto node : sg_nodes) { NGRAPH_DEBUG << *node; NGRAPH_CHECK(m_pass.get_subgraph_id(node) == sg2.get_id(), "Node does not belong to sub-graph"); m_pass.m_node_to_graph[node] = get_id(); } // nodes of sub-graphs are exclusive m_nodes.insert(sg2.get_nodes().begin(), sg2.get_nodes().end()); // merge inputs add_inputs(sg2.get_inputs()); // Remove sub-graph from map m_pass.m_id_to_graph.erase(sg2.get_id()); } // The sub-graph construction algorithm is as follows // For each node, check its predecessors, if // - all predecessors in sub-graphs belong to the same sub-graph (graph ID), then extend the sub-graph to include the current node. // Predecessors outside sub-graphs are marked as input to the sub-graph. // - predecessors in sub-graphs belong to different sub-graphs, then merge all the sub-graphs into one, and add current node to it. // Predecessors outside sub-graphs are marked as input to the sub-graph. // // If the node has any external inputs, then it's possible that the input may come from one of the predecessor sub-graphs (cycle). // If a cycle is found, always start a new sub-graph. // // For each sub-graph found build a CompiledKernel(CK) node around it as follows // - all inputs edges to the sub-graph are cloned as inputs to CK node as well. // - all outputs edges from the sub-graph are removed and added as outputs to CK node instead. // - CK will internally have lists record graph nodes, and graph output nodes. bool MLIRSubgraphExtractionPass::run_on_function(std::shared_ptr<Function> func) { NGRAPH_DEBUG << "[CK Extract] Construct sub-graphs" << std::endl; for (auto op : func->get_ordered_ops()) { NodeVector inputs; std::unordered_set<int> subgraph_ids; // unsupported ops, skip if (!is_supported_mlir_op(op)) { continue; } if (TI(Parameter) == TI(*op) || TI(Result) == TI(*op)) { continue; } NGRAPH_DEBUG << "[CK Extract] Processing " << *op << std::endl; // supported op for (auto pred : op->get_arguments()) { int pred_subgraph_id = get_subgraph_id(pred); if (pred_subgraph_id == -1) { // predecessor doesn't belong to any sub-graph, it is an input inputs.push_back(pred); } else { // record sub-graph id of the predecessor subgraph_ids.insert(pred_subgraph_id); } } if (subgraph_ids.size() == 0) { NGRAPH_DEBUG << "[CK Extract] Start new sub-graph " << std::endl; // we couldn't find any predecessor sub-graphs to extend with this node // create a new sub-graph MLIRSubgraph sg = MLIRSubgraph::create(this); sg.add_inputs(inputs); sg.add_node(op); add_subgraph(sg); } else { // we have sub-graphs. // check if adding this node to the sub-graph will create a cycle in the DAG NGRAPH_DEBUG << "[CK Extract] Extending sub-graph. Check for cycles " << std::endl; if (!check_cycles(op, subgraph_ids)) { NGRAPH_DEBUG << "[CK Extract] Merging subgraphs"; // merge sub-graphs if needed std::unordered_set<int>::iterator it = subgraph_ids.begin(); int sg_id = *it; MLIRSubgraph& first_subgraph = get_subgraph(sg_id); NGRAPH_CHECK(first_subgraph.get_id() == sg_id); while (++it != subgraph_ids.end()) { sg_id = *it; MLIRSubgraph& subgraph = get_subgraph(sg_id); NGRAPH_CHECK(subgraph.get_id() == sg_id); first_subgraph.merge(subgraph); } first_subgraph.add_node(op); first_subgraph.add_inputs(inputs); } else { // we have a cycle, start a new sub-graph MLIRSubgraph sg = MLIRSubgraph::create(this); NGRAPH_DEBUG << "[CK Extract] Cycle found. Start a new subgraph"; // use all predecessors as graph inputs NodeVector inputs = op->get_arguments(); sg.add_inputs(inputs); sg.add_node(op); add_subgraph(sg); } } NGRAPH_DEBUG << "[CK Extract] Node Processed " << *op << std::endl; } NGRAPH_DEBUG << "[CK Extract] Get subgraphs output nodes" << std::endl; // get output nodes for each sub-graph. Do this before attaching CK nodes since we will // remove output edges from the sub-graphs. for (IDGraphMap::iterator it = m_id_to_graph.begin(); it != m_id_to_graph.end(); it++) { MLIRSubgraph& sg = it->second; auto& nodes = sg.get_nodes(); NodeVector outputs = std::move(get_subgraph_outputs(NodeVector(nodes.begin(), nodes.end()), {} /*exclusions*/, false /* ignore unused */, false /* ignore output duplicates */)); sg.add_outputs(outputs); } NGRAPH_DEBUG << "[CK Extract] Construct CK nodes" << std::endl; // attach CK node to each sub-graph. for (auto it : m_id_to_graph) { MLIRSubgraph sg = it.second; auto& inputs = sg.get_inputs(); auto& outputs = sg.get_outputs(); auto& nodes = sg.get_nodes(); NodeVector inputs_vector(inputs.begin(), inputs.end()); NodeVector outputs_vector(outputs.begin(), outputs.end()); // must store nodes in topological order auto nodes_list = subgraph_topological_sort(nodes); NodeVector nodes_vector(nodes_list.begin(), nodes_list.end()); auto ck = std::make_shared<CompiledKernel>(nodes_vector, outputs_vector, inputs_vector); NGRAPH_DEBUG << "[CK Extract] Graph ID = " << sg.get_id() << std::endl; NGRAPH_DEBUG << "[CK Extract] Graph Nodes: " << std::endl; for (auto node : nodes) { NGRAPH_DEBUG << "[CK Extract] " << *node << std::endl; } NGRAPH_DEBUG << "[CK Extract] Input Nodes: " << std::endl; for (auto node : inputs) { NGRAPH_DEBUG << "[CK Extract] " << *node << std::endl; } NGRAPH_DEBUG << "[CK Extract] Output Nodes: " << std::endl; for (auto node : outputs) { NGRAPH_DEBUG << "[CK Extract] " << *node << std::endl; } // Connect CompiledKernel to output nodes by replacing the output descriptors of the output // nodes. for (size_t i = 0, end = outputs_vector.size(); i < end; ++i) { auto& output_descs = outputs_vector[i]->get_outputs(); NGRAPH_CHECK(output_descs.size() == 1, "Unexpected multiple output descriptors"); auto& out_desc = output_descs[0]; // 'replace_output' invalidates iterator of the original container. Use a copy instead. const std::vector<descriptor::Input*> input_descs = out_desc.get_inputs(); for (descriptor::Input* in_desc : input_descs) { if (nodes.find(in_desc->get_node()) == nodes.end()) { in_desc->replace_output(ck, i); } } } } return true; } #define TI(x) std::type_index(typeid(x)) bool MLIRSubgraphExtractionPass::is_supported_mlir_op(std::shared_ptr<Node> node) { if (TI(Parameter) == TI(*node) || TI(Result) == TI(*node)) { return true; } // supported by backend ? if (m_supported_ops.find(TI(*node)) == m_supported_ops.end()) { return false; } // check on invariants expected by MLIR backend if (TI(ngraph::op::Divide) == TI(*node)) { auto* div = static_cast<ngraph::op::Divide*>(node.get()); if (div->is_pythondiv()) { // Python specific division rounding is not supported yet. return false; } return true; } // Dot is 2D only if (TI(ngraph::op::Dot) == TI(*node)) { if (node->get_input_shape(0).size() != 2 || node->get_input_shape(1).size() != 2) { return false; } else { return true; } } if (TI(ngraph::op::ArgMin) == TI(*node) || TI(ngraph::op::ArgMax) == TI(*node)) { // TODO: Remove this when MLIR has float point cmp support if (!node->input(0).get_element_type().is_integral()) { return false; } else { return true; } } if (TI(ngraph::op::Maximum) == TI(*node) || TI(ngraph::op::Minimum) == TI(*node)) { // TODO: Remove this when MLIR has float point cmp support if (!node->input(0).get_element_type().is_integral()) { return false; } else { return true; } } if (TI(ngraph::op::Greater) == TI(*node) || TI(ngraph::op::Less) == TI(*node)) { // TODO: Remove this when MLIR has float point cmp support if (!node->input(0).get_element_type().is_integral()) { return false; } else { return true; } } if (TI(ngraph::op::Negative) == TI(*node)) { return true; } return true; } bool MLIRSubgraphExtractionPass::check_cycles(std::shared_ptr<Node> node, std::unordered_set<int>& subgraph_ids, bool inside_subgraphs, unsigned depth) { // Going too deep, bail out. if (depth >= MAX_CYCLE_DEPTH) return true; // root node is always inside merged sub-graphs. if (depth != 0) { if (subgraph_ids.find(get_subgraph_id(node)) != subgraph_ids.end()) { // This node is inside a sub-graph. If we are coming from outside the sub-graphs, then we formed a cycle. if (!inside_subgraphs) { return true; } } else { inside_subgraphs = false; } } for (auto& input : node->get_arguments()) { if (check_cycles(input, subgraph_ids, inside_subgraphs, ++depth)) return true; } return false; } const std::set<std::type_index> MLIRSubgraphExtractionPass::m_supported_ops{ #define MLIR_OP(OP) TI(ngraph::op::OP), #include "contrib/mlir/ops_supported.inc" };
Copy outputs only if the use is outside the sub-graph (#3446)
Copy outputs only if the use is outside the sub-graph (#3446) * Copy outputs only if the use is outside the sub-graph * Use unordered_set find
C++
apache-2.0
NervanaSystems/ngraph,NervanaSystems/ngraph,NervanaSystems/ngraph,NervanaSystems/ngraph
de1029ff34c4e557eb6327c7b508614d76695904
lib/demoloop-lib/src/graphics/3d_primitives.cpp
lib/demoloop-lib/src/graphics/3d_primitives.cpp
#include "graphics/3d_primitives.h" #include <cmath> #include <numeric> namespace demoloop { Mesh* cube(const float cx, const float cy, const float cz, const float radius) { // static const GLfloat g_vertex_buffer_data[] = { // -1.0f,-1.0f,-1.0f, // -1.0f,-1.0f, 1.0f, // -1.0f, 1.0f, 1.0f, // 1.0f, 1.0f,-1.0f, // -1.0f,-1.0f,-1.0f, // -1.0f, 1.0f,-1.0f, // 1.0f,-1.0f, 1.0f, // -1.0f,-1.0f,-1.0f, // 1.0f,-1.0f,-1.0f, // 1.0f, 1.0f,-1.0f, // 1.0f,-1.0f,-1.0f, // -1.0f,-1.0f,-1.0f, // -1.0f,-1.0f,-1.0f, // -1.0f, 1.0f, 1.0f, // -1.0f, 1.0f,-1.0f, // 1.0f,-1.0f, 1.0f, // -1.0f,-1.0f, 1.0f, // -1.0f,-1.0f,-1.0f, // -1.0f, 1.0f, 1.0f, // -1.0f,-1.0f, 1.0f, // 1.0f,-1.0f, 1.0f, // 1.0f, 1.0f, 1.0f, // 1.0f,-1.0f,-1.0f, // 1.0f, 1.0f,-1.0f, // 1.0f,-1.0f,-1.0f, // 1.0f, 1.0f, 1.0f, // 1.0f,-1.0f, 1.0f, // 1.0f, 1.0f, 1.0f, // 1.0f, 1.0f,-1.0f, // -1.0f, 1.0f,-1.0f, // 1.0f, 1.0f, 1.0f, // -1.0f, 1.0f,-1.0f, // -1.0f, 1.0f, 1.0f, // 1.0f, 1.0f, 1.0f, // -1.0f, 1.0f, 1.0f, // 1.0f,-1.0f, 1.0f // }; static const GLfloat g_vertex_buffer_data[] = { // Top face 1.0f, 1.0f, -1.0f , 1.0f, 0.0f, // Top-right of top face -1.0f, 1.0f, -1.0f , 0.0f, 0.0f, // Top-left of top face -1.0f, 1.0f, 1.0f , 0.0f, 1.0f, // Bottom-left of top face 1.0f, 1.0f, 1.0f , 1.0f, 1.0f, // Bottom-right of top face // Bottom face 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, // Top-right of bottom face -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, // Top-left of bottom face -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, // Bottom-left of bottom face 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, // Bottom-right of bottom face // Front face 1.0f, 1.0f, 1.0f , 1.0f, 0.0f, // Top-Right of front face -1.0f, 1.0f, 1.0f , 0.0f, 0.0f, // Top-left of front face -1.0f, -1.0f, 1.0f , 0.0f, 1.0f, // Bottom-left of front face 1.0f, -1.0f, 1.0f , 1.0f, 1.0f, // Bottom-right of front face // Back face -1.0f, 1.0f, -1.0f, 1.0f, 0.0f, // Top-Right of back face 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, // Top-Left of back face 1.0f, -1.0f, -1.0f, 0.0f, 1.0f, // Bottom-Left of back face -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, // Bottom-Right of back face // Left face -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // Top-Right of left face -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, // Top-Left of left face -1.0f, -1.0f, -1.0f, 0.0f, 1.0f, // Bottom-Left of left face -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, // Bottom-Right of left face // Right face 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // Top-Right of left face 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, // Top-Left of left face 1.0f, -1.0f, -1.0f, 0.0f, 1.0f, // Bottom-Left of left face 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, // Bottom-Right of left face }; // std::vector<uint32_t> indices = { // 0, 1, 2, 3, 0, 5, 6, 0, 8, 3, 8, // 0, 0, 2, 5, 6, 1, 0, 2, 1, 6, 21, // 8, 3, 8, 21, 6, 21, 3, 5, 21, 5, 2, 21, 2, 6 // }; std::vector<uint32_t> indices = { 0+0, 1+0, 2+0, 3+0, 2+0, 0+0, 0+4, 1+4, 2+4, 3+4, 2+4, 0+4, 0+8, 1+8, 2+8, 3+8, 2+8, 0+8, 0+12, 1+12, 2+12, 3+12, 2+12, 0+12, 0+16, 1+16, 2+16, 3+16, 2+16, 0+16, 0+20, 1+20, 2+20, 3+20, 2+20, 0+20 }; std::vector<Vertex> vertices; vertices.reserve(24); for (int i = 0; i < 24; ++i) { Vertex v; v.x = g_vertex_buffer_data[i * 5 + 0] * radius + cx; v.y = g_vertex_buffer_data[i * 5 + 1] * radius + cy; v.z = g_vertex_buffer_data[i * 5 + 2] * radius + cz; v.s = g_vertex_buffer_data[i * 5 + 3]; v.t = g_vertex_buffer_data[i * 5 + 4]; vertices.push_back(v); } return new Mesh(vertices, indices); } Mesh* sphere(const float cx, const float cy, const float cz, const float radius) { const float t = (1.0 + sqrt(5.0)) / 2.0 * radius; Vertex points[12]; points[0].x = -radius + cx; points[0].y = t + cy; points[0].z = 0 + cz; points[1].x = radius + cx; points[1].y = t + cy; points[1].z = 0 + cz; points[2].x = -radius + cx; points[2].y = -t + cy; points[2].z = 0 + cz; points[3].x = radius + cx; points[3].y = -t + cy; points[3].z = 0 + cz; points[4].x = 0 + cx; points[4].y = -radius + cy; points[4].z = t + cz; points[5].x = 0 + cx; points[5].y = radius + cy; points[5].z = t + cz; points[6].x = 0 + cx; points[6].y = -radius + cy; points[6].z = -t + cz; points[7].x = 0 + cx; points[7].y = radius + cy; points[7].z = -t + cz; points[8].x = t + cx; points[8].y = 0 + cy; points[8].z = -radius + cz; points[9].x = t + cx; points[9].y = 0 + cy; points[9].z = radius + cz; points[10].x = -t + cx; points[10].y = 0 + cy; points[10].z = -radius + cz; points[11].x = -t + cx; points[11].y = 0 + cy; points[11].z = radius + cz; std::vector<Vertex> vertices; vertices.reserve(60); vertices.push_back(Vertex(points[0])); vertices.push_back(Vertex(points[11])); vertices.push_back(Vertex(points[5])); vertices.push_back(Vertex(points[0])); vertices.push_back(Vertex(points[5])); vertices.push_back(Vertex(points[1])); vertices.push_back(Vertex(points[0])); vertices.push_back(Vertex(points[1])); vertices.push_back(Vertex(points[7])); vertices.push_back(Vertex(points[0])); vertices.push_back(Vertex(points[7])); vertices.push_back(Vertex(points[10])); vertices.push_back(Vertex(points[0])); vertices.push_back(Vertex(points[10])); vertices.push_back(Vertex(points[11])); vertices.push_back(Vertex(points[1])); vertices.push_back(Vertex(points[5])); vertices.push_back(Vertex(points[9])); vertices.push_back(Vertex(points[5])); vertices.push_back(Vertex(points[11])); vertices.push_back(Vertex(points[4])); vertices.push_back(Vertex(points[11])); vertices.push_back(Vertex(points[10])); vertices.push_back(Vertex(points[2])); vertices.push_back(Vertex(points[10])); vertices.push_back(Vertex(points[7])); vertices.push_back(Vertex(points[6])); vertices.push_back(Vertex(points[7])); vertices.push_back(Vertex(points[1])); vertices.push_back(Vertex(points[8])); vertices.push_back(Vertex(points[3])); vertices.push_back(Vertex(points[9])); vertices.push_back(Vertex(points[4])); vertices.push_back(Vertex(points[3])); vertices.push_back(Vertex(points[4])); vertices.push_back(Vertex(points[2])); vertices.push_back(Vertex(points[3])); vertices.push_back(Vertex(points[2])); vertices.push_back(Vertex(points[6])); vertices.push_back(Vertex(points[3])); vertices.push_back(Vertex(points[6])); vertices.push_back(Vertex(points[8])); vertices.push_back(Vertex(points[3])); vertices.push_back(Vertex(points[8])); vertices.push_back(Vertex(points[9])); vertices.push_back(Vertex(points[4])); vertices.push_back(Vertex(points[9])); vertices.push_back(Vertex(points[5])); vertices.push_back(Vertex(points[2])); vertices.push_back(Vertex(points[4])); vertices.push_back(Vertex(points[11])); vertices.push_back(Vertex(points[6])); vertices.push_back(Vertex(points[2])); vertices.push_back(Vertex(points[10])); vertices.push_back(Vertex(points[8])); vertices.push_back(Vertex(points[6])); vertices.push_back(Vertex(points[7])); vertices.push_back(Vertex(points[9])); vertices.push_back(Vertex(points[8])); vertices.push_back(Vertex(points[1])); std::vector<uint32_t> indices = { 0, 1, 2, 0, 2, 5, 0, 5, 8, 0, 8, 11, 0, 11, 1, 5, 2, 17, 2, 1, 20, 1, 11, 23, 11, 8, 26, 8, 5, 29, 30, 17, 20, 30, 20, 23, 30, 23, 26, 30, 26, 29, 30, 29, 17, 20, 17, 2, 23, 20, 1, 26, 23, 11, 29, 26, 8, 17, 29, 5 }; return new Mesh(vertices, indices); } void polygon(GL& gl, const float* xCoords, const float* yCoords, const float* zCoords, uint32_t count) { const float x = xCoords[0]; const float y = yCoords[0]; const float z = zCoords[0]; Vertex *vertices = new Vertex[(count - 2) * 3]; uint32_t vertexIndex = 0; for (uint32_t i = 1; i < count - 1; i++) { vertices[vertexIndex].x = x; vertices[vertexIndex].y = y; vertices[vertexIndex].z = z; vertexIndex++; vertices[vertexIndex].x = xCoords[i]; vertices[vertexIndex].y = yCoords[i]; vertices[vertexIndex].z = zCoords[i]; vertexIndex++; vertices[vertexIndex].x = xCoords[i+1]; vertices[vertexIndex].y = yCoords[i+1]; vertices[vertexIndex].z = zCoords[i+1]; vertexIndex++; } gl.bindTexture(gl.getDefaultTexture()); gl.triangles(vertices, vertexIndex); delete[] vertices; } void line(GL& gl, const float x1, const float y1, const float z1, const float x2, const float y2, const float z2) { Vertex vertices[2]; vertices[0].x = x1; vertices[0].y = y1; vertices[0].z = z1; vertices[1].x = x2; vertices[1].y = y2; vertices[1].z = z2; gl.bindTexture(gl.getDefaultTexture()); gl.lines(vertices, 2); } }
#include "graphics/3d_primitives.h" #include <cmath> #include <numeric> namespace demoloop { Mesh* cube(const float cx, const float cy, const float cz, const float radius) { static const GLfloat g_vertex_buffer_data[] = { // Top face 1.0f, 1.0f, -1.0f , 1.0f, 0.0f, // Top-right of top face -1.0f, 1.0f, -1.0f , 0.0f, 0.0f, // Top-left of top face -1.0f, 1.0f, 1.0f , 0.0f, 1.0f, // Bottom-left of top face 1.0f, 1.0f, 1.0f , 1.0f, 1.0f, // Bottom-right of top face // Bottom face 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, // Top-right of bottom face -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, // Top-left of bottom face -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, // Bottom-left of bottom face 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, // Bottom-right of bottom face // Front face 1.0f, 1.0f, 1.0f , 1.0f, 0.0f, // Top-Right of front face -1.0f, 1.0f, 1.0f , 0.0f, 0.0f, // Top-left of front face -1.0f, -1.0f, 1.0f , 0.0f, 1.0f, // Bottom-left of front face 1.0f, -1.0f, 1.0f , 1.0f, 1.0f, // Bottom-right of front face // Back face -1.0f, 1.0f, -1.0f, 1.0f, 0.0f, // Top-Right of back face 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, // Top-Left of back face 1.0f, -1.0f, -1.0f, 0.0f, 1.0f, // Bottom-Left of back face -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, // Bottom-Right of back face // Left face -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // Top-Right of left face -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, // Top-Left of left face -1.0f, -1.0f, -1.0f, 0.0f, 1.0f, // Bottom-Left of left face -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, // Bottom-Right of left face // Right face 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // Top-Left of left face 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, // Top-Right of left face 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, // Bottom-Right of left face 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, // Bottom-Left of left face }; std::vector<uint32_t> indices = { 0+0, 1+0, 2+0, 0+0, 2+0, 3+0, 0+4, 1+4, 2+4, 0+4, 2+4, 3+4, 0+8, 1+8, 2+8, 0+8, 2+8, 3+8, 0+12, 1+12, 2+12, 0+12, 2+12, 3+12, 0+16, 1+16, 2+16, 0+16, 2+16, 3+16, 2+20, 1+20, 0+20, 3+20, 2+20, 0+20 }; std::vector<Vertex> vertices; vertices.reserve(24); for (int i = 0; i < 24; ++i) { Vertex v; v.x = g_vertex_buffer_data[i * 5 + 0] * radius + cx; v.y = g_vertex_buffer_data[i * 5 + 1] * radius + cy; v.z = g_vertex_buffer_data[i * 5 + 2] * radius + cz; v.s = g_vertex_buffer_data[i * 5 + 3]; v.t = g_vertex_buffer_data[i * 5 + 4]; vertices.push_back(v); } return new Mesh(vertices, indices); } Mesh* sphere(const float cx, const float cy, const float cz, const float radius) { const float t = (1.0 + sqrt(5.0)) / 2.0 * radius; Vertex points[12]; points[0].x = -radius + cx; points[0].y = t + cy; points[0].z = 0 + cz; points[1].x = radius + cx; points[1].y = t + cy; points[1].z = 0 + cz; points[2].x = -radius + cx; points[2].y = -t + cy; points[2].z = 0 + cz; points[3].x = radius + cx; points[3].y = -t + cy; points[3].z = 0 + cz; points[4].x = 0 + cx; points[4].y = -radius + cy; points[4].z = t + cz; points[5].x = 0 + cx; points[5].y = radius + cy; points[5].z = t + cz; points[6].x = 0 + cx; points[6].y = -radius + cy; points[6].z = -t + cz; points[7].x = 0 + cx; points[7].y = radius + cy; points[7].z = -t + cz; points[8].x = t + cx; points[8].y = 0 + cy; points[8].z = -radius + cz; points[9].x = t + cx; points[9].y = 0 + cy; points[9].z = radius + cz; points[10].x = -t + cx; points[10].y = 0 + cy; points[10].z = -radius + cz; points[11].x = -t + cx; points[11].y = 0 + cy; points[11].z = radius + cz; std::vector<Vertex> vertices; vertices.reserve(60); vertices.push_back(Vertex(points[0])); vertices.push_back(Vertex(points[11])); vertices.push_back(Vertex(points[5])); vertices.push_back(Vertex(points[0])); vertices.push_back(Vertex(points[5])); vertices.push_back(Vertex(points[1])); vertices.push_back(Vertex(points[0])); vertices.push_back(Vertex(points[1])); vertices.push_back(Vertex(points[7])); vertices.push_back(Vertex(points[0])); vertices.push_back(Vertex(points[7])); vertices.push_back(Vertex(points[10])); vertices.push_back(Vertex(points[0])); vertices.push_back(Vertex(points[10])); vertices.push_back(Vertex(points[11])); vertices.push_back(Vertex(points[1])); vertices.push_back(Vertex(points[5])); vertices.push_back(Vertex(points[9])); vertices.push_back(Vertex(points[5])); vertices.push_back(Vertex(points[11])); vertices.push_back(Vertex(points[4])); vertices.push_back(Vertex(points[11])); vertices.push_back(Vertex(points[10])); vertices.push_back(Vertex(points[2])); vertices.push_back(Vertex(points[10])); vertices.push_back(Vertex(points[7])); vertices.push_back(Vertex(points[6])); vertices.push_back(Vertex(points[7])); vertices.push_back(Vertex(points[1])); vertices.push_back(Vertex(points[8])); vertices.push_back(Vertex(points[3])); vertices.push_back(Vertex(points[9])); vertices.push_back(Vertex(points[4])); vertices.push_back(Vertex(points[3])); vertices.push_back(Vertex(points[4])); vertices.push_back(Vertex(points[2])); vertices.push_back(Vertex(points[3])); vertices.push_back(Vertex(points[2])); vertices.push_back(Vertex(points[6])); vertices.push_back(Vertex(points[3])); vertices.push_back(Vertex(points[6])); vertices.push_back(Vertex(points[8])); vertices.push_back(Vertex(points[3])); vertices.push_back(Vertex(points[8])); vertices.push_back(Vertex(points[9])); vertices.push_back(Vertex(points[4])); vertices.push_back(Vertex(points[9])); vertices.push_back(Vertex(points[5])); vertices.push_back(Vertex(points[2])); vertices.push_back(Vertex(points[4])); vertices.push_back(Vertex(points[11])); vertices.push_back(Vertex(points[6])); vertices.push_back(Vertex(points[2])); vertices.push_back(Vertex(points[10])); vertices.push_back(Vertex(points[8])); vertices.push_back(Vertex(points[6])); vertices.push_back(Vertex(points[7])); vertices.push_back(Vertex(points[9])); vertices.push_back(Vertex(points[8])); vertices.push_back(Vertex(points[1])); std::vector<uint32_t> indices = { 0, 1, 2, 0, 2, 5, 0, 5, 8, 0, 8, 11, 0, 11, 1, 5, 2, 17, 2, 1, 20, 1, 11, 23, 11, 8, 26, 8, 5, 29, 30, 17, 20, 30, 20, 23, 30, 23, 26, 30, 26, 29, 30, 29, 17, 20, 17, 2, 23, 20, 1, 26, 23, 11, 29, 26, 8, 17, 29, 5 }; return new Mesh(vertices, indices); } void polygon(GL& gl, const float* xCoords, const float* yCoords, const float* zCoords, uint32_t count) { const float x = xCoords[0]; const float y = yCoords[0]; const float z = zCoords[0]; Vertex *vertices = new Vertex[(count - 2) * 3]; uint32_t vertexIndex = 0; for (uint32_t i = 1; i < count - 1; i++) { vertices[vertexIndex].x = x; vertices[vertexIndex].y = y; vertices[vertexIndex].z = z; vertexIndex++; vertices[vertexIndex].x = xCoords[i]; vertices[vertexIndex].y = yCoords[i]; vertices[vertexIndex].z = zCoords[i]; vertexIndex++; vertices[vertexIndex].x = xCoords[i+1]; vertices[vertexIndex].y = yCoords[i+1]; vertices[vertexIndex].z = zCoords[i+1]; vertexIndex++; } gl.bindTexture(gl.getDefaultTexture()); gl.triangles(vertices, vertexIndex); delete[] vertices; } void line(GL& gl, const float x1, const float y1, const float z1, const float x2, const float y2, const float z2) { Vertex vertices[2]; vertices[0].x = x1; vertices[0].y = y1; vertices[0].z = z1; vertices[1].x = x2; vertices[1].y = y2; vertices[1].z = z2; gl.bindTexture(gl.getDefaultTexture()); gl.lines(vertices, 2); } }
fix cube winding and right face orientation
fix cube winding and right face orientation
C++
mit
TannerRogalsky/Demoloops,TannerRogalsky/Demoloops,TannerRogalsky/Demoloops,TannerRogalsky/Demoloops
8968c453416296d6d3a461cfb3d420cd1d3d869c
src/main/resources/main/includes/Camera.hpp
src/main/resources/main/includes/Camera.hpp
/* * This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT) * * Copyright (c) 2018 Grégory Van den Borre * * More infos available: https://www.yildiz-games.be * * 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. */ #ifndef CAMERA_H #define CAMERA_H #include <vector> #include <Ogre.h> #include "stdafx.h" #include "AbstractCameraListener.hpp" #include "RayProvider.hpp" #include "HelperLogics.hpp" #include "Node.hpp" #include "AbstractMovable.hpp" namespace yz { /** *@author Grégory Van den Borre */ class Camera : public AbstractMovable, RayProvider { public: Camera(Ogre::Camera* cam); Ogre::Vector3 getPoint(const Ogre::Vector3& pos, const Ogre::Real x, const Ogre::Real y); Ogre::Ray getRay(const Ogre::Real x, const Ogre::Real y); inline void setAspectRatio(const Ogre::Real ratio) { LOG_FUNCTION this->camera->setAspectRatio(ratio); } inline void setNearClipDistance(const Ogre::Real dist) { LOG_FUNCTION this->camera->setNearClipDistance(dist); } inline void setFarClipDistance(const Ogre::Real dist) { LOG_FUNCTION this->camera->setFarClipDistance(dist); } inline void addListener(yz::AbstractCameraListener* l) { LOG_FUNCTION this->listenerList.push_back(l); } inline void enableRenderingDistance() { LOG_FUNCTION this->camera->setUseRenderingDistance(true); } /** * Remove a listener from the list and call its destructor. * @param l Listener to remove. */ inline void removeListener(yz::AbstractCameraListener* l) { LOG_FUNCTION this->listenerList.erase(std::remove(this->listenerList.begin(), this->listenerList.end(), l)); delete l; } std::string getName() const { LOG_FUNCTION return this->camera->getName(); } inline bool isVisible(const Ogre::Real x, const Ogre::Real y, const Ogre::Real z) { LOG_FUNCTION return this->camera->isVisible(Ogre::Vector3(x, y, z)); } inline void forceListenersUpdate() { LOG_FUNCTION this->updateListeners(); } void updateListeners(); inline Ogre::Camera* getCamera() const{ LOG_FUNCTION return this->camera; } Ogre::Vector3 getPosition() const { LOG_FUNCTION return this->camera->getParentSceneNode()->getPosition(); } inline void detachFromParent() { LOG_FUNCTION this->camera->detachFromParent(); } Ogre::MovableObject* getMovableObject() { LOG_FUNCTION return this->camera; } inline static yz::Camera* get(const POINTER pointer) { LOG_FUNCTION return reinterpret_cast<yz::Camera*>(pointer); } private: static yz::Id* ID_WORLD; std::vector<yz::AbstractCameraListener*> listenerList; Ogre::Camera* camera; }; } #endif
/* * This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT) * * Copyright (c) 2018 Grégory Van den Borre * * More infos available: https://www.yildiz-games.be * * 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. */ #ifndef CAMERA_H #define CAMERA_H #include <vector> #include <Ogre.h> #include "stdafx.h" #include "AbstractCameraListener.hpp" #include "RayProvider.hpp" #include "HelperLogics.hpp" #include "Node.hpp" #include "AbstractMovable.hpp" namespace yz { /** *@author Grégory Van den Borre */ class Camera : public AbstractMovable, public RayProvider { public: Camera(Ogre::Camera* cam); Ogre::Vector3 getPoint(const Ogre::Vector3& pos, const Ogre::Real x, const Ogre::Real y); Ogre::Ray getRay(const Ogre::Real x, const Ogre::Real y); inline void setAspectRatio(const Ogre::Real ratio) { LOG_FUNCTION this->camera->setAspectRatio(ratio); } inline void setNearClipDistance(const Ogre::Real dist) { LOG_FUNCTION this->camera->setNearClipDistance(dist); } inline void setFarClipDistance(const Ogre::Real dist) { LOG_FUNCTION this->camera->setFarClipDistance(dist); } inline void addListener(yz::AbstractCameraListener* l) { LOG_FUNCTION this->listenerList.push_back(l); } inline void enableRenderingDistance() { LOG_FUNCTION this->camera->setUseRenderingDistance(true); } /** * Remove a listener from the list and call its destructor. * @param l Listener to remove. */ inline void removeListener(yz::AbstractCameraListener* l) { LOG_FUNCTION this->listenerList.erase(std::remove(this->listenerList.begin(), this->listenerList.end(), l)); delete l; } std::string getName() const { LOG_FUNCTION return this->camera->getName(); } inline bool isVisible(const Ogre::Real x, const Ogre::Real y, const Ogre::Real z) { LOG_FUNCTION return this->camera->isVisible(Ogre::Vector3(x, y, z)); } inline void forceListenersUpdate() { LOG_FUNCTION this->updateListeners(); } void updateListeners(); inline Ogre::Camera* getCamera() const{ LOG_FUNCTION return this->camera; } Ogre::Vector3 getPosition() const { LOG_FUNCTION return this->camera->getParentSceneNode()->getPosition(); } inline void detachFromParent() { LOG_FUNCTION this->camera->detachFromParent(); } Ogre::MovableObject* getMovableObject() { LOG_FUNCTION return this->camera; } inline static yz::Camera* get(const POINTER pointer) { LOG_FUNCTION return reinterpret_cast<yz::Camera*>(pointer); } private: static yz::Id* ID_WORLD; std::vector<yz::AbstractCameraListener*> listenerList; Ogre::Camera* camera; }; } #endif
Add query.
[YE-0] Add query.
C++
mit
yildiz-online/module-graphic-ogre,yildiz-online/module-graphic-ogre,yildiz-online/module-graphic-ogre
b2e4f6d366fb06eae3cdad0af80e4a01b0c31074
src/view/consolebotview.hpp
src/view/consolebotview.hpp
#ifndef CONSOLEBOTVIEW_HPP_ #define CONSOLEBOTVIEW_HPP_ #include "ioview.hpp" class ConsoleBotView: public IoView { protected: void outputGeneral() const; void typeError_impl() const; void indexError_impl() const; void finish_impl(bool check_fail, int score, int steps_number) const; void sendHelpMessage_impl() const; }; #endif
#ifndef CONSOLEBOTVIEW_HPP_ #define CONSOLEBOTVIEW_HPP_ #include "ioview.hpp" class ConsoleBotView: public IoView { protected: void outputGeneral() const; void typeError_impl() const; void indexError_impl() const; void finish_impl(bool check_fail, int score, int steps_number) const; void sendHelpMessage_impl() const; }; #endif
Apply astyle
Apply astyle
C++
mit
zer0main/bin_game_mvc
a6b03c051f9f62771978f8621e7d82ebd1aadd2d
lib/lsan/lit_tests/TestCases/use_tls_dynamic.cc
lib/lsan/lit_tests/TestCases/use_tls_dynamic.cc
// Test that dynamically allocated TLS space is included in the root set. // RUN: LSAN_BASE="report_objects=1:use_stacks=0:use_registers=0" // RUN: %clangxx %p/SharedLibs/huge_tls_lib_so.cc -fPIC -shared -o %t-so.so // RUN: %clangxx_lsan %s -o %t // RUN: LSAN_OPTIONS=$LSAN_BASE:"use_tls=0" not %t 2>&1 | FileCheck %s // RUN: LSAN_OPTIONS=$LSAN_BASE:"use_tls=1" %t 2>&1 // RUN: LSAN_OPTIONS="" %t 2>&1 #include <assert.h> #include <dlfcn.h> #include <stdio.h> #include <stdlib.h> #include <string> int main(int argc, char *argv[]) { std::string path = std::string(argv[0]) + "-so.so"; void *handle = dlopen(path.c_str(), RTLD_LAZY); assert(handle != 0); typedef void **(* store_t)(void *p); store_t StoreToTLS = (store_t)dlsym(handle, "StoreToTLS"); assert(dlerror() == 0); void *p = malloc(1337); void **p_in_tls = StoreToTLS(p); assert(*p_in_tls == p); fprintf(stderr, "Test alloc: %p.\n", p); return 0; } // CHECK: Test alloc: [[ADDR:.*]]. // CHECK: leaked 1337 byte object at [[ADDR]] // CHECK: LeakSanitizer: detected memory leaks // CHECK: SUMMARY: LeakSanitizer:
// Test that dynamically allocated TLS space is included in the root set. // RUN: LSAN_BASE="report_objects=1:use_stacks=0:use_registers=0" // RUN: %clangxx %p/SharedLibs/huge_tls_lib_so.cc -fPIC -shared -o %t-so.so // RUN: %clangxx_lsan %s -o %t // RUN: LSAN_OPTIONS=$LSAN_BASE:"use_tls=0" not %t 2>&1 | FileCheck %s // RUN: LSAN_OPTIONS=$LSAN_BASE:"use_tls=1" %t 2>&1 // RUN: LSAN_OPTIONS="" %t 2>&1 #include <assert.h> #include <dlfcn.h> #include <stdio.h> #include <stdlib.h> #include <string> int main(int argc, char *argv[]) { std::string path = std::string(argv[0]) + "-so.so"; void *handle = dlopen(path.c_str(), RTLD_LAZY); assert(handle != 0); typedef void **(* store_t)(void *p); store_t StoreToTLS = (store_t)dlsym(handle, "StoreToTLS"); assert(dlerror() == 0); void *p = malloc(1337); void **p_in_tls = StoreToTLS(p); assert(*p_in_tls == p); fprintf(stderr, "Test alloc: %p.\n", p); return 0; } // CHECK: Test alloc: [[ADDR:.*]]. // CHECK: leaked 1337 byte object at [[ADDR]] // CHECK: LeakSanitizer: detected memory leaks // CHECK: dl-tls.c // CHECK: SUMMARY: LeakSanitizer:
Check that dynamic linker library is properly symbolized
LSan: Check that dynamic linker library is properly symbolized git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@189347 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
1314b2139f77351ef5189803951f9aaab766a936
src/operator/slice_channel.cc
src/operator/slice_channel.cc
/*! * Copyright (c) 2015 by Contributors * \file slice_channel.cc * \brief * \author Bing Xu */ #include "./slice_channel-inl.h" namespace mxnet { namespace op { template<> Operator* CreateOp<cpu>(SliceChannelParam param, int dtype) { Operator* op = nullptr; MSHADOW_TYPE_SWITCH(dtype, DType, { op = new SliceChannelOp<cpu, DType>(param); }) return op; } Operator* SliceChannelProp::CreateOperatorEx(Context ctx, std::vector<TShape>* in_shape, std::vector<int>* in_type) const { DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0]); } DMLC_REGISTER_PARAMETER(SliceChannelParam); MXNET_REGISTER_OP_PROPERTY(SliceChannel, SliceChannelProp) .describe(R"code(Split an array along a particular axis into multiple sub-arrays. Assume the input array has shape ``(d_0, ..., d_n)`` and we slice it into *m* (``num_outputs=m``) subarrays along axis *k*, then we will obtain a list of *m* arrays with each of which has shape ``(d_0, ..., d_k/m, ..., d_n)``. For example:: x = [[1, 2], [3, 4], [5, 6], [7, 8]] // 4x2 array y = split(x, axis=0, num_outputs=4) // a list of 4 arrays y[0] = [[ 1., 2.]] // 1x2 array z = split(x, axis=0, num_outputs=2) // a list of 2 arrays z[0] = [[ 1., 2.], [ 3., 4.]] When setting optional argument ``squeeze_axis=1``, then the *k*-dimension will be removed from the shape if it becomes 1:: y = split(x, axis=0, num_outputs=4, squeeze_axis=1) y[0] = [ 1., 2.] // (2,) vector )code" ADD_FILELINE) .set_return_type("NDArray-or-Symbol[]") .add_arguments(SliceChannelParam::__FIELDS__()); NNVM_REGISTER_OP(SliceChannel).add_alias("split"); } // namespace op } // namespace mxnet
/*! * Copyright (c) 2015 by Contributors * \file slice_channel.cc * \brief * \author Bing Xu */ #include "./slice_channel-inl.h" namespace mxnet { namespace op { template<> Operator* CreateOp<cpu>(SliceChannelParam param, int dtype) { Operator* op = nullptr; MSHADOW_TYPE_SWITCH(dtype, DType, { op = new SliceChannelOp<cpu, DType>(param); }) return op; } Operator* SliceChannelProp::CreateOperatorEx(Context ctx, std::vector<TShape>* in_shape, std::vector<int>* in_type) const { DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0]); } DMLC_REGISTER_PARAMETER(SliceChannelParam); MXNET_REGISTER_OP_PROPERTY(SliceChannel, SliceChannelProp) .describe(R"code(Split an array along a particular axis into multiple sub-arrays. Assume the input array has shape ``(d_0, ..., d_n)`` and we slice it into *m* (``num_outputs=m``) subarrays along axis *k*, then we will obtain a list of *m* arrays with each of which has shape ``(d_0, ..., d_k/m, ..., d_n)``. For example:: x = [[1, 2], [3, 4], [5, 6], [7, 8]] // 4x2 array y = split(x, axis=0, num_outputs=4) // a list of 4 arrays y[0] = [[ 1., 2.]] // 1x2 array z = split(x, axis=0, num_outputs=2) // a list of 2 arrays z[0] = [[ 1., 2.], [ 3., 4.]] When setting optional argument ``squeeze_axis=1``, then the *k*-dimension will be removed from the shape if it becomes 1:: y = split(x, axis=0, num_outputs=4, squeeze_axis=1) y[0] = [ 1., 2.] // (2,) vector )code" ADD_FILELINE) .set_return_type("NDArray-or-Symbol[]") .add_argument("data", "NDArray-or-Symbol", "Source input") .add_arguments(SliceChannelParam::__FIELDS__()); NNVM_REGISTER_OP(SliceChannel).add_alias("split"); } // namespace op } // namespace mxnet
fix ndarray split
fix ndarray split
C++
apache-2.0
sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet
8abb75bc6173c82a3153fd358735219b3355b539
lib/Target/TargetSubtargetInfo.cpp
lib/Target/TargetSubtargetInfo.cpp
//===-- TargetSubtargetInfo.cpp - General Target Information ---------------==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file describes the general parts of a Subtarget. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Target/TargetSubtargetInfo.h" using namespace llvm; //--------------------------------------------------------------------------- // TargetSubtargetInfo Class // TargetSubtargetInfo::TargetSubtargetInfo() {} TargetSubtargetInfo::~TargetSubtargetInfo() {} // Temporary option to compare overall performance change when moving from the // SD scheduler to the MachineScheduler pass pipeline. It should be removed // before 3.4. The normal way to enable/disable the MachineScheduling pass // itself is by using -enable-misched. For targets that already use MI sched // (via MySubTarget::enableMachineScheduler()) -misched-bench=false negates the // subtarget hook. static cl::opt<bool> BenchMachineSched("misched-bench", cl::Hidden, cl::desc("Migrate from the target's default SD scheduler to MI scheduler")); bool TargetSubtargetInfo::useMachineScheduler() const { if (BenchMachineSched.getNumOccurrences()) return BenchMachineSched; return enableMachineScheduler(); } bool TargetSubtargetInfo::enableMachineScheduler() const { return false; } bool TargetSubtargetInfo::enablePostRAScheduler( CodeGenOpt::Level OptLevel, AntiDepBreakMode& Mode, RegClassVector& CriticalPathRCs) const { Mode = ANTIDEP_NONE; CriticalPathRCs.clear(); return false; } bool TargetSubtargetInfo::useAA() const { return false; }
//===-- TargetSubtargetInfo.cpp - General Target Information ---------------==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file describes the general parts of a Subtarget. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Target/TargetSubtargetInfo.h" using namespace llvm; //--------------------------------------------------------------------------- // TargetSubtargetInfo Class // TargetSubtargetInfo::TargetSubtargetInfo() {} TargetSubtargetInfo::~TargetSubtargetInfo() {} // Temporary option to compare overall performance change when moving from the // SD scheduler to the MachineScheduler pass pipeline. This is convenient for // benchmarking during the transition from SD to MI scheduling. Once armv7 makes // the switch, it should go away. The normal way to enable/disable the // MachineScheduling pass itself is by using -enable-misched. For targets that // already use MI sched (via MySubTarget::enableMachineScheduler()) // -misched-bench=false negates the subtarget hook. static cl::opt<bool> BenchMachineSched("misched-bench", cl::Hidden, cl::desc("Migrate from the target's default SD scheduler to MI scheduler")); bool TargetSubtargetInfo::useMachineScheduler() const { if (BenchMachineSched.getNumOccurrences()) return BenchMachineSched; return enableMachineScheduler(); } bool TargetSubtargetInfo::enableMachineScheduler() const { return false; } bool TargetSubtargetInfo::enablePostRAScheduler( CodeGenOpt::Level OptLevel, AntiDepBreakMode& Mode, RegClassVector& CriticalPathRCs) const { Mode = ANTIDEP_NONE; CriticalPathRCs.clear(); return false; } bool TargetSubtargetInfo::useAA() const { return false; }
Update an embarassing out-of-date comment.
Update an embarassing out-of-date comment. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@208137 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,dslab-epfl/asap,llvm-mirror/llvm
0fbfea3e8b6af379c3c84a1bb780e939c0cbfe27
ext/embed/sunscraperthread.cpp
ext/embed/sunscraperthread.cpp
#include <QApplication> #include <QtDebug> #include "sunscraperthread.h" #include "sunscraperworker.h" #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) pthread_t SunscraperThread::m_thread; #endif extern void qt_set_current_thread_to_main_thread(); void SunscraperThread::invoke() { #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) pthread_create(&m_thread, NULL, &SunscraperThread::thread_routine, NULL); #endif } void *SunscraperThread::thread_routine(void *) { /* Better error messages. */ int argc = 1; char *argv[] = { (char*) "Sunscraper", NULL}; /* Why (char*)? Because argv can (theoretically) be modified. * * But Qt won't do that with argv[0]. I know, trust me. */ qt_set_current_thread_to_main_thread(); QApplication app(argc, argv); app.setApplicationName("Sunscraper-Embed"); SunscraperWorker::unlock(); /* * The magic value 42 means we want exit from the loop. * E.g. alerts from within the page may exit the loop with value 0. */ while(app.exec() != 42); /* Our host application exits. */ return NULL; } void SunscraperThread::commitSuicide() { QApplication::exit(42); #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) pthread_join(m_thread, NULL); #endif }
#include <QApplication> #include <qnamespace.h> #include <QtDebug> #include "sunscraperthread.h" #include "sunscraperworker.h" #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) pthread_t SunscraperThread::m_thread; #endif extern void qt_set_current_thread_to_main_thread(); void SunscraperThread::invoke() { #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) pthread_create(&m_thread, NULL, &SunscraperThread::thread_routine, NULL); #endif } void *SunscraperThread::thread_routine(void *) { /* Better error messages. */ int argc = 1; char *argv[] = { (char*) "Sunscraper", NULL}; /* Why (char*)? Because argv can (theoretically) be modified. * * But Qt won't do that with argv[0]. I know, trust me. */ QInternal::callFunction(QInternal::SetCurrentThreadToMainThread, NULL); QApplication app(argc, argv); app.setApplicationName("Sunscraper-Embed"); SunscraperWorker::unlock(); /* * The magic value 42 means we want exit from the loop. * E.g. alerts from within the page may exit the loop with value 0. */ while(app.exec() != 42); /* Our host application exits. */ return NULL; } void SunscraperThread::commitSuicide() { QApplication::exit(42); #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) pthread_join(m_thread, NULL); #endif }
Use a proper way to call undocumented functions.
Use a proper way to call undocumented functions.
C++
mit
inossidabile/sunscraper,inossidabile/sunscraper
c4a02a17991a857ad01d9ed61aad7da167faec4e
taglib/ogg/xiphcomment.cpp
taglib/ogg/xiphcomment.cpp
/*************************************************************************** copyright : (C) 2002 - 2008 by Scott Wheeler email : [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 Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tbytevector.h> #include <tdebug.h> #include <flacpicture.h> #include <xiphcomment.h> #include <tpropertymap.h> using namespace TagLib; typedef List<FLAC::Picture*> PictureList; class Ogg::XiphComment::XiphCommentPrivate { public: FieldListMap fieldListMap; String vendorID; String commentField; PictureList pictureList; }; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// Ogg::XiphComment::XiphComment() : TagLib::Tag() { d = new XiphCommentPrivate; } Ogg::XiphComment::XiphComment(const ByteVector &data) : TagLib::Tag() { d = new XiphCommentPrivate; parse(data); } Ogg::XiphComment::~XiphComment() { removePictures(); delete d; } String Ogg::XiphComment::title() const { if(d->fieldListMap["TITLE"].isEmpty()) return String::null; return d->fieldListMap["TITLE"].toString(); } String Ogg::XiphComment::artist() const { if(d->fieldListMap["ARTIST"].isEmpty()) return String::null; return d->fieldListMap["ARTIST"].toString(); } String Ogg::XiphComment::album() const { if(d->fieldListMap["ALBUM"].isEmpty()) return String::null; return d->fieldListMap["ALBUM"].toString(); } String Ogg::XiphComment::comment() const { if(!d->fieldListMap["DESCRIPTION"].isEmpty()) { d->commentField = "DESCRIPTION"; return d->fieldListMap["DESCRIPTION"].toString(); } if(!d->fieldListMap["COMMENT"].isEmpty()) { d->commentField = "COMMENT"; return d->fieldListMap["COMMENT"].toString(); } return String::null; } String Ogg::XiphComment::genre() const { if(d->fieldListMap["GENRE"].isEmpty()) return String::null; return d->fieldListMap["GENRE"].toString(); } TagLib::uint Ogg::XiphComment::year() const { if(!d->fieldListMap["DATE"].isEmpty()) return d->fieldListMap["DATE"].front().toInt(); if(!d->fieldListMap["YEAR"].isEmpty()) return d->fieldListMap["YEAR"].front().toInt(); return 0; } TagLib::uint Ogg::XiphComment::track() const { if(!d->fieldListMap["TRACKNUMBER"].isEmpty()) return d->fieldListMap["TRACKNUMBER"].front().toInt(); if(!d->fieldListMap["TRACKNUM"].isEmpty()) return d->fieldListMap["TRACKNUM"].front().toInt(); return 0; } void Ogg::XiphComment::setTitle(const String &s) { addField("TITLE", s); } void Ogg::XiphComment::setArtist(const String &s) { addField("ARTIST", s); } void Ogg::XiphComment::setAlbum(const String &s) { addField("ALBUM", s); } void Ogg::XiphComment::setComment(const String &s) { addField(d->commentField.isEmpty() ? "DESCRIPTION" : d->commentField, s); } void Ogg::XiphComment::setGenre(const String &s) { addField("GENRE", s); } void Ogg::XiphComment::setYear(uint i) { removeField("YEAR"); if(i == 0) removeField("DATE"); else addField("DATE", String::number(i)); } void Ogg::XiphComment::setTrack(uint i) { removeField("TRACKNUM"); if(i == 0) removeField("TRACKNUMBER"); else addField("TRACKNUMBER", String::number(i)); } bool Ogg::XiphComment::isEmpty() const { FieldListMap::ConstIterator it = d->fieldListMap.begin(); for(; it != d->fieldListMap.end(); ++it) if(!(*it).second.isEmpty()) return false; return true; } TagLib::uint Ogg::XiphComment::fieldCount() const { uint count = 0; FieldListMap::ConstIterator it = d->fieldListMap.begin(); for(; it != d->fieldListMap.end(); ++it) count += (*it).second.size(); count += d->pictureList.size(); return count; } const Ogg::FieldListMap &Ogg::XiphComment::fieldListMap() const { return d->fieldListMap; } PropertyMap Ogg::XiphComment::properties() const { return d->fieldListMap; } PropertyMap Ogg::XiphComment::setProperties(const PropertyMap &properties) { // check which keys are to be deleted StringList toRemove; for(FieldListMap::ConstIterator it = d->fieldListMap.begin(); it != d->fieldListMap.end(); ++it) if (!properties.contains(it->first)) toRemove.append(it->first); for(StringList::ConstIterator it = toRemove.begin(); it != toRemove.end(); ++it) removeField(*it); // now go through keys in \a properties and check that the values match those in the xiph comment PropertyMap invalid; PropertyMap::ConstIterator it = properties.begin(); for(; it != properties.end(); ++it) { if(!checkKey(it->first)) invalid.insert(it->first, it->second); else if(!d->fieldListMap.contains(it->first) || !(it->second == d->fieldListMap[it->first])) { const StringList &sl = it->second; if(sl.size() == 0) // zero size string list -> remove the tag with all values removeField(it->first); else { // replace all strings in the list for the tag StringList::ConstIterator valueIterator = sl.begin(); addField(it->first, *valueIterator, true); ++valueIterator; for(; valueIterator != sl.end(); ++valueIterator) addField(it->first, *valueIterator, false); } } } return invalid; } bool Ogg::XiphComment::checkKey(const String &key) { if(key.size() < 1) return false; for(String::ConstIterator it = key.begin(); it != key.end(); it++) // forbid non-printable, non-ascii, '=' (#61) and '~' (#126) if (*it < 32 || *it >= 128 || *it == 61 || *it == 126) return false; return true; } String Ogg::XiphComment::vendorID() const { return d->vendorID; } void Ogg::XiphComment::addField(const String &key, const String &value, bool replace) { if(replace) removeField(key.upper()); if(!key.isEmpty() && !value.isEmpty()) d->fieldListMap[key.upper()].append(value); } void Ogg::XiphComment::removeField(const String &key, const String &value) { if(!value.isNull()) { StringList::Iterator it = d->fieldListMap[key].begin(); while(it != d->fieldListMap[key].end()) { if(value == *it) it = d->fieldListMap[key].erase(it); else it++; } } else d->fieldListMap.erase(key); } bool Ogg::XiphComment::contains(const String &key) const { return d->fieldListMap.contains(key) && !d->fieldListMap[key].isEmpty(); } void Ogg::XiphComment::removePicture(FLAC::Picture *picture, bool del) { List<FLAC::Picture *>::Iterator it = d->pictureList.find(picture); if(it != d->pictureList.end()) d->pictureList.erase(it); if(del) delete picture; } void Ogg::XiphComment::removePictures() { PictureList newList; for(uint i = 0; i < d->pictureList.size(); i++) { delete d->pictureList[i]; } d->pictureList = newList; } void Ogg::XiphComment::addPicture(FLAC::Picture * picture) { d->pictureList.append(picture); } List<FLAC::Picture *> Ogg::XiphComment::pictureList() { return d->pictureList; } ByteVector Ogg::XiphComment::render() const { return render(true); } ByteVector Ogg::XiphComment::render(bool addFramingBit) const { ByteVector data; // Add the vendor ID length and the vendor ID. It's important to use the // length of the data(String::UTF8) rather than the length of the the string // since this is UTF8 text and there may be more characters in the data than // in the UTF16 string. ByteVector vendorData = d->vendorID.data(String::UTF8); data.append(ByteVector::fromUInt(vendorData.size(), false)); data.append(vendorData); // Add the number of fields. data.append(ByteVector::fromUInt(fieldCount(), false)); // Iterate over the the field lists. Our iterator returns a // std::pair<String, StringList> where the first String is the field name and // the StringList is the values associated with that field. FieldListMap::ConstIterator it = d->fieldListMap.begin(); for(; it != d->fieldListMap.end(); ++it) { // And now iterate over the values of the current list. String fieldName = (*it).first; StringList values = (*it).second; StringList::ConstIterator valuesIt = values.begin(); for(; valuesIt != values.end(); ++valuesIt) { ByteVector fieldData = fieldName.data(String::UTF8); fieldData.append('='); fieldData.append((*valuesIt).data(String::UTF8)); data.append(ByteVector::fromUInt(fieldData.size(), false)); data.append(fieldData); } } for(PictureList::ConstIterator it = d->pictureList.begin(); it != d->pictureList.end(); ++it) { ByteVector picture = (*it)->render().toBase64(); data.append(ByteVector::fromUInt(picture.size()+23,false)); data.append("METADATA_BLOCK_PICTURE="); data.append(picture); } // Append the "framing bit". if(addFramingBit) data.append(char(1)); return data; } //////////////////////////////////////////////////////////////////////////////// // protected members //////////////////////////////////////////////////////////////////////////////// void Ogg::XiphComment::parse(const ByteVector &data) { // The first thing in the comment data is the vendor ID length, followed by a // UTF8 string with the vendor ID. uint pos = 0; const uint vendorLength = data.toUInt(0, false); pos += 4; d->vendorID = String(data.mid(pos, vendorLength), String::UTF8); pos += vendorLength; // Next the number of fields in the comment vector. const uint commentFields = data.toUInt(pos, false); pos += 4; if(commentFields > (data.size() - 8) / 4) { return; } for(uint i = 0; i < commentFields; i++) { // Each comment field is in the format "KEY=value" in a UTF8 string and has // 4 bytes before the text starts that gives the length. const uint commentLength = data.toUInt(pos, false); pos += 4; ByteVector entry = data.mid(pos, commentLength); // Don't go past data end pos+=commentLength; if (pos>data.size()) break; // Handle Pictures separately if(entry.startsWith("METADATA_BLOCK_PICTURE=")) { // Decode base64 picture data ByteVector picturedata = ByteVector::fromBase64(entry.mid(23)); if(picturedata.size()==0) { debug("Empty picture data. Discarding content"); continue; } FLAC::Picture * picture = new FLAC::Picture(); if(picture->parse(picturedata)) d->pictureList.append(picture); else debug("Unable to parse METADATA_BLOCK_PICTURE. Discarding content."); } else { // Check for field separator int sep = entry.find('='); if (sep == -1) break; // Parse key and value String key = String(entry.mid(0,sep), String::UTF8); String value = String(entry.mid(sep+1, commentLength-sep), String::UTF8); addField(key, value, false); } } }
/*************************************************************************** copyright : (C) 2002 - 2008 by Scott Wheeler email : [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 Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tbytevector.h> #include <tdebug.h> #include <flacpicture.h> #include <xiphcomment.h> #include <tpropertymap.h> using namespace TagLib; typedef List<FLAC::Picture*> PictureList; class Ogg::XiphComment::XiphCommentPrivate { public: FieldListMap fieldListMap; String vendorID; String commentField; PictureList pictureList; }; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// Ogg::XiphComment::XiphComment() : TagLib::Tag() { d = new XiphCommentPrivate; } Ogg::XiphComment::XiphComment(const ByteVector &data) : TagLib::Tag() { d = new XiphCommentPrivate; parse(data); } Ogg::XiphComment::~XiphComment() { removePictures(); delete d; } String Ogg::XiphComment::title() const { if(d->fieldListMap["TITLE"].isEmpty()) return String::null; return d->fieldListMap["TITLE"].toString(); } String Ogg::XiphComment::artist() const { if(d->fieldListMap["ARTIST"].isEmpty()) return String::null; return d->fieldListMap["ARTIST"].toString(); } String Ogg::XiphComment::album() const { if(d->fieldListMap["ALBUM"].isEmpty()) return String::null; return d->fieldListMap["ALBUM"].toString(); } String Ogg::XiphComment::comment() const { if(!d->fieldListMap["DESCRIPTION"].isEmpty()) { d->commentField = "DESCRIPTION"; return d->fieldListMap["DESCRIPTION"].toString(); } if(!d->fieldListMap["COMMENT"].isEmpty()) { d->commentField = "COMMENT"; return d->fieldListMap["COMMENT"].toString(); } return String::null; } String Ogg::XiphComment::genre() const { if(d->fieldListMap["GENRE"].isEmpty()) return String::null; return d->fieldListMap["GENRE"].toString(); } TagLib::uint Ogg::XiphComment::year() const { if(!d->fieldListMap["DATE"].isEmpty()) return d->fieldListMap["DATE"].front().toInt(); if(!d->fieldListMap["YEAR"].isEmpty()) return d->fieldListMap["YEAR"].front().toInt(); return 0; } TagLib::uint Ogg::XiphComment::track() const { if(!d->fieldListMap["TRACKNUMBER"].isEmpty()) return d->fieldListMap["TRACKNUMBER"].front().toInt(); if(!d->fieldListMap["TRACKNUM"].isEmpty()) return d->fieldListMap["TRACKNUM"].front().toInt(); return 0; } void Ogg::XiphComment::setTitle(const String &s) { addField("TITLE", s); } void Ogg::XiphComment::setArtist(const String &s) { addField("ARTIST", s); } void Ogg::XiphComment::setAlbum(const String &s) { addField("ALBUM", s); } void Ogg::XiphComment::setComment(const String &s) { addField(d->commentField.isEmpty() ? "DESCRIPTION" : d->commentField, s); } void Ogg::XiphComment::setGenre(const String &s) { addField("GENRE", s); } void Ogg::XiphComment::setYear(uint i) { removeField("YEAR"); if(i == 0) removeField("DATE"); else addField("DATE", String::number(i)); } void Ogg::XiphComment::setTrack(uint i) { removeField("TRACKNUM"); if(i == 0) removeField("TRACKNUMBER"); else addField("TRACKNUMBER", String::number(i)); } bool Ogg::XiphComment::isEmpty() const { FieldListMap::ConstIterator it = d->fieldListMap.begin(); for(; it != d->fieldListMap.end(); ++it) if(!(*it).second.isEmpty()) return false; return true; } TagLib::uint Ogg::XiphComment::fieldCount() const { uint count = 0; FieldListMap::ConstIterator it = d->fieldListMap.begin(); for(; it != d->fieldListMap.end(); ++it) count += (*it).second.size(); count += d->pictureList.size(); return count; } const Ogg::FieldListMap &Ogg::XiphComment::fieldListMap() const { return d->fieldListMap; } PropertyMap Ogg::XiphComment::properties() const { return d->fieldListMap; } PropertyMap Ogg::XiphComment::setProperties(const PropertyMap &properties) { // check which keys are to be deleted StringList toRemove; for(FieldListMap::ConstIterator it = d->fieldListMap.begin(); it != d->fieldListMap.end(); ++it) if (!properties.contains(it->first)) toRemove.append(it->first); for(StringList::ConstIterator it = toRemove.begin(); it != toRemove.end(); ++it) removeField(*it); // now go through keys in \a properties and check that the values match those in the xiph comment PropertyMap invalid; PropertyMap::ConstIterator it = properties.begin(); for(; it != properties.end(); ++it) { if(!checkKey(it->first)) invalid.insert(it->first, it->second); else if(!d->fieldListMap.contains(it->first) || !(it->second == d->fieldListMap[it->first])) { const StringList &sl = it->second; if(sl.size() == 0) // zero size string list -> remove the tag with all values removeField(it->first); else { // replace all strings in the list for the tag StringList::ConstIterator valueIterator = sl.begin(); addField(it->first, *valueIterator, true); ++valueIterator; for(; valueIterator != sl.end(); ++valueIterator) addField(it->first, *valueIterator, false); } } } return invalid; } bool Ogg::XiphComment::checkKey(const String &key) { if(key.size() < 1) return false; for(String::ConstIterator it = key.begin(); it != key.end(); it++) // forbid non-printable, non-ascii, '=' (#61) and '~' (#126) if (*it < 32 || *it >= 128 || *it == 61 || *it == 126) return false; return true; } String Ogg::XiphComment::vendorID() const { return d->vendorID; } void Ogg::XiphComment::addField(const String &key, const String &value, bool replace) { if(replace) removeField(key.upper()); if(!key.isEmpty() && !value.isEmpty()) d->fieldListMap[key.upper()].append(value); } void Ogg::XiphComment::removeField(const String &key, const String &value) { if(!value.isNull()) { StringList::Iterator it = d->fieldListMap[key].begin(); while(it != d->fieldListMap[key].end()) { if(value == *it) it = d->fieldListMap[key].erase(it); else it++; } } else d->fieldListMap.erase(key); } bool Ogg::XiphComment::contains(const String &key) const { return d->fieldListMap.contains(key) && !d->fieldListMap[key].isEmpty(); } void Ogg::XiphComment::removePicture(FLAC::Picture *picture, bool del) { List<FLAC::Picture *>::Iterator it = d->pictureList.find(picture); if(it != d->pictureList.end()) d->pictureList.erase(it); if(del) delete picture; } void Ogg::XiphComment::removePictures() { PictureList newList; for(uint i = 0; i < d->pictureList.size(); i++) { delete d->pictureList[i]; } d->pictureList = newList; } void Ogg::XiphComment::addPicture(FLAC::Picture * picture) { d->pictureList.append(picture); } List<FLAC::Picture *> Ogg::XiphComment::pictureList() { return d->pictureList; } ByteVector Ogg::XiphComment::render() const { return render(true); } ByteVector Ogg::XiphComment::render(bool addFramingBit) const { ByteVector data; // Add the vendor ID length and the vendor ID. It's important to use the // length of the data(String::UTF8) rather than the length of the the string // since this is UTF8 text and there may be more characters in the data than // in the UTF16 string. ByteVector vendorData = d->vendorID.data(String::UTF8); data.append(ByteVector::fromUInt(vendorData.size(), false)); data.append(vendorData); // Add the number of fields. data.append(ByteVector::fromUInt(fieldCount(), false)); // Iterate over the the field lists. Our iterator returns a // std::pair<String, StringList> where the first String is the field name and // the StringList is the values associated with that field. FieldListMap::ConstIterator it = d->fieldListMap.begin(); for(; it != d->fieldListMap.end(); ++it) { // And now iterate over the values of the current list. String fieldName = (*it).first; StringList values = (*it).second; StringList::ConstIterator valuesIt = values.begin(); for(; valuesIt != values.end(); ++valuesIt) { ByteVector fieldData = fieldName.data(String::UTF8); fieldData.append('='); fieldData.append((*valuesIt).data(String::UTF8)); data.append(ByteVector::fromUInt(fieldData.size(), false)); data.append(fieldData); } } for(PictureList::ConstIterator it = d->pictureList.begin(); it != d->pictureList.end(); ++it) { ByteVector picture = (*it)->render().toBase64(); data.append(ByteVector::fromUInt(picture.size()+23,false)); data.append("METADATA_BLOCK_PICTURE="); data.append(picture); } // Append the "framing bit". if(addFramingBit) data.append(char(1)); return data; } //////////////////////////////////////////////////////////////////////////////// // protected members //////////////////////////////////////////////////////////////////////////////// void Ogg::XiphComment::parse(const ByteVector &data) { // The first thing in the comment data is the vendor ID length, followed by a // UTF8 string with the vendor ID. uint pos = 0; const uint vendorLength = data.toUInt(0, false); pos += 4; d->vendorID = String(data.mid(pos, vendorLength), String::UTF8); pos += vendorLength; // Next the number of fields in the comment vector. const uint commentFields = data.toUInt(pos, false); pos += 4; if(commentFields > (data.size() - 8) / 4) { return; } for(uint i = 0; i < commentFields; i++) { // Each comment field is in the format "KEY=value" in a UTF8 string and has // 4 bytes before the text starts that gives the length. const uint commentLength = data.toUInt(pos, false); pos += 4; ByteVector entry = data.mid(pos, commentLength); // Don't go past data end pos+=commentLength; if (pos>data.size()) break; // Handle Pictures separately if(entry.startsWith("METADATA_BLOCK_PICTURE=")) { // Decode base64 picture data ByteVector picturedata = ByteVector::fromBase64(entry.mid(23)); if(picturedata.size()==0) { debug("Empty picture data. Discarding content"); continue; } FLAC::Picture * picture = new FLAC::Picture(); if(picture->parse(picturedata)) d->pictureList.append(picture); else debug("Unable to parse METADATA_BLOCK_PICTURE. Discarding content."); } else { // Check for field separator int sep = entry.find('='); if (sep == -1) break; // Parse key and value String key = String(entry.mid(0,sep), String::UTF8); String value = String(entry.mid(sep+1), String::UTF8); addField(key, value, false); } } }
remove redundant size specificier in mid usage
remove redundant size specificier in mid usage
C++
lgpl-2.1
taglib/taglib,black78/taglib,TsudaKageyu/taglib,TsudaKageyu/taglib,Distrotech/taglib,taglib/taglib,Distrotech/taglib,black78/taglib,taglib/taglib,black78/taglib,Distrotech/taglib,TsudaKageyu/taglib
35e3b9f6238038ec286e87ca6ab4bc06f4c0183f
src/MainApp.cpp
src/MainApp.cpp
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "StdAfx.h" #include "MainApp.h" #include "controls\MyDialogEx.h" #include "dialogs\MainDlg.h" #include "utilities\Utilities.h" CMainApp mainApp; BEGIN_MESSAGE_MAP(CMainApp, CWinAppEx) ON_COMMAND(ID_HELP, CWinAppEx::OnHelp) END_MESSAGE_MAP() CMainApp::CMainApp() { } CString CMainApp::CombinePath(CString szPath, CString szFile) { CString szOutputFile = szFile; if (szPath.GetLength() >= 1) { auto cLast = szPath[szPath.GetLength() - 1]; if ((cLast == '\\') || (cLast == '/')) szOutputFile = szPath + szOutputFile; else szOutputFile = szPath + _T("\\") + szOutputFile; } return szOutputFile; } BOOL CMainApp::InitInstance() { INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinAppEx::InitInstance(); AfxEnableControlContainer(); InitShellManager(); this->m_bIsPortable = PathFileExists(::GetExeFilePath() + "BatchEncoder.portable") == TRUE ? true : false; if (this->m_bIsPortable == true) { this->szSettingsPath = ::GetExeFilePath(); this->szFormatsPath = this->szSettingsPath + _T("formats"); this->szLanguagesPath = this->szSettingsPath + _T("lang"); this->szProgressPath = this->szSettingsPath + _T("progress"); this->szToolsPath = this->szSettingsPath + _T("tools"); try { ::CreateDirectory(this->szFormatsPath, NULL); ::CreateDirectory(this->szLanguagesPath, NULL); ::CreateDirectory(this->szProgressPath, NULL); ::CreateDirectory(this->szToolsPath, NULL); } catch (...) {} this->szOptionsFile = this->szSettingsPath + _T("BatchEncoder.options"); this->szFormatsFile = this->szSettingsPath + _T("BatchEncoder.formats"); this->szItemsFile = this->szSettingsPath + _T("BatchEncoder.items"); this->szToolsFile = this->szSettingsPath + _T("BatchEncoder.tools"); } else { CString szConfigDir = _T("BatchEncoder"); this->szSettingsPath = GetSettingsFilePath(_T(""), szConfigDir); this->szFormatsPath = GetSettingsFilePath(_T(""), szConfigDir + _T("\\formats")); this->szLanguagesPath = GetSettingsFilePath(_T(""), szConfigDir + _T("\\lang")); this->szProgressPath = GetSettingsFilePath(_T(""), szConfigDir + _T("\\progress")); this->szToolsPath = GetSettingsFilePath(_T(""), szConfigDir + _T("\\tools")); try { ::CreateDirectory(szSettingsPath, NULL); ::CreateDirectory(szFormatsPath, NULL); ::CreateDirectory(szLanguagesPath, NULL); ::CreateDirectory(szProgressPath, NULL); ::CreateDirectory(szToolsPath, NULL); } catch (...) {} this->szOptionsFile = ::GetSettingsFilePath(_T("BatchEncoder.options"), szConfigDir); this->szFormatsFile = ::GetSettingsFilePath(_T("BatchEncoder.formats"), szConfigDir); this->szItemsFile = ::GetSettingsFilePath(_T("BatchEncoder.items"), szConfigDir); this->szToolsFile = ::GetSettingsFilePath(_T("BatchEncoder.tools"), szConfigDir); } CMainDlg dlg; m_pMainWnd = &dlg; dlg.DoModal(); return FALSE; }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "StdAfx.h" #include "MainApp.h" #include "controls\MyDialogEx.h" #include "dialogs\MainDlg.h" #include "utilities\Utilities.h" CMainApp mainApp; BEGIN_MESSAGE_MAP(CMainApp, CWinAppEx) ON_COMMAND(ID_HELP, CWinAppEx::OnHelp) END_MESSAGE_MAP() CMainApp::CMainApp() { } CString CMainApp::CombinePath(CString szPath, CString szFile) { CString szOutputFile = szFile; if (szPath.GetLength() >= 1) { auto cLast = szPath[szPath.GetLength() - 1]; if ((cLast == '\\') || (cLast == '/')) szOutputFile = szPath + szOutputFile; else szOutputFile = szPath + _T("\\") + szOutputFile; } return szOutputFile; } BOOL CMainApp::InitInstance() { INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinAppEx::InitInstance(); AfxEnableControlContainer(); InitShellManager(); this->m_bIsPortable = PathFileExists(::GetExeFilePath() + "BatchEncoder.portable") == TRUE ? true : false; if (this->m_bIsPortable == true) { this->szSettingsPath = ::GetExeFilePath(); this->szFormatsPath = this->szSettingsPath + _T("formats"); this->szLanguagesPath = this->szSettingsPath + _T("lang"); this->szProgressPath = this->szSettingsPath + _T("progress"); this->szToolsPath = this->szSettingsPath + _T("tools"); try { ::CreateDirectory(this->szFormatsPath, NULL); ::CreateDirectory(this->szLanguagesPath, NULL); ::CreateDirectory(this->szProgressPath, NULL); ::CreateDirectory(this->szToolsPath, NULL); } catch (...) {} this->szOptionsFile = this->szSettingsPath + _T("BatchEncoder.options"); this->szFormatsFile = this->szSettingsPath + _T("BatchEncoder.formats"); this->szItemsFile = this->szSettingsPath + _T("BatchEncoder.items"); this->szToolsFile = this->szSettingsPath + _T("BatchEncoder.tools"); } else { CString szConfigDir = _T("BatchEncoder"); this->szSettingsPath = GetSettingsFilePath(_T(""), szConfigDir); this->szFormatsPath = GetSettingsFilePath(_T(""), szConfigDir + _T("\\formats")); this->szLanguagesPath = GetSettingsFilePath(_T(""), szConfigDir + _T("\\lang")); this->szProgressPath = GetSettingsFilePath(_T(""), szConfigDir + _T("\\progress")); this->szToolsPath = GetSettingsFilePath(_T(""), szConfigDir + _T("\\tools")); try { ::CreateDirectory(szSettingsPath, NULL); ::CreateDirectory(szFormatsPath, NULL); ::CreateDirectory(szLanguagesPath, NULL); ::CreateDirectory(szProgressPath, NULL); ::CreateDirectory(szToolsPath, NULL); } catch (...) {} this->szOptionsFile = ::GetSettingsFilePath(_T("BatchEncoder.options"), szConfigDir); this->szFormatsFile = ::GetSettingsFilePath(_T("BatchEncoder.formats"), szConfigDir); this->szItemsFile = ::GetSettingsFilePath(_T("BatchEncoder.items"), szConfigDir); this->szToolsFile = ::GetSettingsFilePath(_T("BatchEncoder.tools"), szConfigDir); } CMainDlg dlg; m_pMainWnd = &dlg; dlg.DoModal(); return FALSE; }
Update MainApp.cpp
Update MainApp.cpp
C++
mit
wieslawsoltes/BatchEncoder,wieslawsoltes/BatchEncoder,wieslawsoltes/BatchEncoder,wieslawsoltes/BatchEncoder
a5a4f1040291ee63083292d50643c0f8c00b2002
src/Mapper1.cpp
src/Mapper1.cpp
#include <cstdint> #include <CartMemory.h> #include <Mapper1.h> Mapper1::Mapper1(CartMemory mem) : Mapper(mem) { updateBankAddresses(); } uint8_t Mapper1::readPrg(uint16_t addr) { if (addr >= 0x8000) { int index = decodePrgRomAddress(addr); return cartMemory.prg[index]; } else if (addr >= 0x6000) { int index = addr % 0x2000; return cartMemory.ram[index]; } else { return 0; } } void Mapper1::writePrg(uint16_t addr, uint8_t value) { if (addr >= 0x8000) { if (value & 0x80) { shiftRegister = 0x10; } else { if (shiftRegister & 1) { shiftRegister >>= 1; shiftRegister |= ((value << 4) & 0x10); loadRegister(addr, value); shiftRegister = 0x10; } else { shiftRegister >>= 1; shiftRegister |= ((value << 4) & 0x10); } } } else if (addr >= 0x6000) { int index = addr % 0x2000; cartMemory.ram[index] = value; } } uint8_t Mapper1::readChr(uint16_t addr) { int index = decodeChrRomAddress(addr); return cartMemory.chr[index]; } void Mapper1::writeChr(uint16_t addr, uint8_t value) { if (cartMemory.chrIsRam) { int index = addr % cartMemory.chr.size(); cartMemory.chr[index] = value; } } void Mapper1::loadRegister(uint16_t addr, uint8_t value) { if (addr >= 0xE000) { prgRomBank = value & 0b01111; prgRamDisable = !!(value & 0b10000); } else if (addr >= 0xC000) { chrRomBank1 = value & 0x1F; } else if (addr >= 0xA000) { chrRomBank0 = value & 0x1F; } else if (addr >= 0x8000) { switch(value & 0b00011) { case 0: cartMemory.mirroring = Mirroring::MIRROR_LOWER_BANK; break; case 1: cartMemory.mirroring = Mirroring::MIRROR_UPPER_BANK; break; case 2: cartMemory.mirroring = Mirroring::MIRROR_VERTICAL; break; case 3: cartMemory.mirroring = Mirroring::MIRROR_HORIZONTAL; break; } switch((value & 0b01100) >> 2) { case 0: case 1: prgMode = PrgMode::PRG_32KB; break; case 2: prgMode = PrgMode::PRG_FIX_FIRST_16KB; break; case 3: prgMode = PrgMode::PRG_FIX_LAST_16KB; break; } switch((value & 0b10000) >> 4) { case 0: chrMode = ChrMode::CHR_8KB; break; case 1: chrMode = ChrMode::CHR_4KB; break; } } updateBankAddresses(); } void Mapper1::updateBankAddresses() { switch (prgMode) { case PrgMode::PRG_32KB: prg16kBankAddresses[0] = (prgRomBank & 0xFFFE) * 0x4000; prg16kBankAddresses[1] = (prgRomBank | 1) * 0x4000; break; case PrgMode::PRG_FIX_FIRST_16KB: prg16kBankAddresses[0] = 0; prg16kBankAddresses[1] = prgRomBank * 0x4000; break; case PrgMode::PRG_FIX_LAST_16KB: prg16kBankAddresses[0] = prgRomBank * 0x4000; prg16kBankAddresses[1] = cartMemory.prg.size() - 0x4000; break; } switch(chrMode) { case ChrMode::CHR_8KB: chr4kBankAddresses[0] = (chrRomBank0 & 0xFFFE) * 0x1000; chr4kBankAddresses[1] = (chrRomBank0 | 1) * 0x1000; break; case ChrMode::CHR_4KB: chr4kBankAddresses[0] = chrRomBank0 * 0x1000; chr4kBankAddresses[1] = chrRomBank1 * 0x1000; break; } } int Mapper1::decodePrgRomAddress(uint16_t addr) { int bankNum = (addr & 0x4000) >> 14; int offset = (addr % 0x4000); return prg16kBankAddresses[bankNum] + offset; } int Mapper1::decodeChrRomAddress(uint16_t addr) { int bankNum = (addr & 0x1000) >> 12; int offset = (addr % 0x1000); return chr4kBankAddresses[bankNum] + offset; }
#include <cstdint> #include <CartMemory.h> #include <Mapper1.h> Mapper1::Mapper1(CartMemory mem) : Mapper(mem) { updateBankAddresses(); } uint8_t Mapper1::readPrg(uint16_t addr) { if (addr >= 0x8000) { int index = decodePrgRomAddress(addr); return cartMemory.prg[index]; } else if (addr >= 0x6000) { int index = addr % 0x2000; return cartMemory.ram[index]; } else { return 0; } } void Mapper1::writePrg(uint16_t addr, uint8_t value) { if (addr >= 0x8000) { if (value & 0x80) { shiftRegister = 0x10; } else { if (shiftRegister & 1) { shiftRegister >>= 1; shiftRegister |= ((value << 4) & 0x10); loadRegister(addr, shiftRegister); shiftRegister = 0x10; } else { shiftRegister >>= 1; shiftRegister |= ((value << 4) & 0x10); } } } else if (addr >= 0x6000) { int index = addr % 0x2000; cartMemory.ram[index] = value; } } uint8_t Mapper1::readChr(uint16_t addr) { int index = decodeChrRomAddress(addr); return cartMemory.chr[index]; } void Mapper1::writeChr(uint16_t addr, uint8_t value) { if (cartMemory.chrIsRam) { int index = addr % cartMemory.chr.size(); cartMemory.chr[index] = value; } } void Mapper1::loadRegister(uint16_t addr, uint8_t value) { if (addr >= 0xE000) { prgRomBank = value & 0b01111; prgRamDisable = !!(value & 0b10000); } else if (addr >= 0xC000) { chrRomBank1 = value & 0x1F; } else if (addr >= 0xA000) { chrRomBank0 = value & 0x1F; } else if (addr >= 0x8000) { switch(value & 0b00011) { case 0: cartMemory.mirroring = Mirroring::MIRROR_LOWER_BANK; break; case 1: cartMemory.mirroring = Mirroring::MIRROR_UPPER_BANK; break; case 2: cartMemory.mirroring = Mirroring::MIRROR_VERTICAL; break; case 3: cartMemory.mirroring = Mirroring::MIRROR_HORIZONTAL; break; } switch((value & 0b01100) >> 2) { case 0: case 1: prgMode = PrgMode::PRG_32KB; break; case 2: prgMode = PrgMode::PRG_FIX_FIRST_16KB; break; case 3: prgMode = PrgMode::PRG_FIX_LAST_16KB; break; } switch((value & 0b10000) >> 4) { case 0: chrMode = ChrMode::CHR_8KB; break; case 1: chrMode = ChrMode::CHR_4KB; break; } } updateBankAddresses(); } void Mapper1::updateBankAddresses() { switch (prgMode) { case PrgMode::PRG_32KB: prg16kBankAddresses[0] = (prgRomBank & 0xFFFE) * 0x4000; prg16kBankAddresses[1] = (prgRomBank | 1) * 0x4000; break; case PrgMode::PRG_FIX_FIRST_16KB: prg16kBankAddresses[0] = 0; prg16kBankAddresses[1] = prgRomBank * 0x4000; break; case PrgMode::PRG_FIX_LAST_16KB: prg16kBankAddresses[0] = prgRomBank * 0x4000; prg16kBankAddresses[1] = cartMemory.prg.size() - 0x4000; break; } switch(chrMode) { case ChrMode::CHR_8KB: chr4kBankAddresses[0] = (chrRomBank0 & 0xFFFE) * 0x1000; chr4kBankAddresses[1] = (chrRomBank0 | 1) * 0x1000; break; case ChrMode::CHR_4KB: chr4kBankAddresses[0] = chrRomBank0 * 0x1000; chr4kBankAddresses[1] = chrRomBank1 * 0x1000; break; } } int Mapper1::decodePrgRomAddress(uint16_t addr) { int bankNum = (addr & 0x4000) >> 14; int offset = (addr % 0x4000); return prg16kBankAddresses[bankNum] + offset; } int Mapper1::decodeChrRomAddress(uint16_t addr) { int bankNum = (addr & 0x1000) >> 12; int offset = (addr % 0x1000); return chr4kBankAddresses[bankNum] + offset; }
Fix mapper 1 loading shift register incorrectly
Fix mapper 1 loading shift register incorrectly
C++
mit
scottjcrouch/ScootNES,scottjcrouch/ScootNES,scottjcrouch/ScootNES
4cf48dfe7f0960f4fec005c76ebeb109c864cdd1
include/apollo/class_utility.hpp
include/apollo/class_utility.hpp
#ifndef APOLLO_CLASS_UTILITY_HPP_INCLUDED #define APOLLO_CLASS_UTILITY_HPP_INCLUDED APOLLO_CLASS_UTILITY_HPP_INCLUDED #include <apollo/class.hpp> #include <apollo/create_table.hpp> #include <apollo/function.hpp> namespace apollo { namespace detail { template <typename Cls, typename Parent> class class_creator; template <typename Derived> class basic_classes_creator: public basic_table_setter<Derived> { public: basic_classes_creator(lua_State* L, int table_idx) : basic_table_setter<Derived>(L, table_idx) { } template <typename Cls, typename... Bases, typename K> class_creator<Cls, Derived> cls(K&& key); }; class classes_creator: public basic_classes_creator<classes_creator> { public: classes_creator(lua_State* L, int idx) : basic_classes_creator<classes_creator>(L, idx) { } }; template <typename T, typename Parent=void> class class_creator: public basic_classes_creator<class_creator<T, Parent>> { public: class_creator(lua_State* L, Parent* parent) : basic_classes_creator<class_creator<T, Parent>>(L, lua_gettop(L)) , m_parent(parent) { } ~class_creator() { if (!m_parent) this->pop_table(); } template<typename... Args> class_creator&& ctor(char const* name = "new") { return (*this)(name, get_raw_ctor_wrapper<T, Args...>()); } typename std::add_rvalue_reference<Parent>::type end_cls() { m_parent->end_subtable(); return std::move(*m_parent); // If you get an error about void here, you called end_cls() after // using export_class, but this is only neccessary to end the classes // created by .cls(). } private: Parent* const m_parent; // variant class[es]_creator? }; template <typename Derived> template <typename Cls, typename... Bases, typename K> class_creator<Cls, Derived> basic_classes_creator<Derived>::cls(K&& key) { register_class<Cls, Bases...>(this->m_L); push_class_metatable<Cls>(this->m_L); this->top_subtable(std::forward<K>(key)); return {this->m_L, static_cast<Derived*>(this)}; } } // namespace detail template <typename T> struct converter<detail::class_creator<T>> : public converter<detail::table_setter> {}; inline detail::classes_creator export_classes(lua_State* L, int into = 0) { if (!into) { lua_newtable(L); into = lua_gettop(L); } return detail::classes_creator(L, lua_absindex(L, into)); } template <typename T, typename... Bases> detail::class_creator<T> export_class(lua_State* L) { register_class<T, Bases...>(L); push_class_metatable<T>(L); return detail::class_creator<T>(L, nullptr); } } // namespace apollo #endif // APOLLO_CLASS_UTILITY_HPP_INCLUDED
#ifndef APOLLO_CLASS_UTILITY_HPP_INCLUDED #define APOLLO_CLASS_UTILITY_HPP_INCLUDED APOLLO_CLASS_UTILITY_HPP_INCLUDED #include <apollo/class.hpp> #include <apollo/create_table.hpp> #include <apollo/function.hpp> #include <apollo/implicit_ctor.hpp> namespace apollo { namespace detail { template <typename Cls, typename Parent> class class_creator; template <typename Derived> class basic_classes_creator: public basic_table_setter<Derived> { public: basic_classes_creator(lua_State* L, int table_idx) : basic_table_setter<Derived>(L, table_idx) { } template <typename Cls, typename... Bases, typename K> class_creator<Cls, Derived> cls(K&& key); }; class classes_creator: public basic_classes_creator<classes_creator> { public: classes_creator(lua_State* L, int idx) : basic_classes_creator<classes_creator>(L, idx) { } }; template <typename T, typename Parent=void> class class_creator: public basic_classes_creator<class_creator<T, Parent>> { public: class_creator(lua_State* L, Parent* parent) : basic_classes_creator<class_creator<T, Parent>>(L, lua_gettop(L)) , m_parent(parent) { } ~class_creator() { if (!m_parent) this->pop_table(); } template<typename... Args> class_creator&& ctor(char const* name = "new") { return (*this)(name, get_raw_ctor_wrapper<T, Args...>()); } // Implicit constructors // template<typename... Args> class_creator&& implicit_ctor(char const* name) { implicit_only_ctor<Args...>(); return (*this)(name, get_raw_ctor_wrapper<T, Args...>()); } template<typename F> class_creator&& implicit_ctor_f(char const* name, F f) { implicit_only_ctor_f(f); return (*this)(name, get_raw_ctor_wrapper<T, Args...>()); } template<typename... Args> class_creator&& implicit_only_ctor() { add_implicit_ctor(m_L, &ctor_wrapper<T, Args...>()); return std::move(*this); } template<typename F> class_creator&& implicit_only_ctor_f(F f) { add_implicit_ctor(m_L, f); return std::move(*this); } // Misc // typename std::add_rvalue_reference<Parent>::type end_cls() { m_parent->end_subtable(); return std::move(*m_parent); // If you get an error about void here, you called end_cls() after // using export_class, but this is only neccessary to end the classes // created by .cls(). } private: Parent* const m_parent; // variant class[es]_creator? }; template <typename Derived> template <typename Cls, typename... Bases, typename K> class_creator<Cls, Derived> basic_classes_creator<Derived>::cls(K&& key) { register_class<Cls, Bases...>(this->m_L); push_class_metatable<Cls>(this->m_L); this->top_subtable(std::forward<K>(key)); return {this->m_L, static_cast<Derived*>(this)}; } } // namespace detail template <typename T> struct converter<detail::class_creator<T>> : public converter<detail::table_setter> {}; inline detail::classes_creator export_classes(lua_State* L, int into = 0) { if (!into) { lua_newtable(L); into = lua_gettop(L); } return detail::classes_creator(L, lua_absindex(L, into)); } template <typename T, typename... Bases> detail::class_creator<T> export_class(lua_State* L) { register_class<T, Bases...>(L); push_class_metatable<T>(L); return detail::class_creator<T>(L, nullptr); } } // namespace apollo #endif // APOLLO_CLASS_UTILITY_HPP_INCLUDED
Support implicit ctors in class_utility (untested).
Support implicit ctors in class_utility (untested).
C++
bsd-2-clause
Oberon00/apollo,Oberon00/apollo
d8132df2ded0684a259353030a6241ed8cf49f14
spirv_cpp.cpp
spirv_cpp.cpp
/* * Copyright 2015-2016 ARM Limited * * 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 "spirv_cpp.hpp" using namespace spv; using namespace spirv_cross; using namespace std; void CompilerCPP::emit_buffer_block(const SPIRVariable &var) { auto &type = get<SPIRType>(var.basetype); auto instance_name = to_name(var.self); uint32_t set = meta[var.self].decoration.set; uint32_t binding = meta[var.self].decoration.binding; emit_struct(type); statement("internal::Resource<", type_to_glsl(type), type_to_array_glsl(type), "> ", instance_name, "__;"); statement_no_indent("#define ", instance_name, " __res->", instance_name, "__.get()"); resource_registrations.push_back(join("s.register_resource(", instance_name, "__", ", ", set, ", ", binding, ");")); statement(""); } void CompilerCPP::emit_interface_block(const SPIRVariable &var) { auto &type = get<SPIRType>(var.basetype); const char *qual = var.storage == StorageClassInput ? "StageInput" : "StageOutput"; const char *lowerqual = var.storage == StorageClassInput ? "stage_input" : "stage_output"; auto instance_name = to_name(var.self); uint32_t location = meta[var.self].decoration.location; auto flags = meta[type.self].decoration.decoration_flags; if (flags & (1ull << DecorationBlock)) emit_struct(type); statement("internal::", qual, "<", type_to_glsl(type), type_to_array_glsl(type), "> ", instance_name, "__;"); statement_no_indent("#define ", instance_name, " __res->", instance_name, "__.get()"); resource_registrations.push_back(join("s.register_", lowerqual, "(", instance_name, "__", ", ", location, ");")); statement(""); } void CompilerCPP::emit_shared(const SPIRVariable &var) { auto instance_name = to_name(var.self); statement(variable_decl(var), ";"); statement_no_indent("#define ", instance_name, " __res->", instance_name); } void CompilerCPP::emit_uniform(const SPIRVariable &var) { auto &type = get<SPIRType>(var.basetype); auto instance_name = to_name(var.self); uint32_t set = meta[var.self].decoration.set; uint32_t binding = meta[var.self].decoration.binding; uint32_t location = meta[var.self].decoration.location; if (type.basetype == SPIRType::Image || type.basetype == SPIRType::SampledImage || type.basetype == SPIRType::AtomicCounter) { statement("internal::Resource<", type_to_glsl(type), type_to_array_glsl(type), "> ", instance_name, "__;"); statement_no_indent("#define ", instance_name, " __res->", instance_name, "__.get()"); resource_registrations.push_back(join("s.register_resource(", instance_name, "__", ", ", set, ", ", binding, ");")); } else { statement("internal::UniformConstant<", type_to_glsl(type), type_to_array_glsl(type), "> ", instance_name, "__;"); statement_no_indent("#define ", instance_name, " __res->", instance_name, "__.get()"); resource_registrations.push_back(join("s.register_uniform_constant(", instance_name, "__", ", ", location, ");")); } statement(""); } void CompilerCPP::emit_push_constant_block(const SPIRVariable &var) { auto &type = get<SPIRType>(var.basetype); auto &flags = meta[var.self].decoration.decoration_flags; if ((flags & (1ull << DecorationBinding)) || (flags & (1ull << DecorationDescriptorSet))) throw CompilerError("Push constant blocks cannot be compiled to GLSL with Binding or Set syntax. " "Remap to location with reflection API first or disable these decorations."); emit_struct(type); auto instance_name = to_name(var.self); statement("internal::PushConstant<", type_to_glsl(type), type_to_array_glsl(type), "> ", instance_name, ";"); statement_no_indent("#define ", instance_name, " __res->", instance_name, ".get()"); resource_registrations.push_back(join("s.register_push_constant(", instance_name, "__", ");")); statement(""); } void CompilerCPP::emit_resources() { // Output all basic struct types which are not Block or BufferBlock as these are declared inplace // when such variables are instantiated. for (auto &id : ids) { if (id.get_type() == TypeType) { auto &type = id.get<SPIRType>(); if (type.basetype == SPIRType::Struct && type.array.empty() && !type.pointer && (meta[type.self].decoration.decoration_flags & ((1ull << DecorationBlock) | (1ull << DecorationBufferBlock))) == 0) { emit_struct(type); } } } statement("struct Resources : ", resource_type); begin_scope(); // Output UBOs and SSBOs for (auto &id : ids) { if (id.get_type() == TypeVariable) { auto &var = id.get<SPIRVariable>(); auto &type = get<SPIRType>(var.basetype); if (type.pointer && type.storage == StorageClassUniform && !is_builtin_variable(var) && (meta[type.self].decoration.decoration_flags & ((1ull << DecorationBlock) | (1ull << DecorationBufferBlock)))) { emit_buffer_block(var); } } } // Output push constant blocks for (auto &id : ids) { if (id.get_type() == TypeVariable) { auto &var = id.get<SPIRVariable>(); auto &type = get<SPIRType>(var.basetype); if (type.pointer && type.storage == StorageClassPushConstant) emit_push_constant_block(var); } } // Output in/out interfaces. for (auto &id : ids) { if (id.get_type() == TypeVariable) { auto &var = id.get<SPIRVariable>(); auto &type = get<SPIRType>(var.basetype); if (!is_builtin_variable(var) && !var.remapped_variable && type.pointer && (var.storage == StorageClassInput || var.storage == StorageClassOutput)) { emit_interface_block(var); } } } // Output Uniform Constants (values, samplers, images, etc). for (auto &id : ids) { if (id.get_type() == TypeVariable) { auto &var = id.get<SPIRVariable>(); auto &type = get<SPIRType>(var.basetype); if (!is_builtin_variable(var) && !var.remapped_variable && type.pointer && (type.storage == StorageClassUniformConstant || type.storage == StorageClassAtomicCounter)) { emit_uniform(var); } } } // Global variables. bool emitted = false; for (auto global : global_variables) { auto &var = get<SPIRVariable>(global); if (var.storage == StorageClassWorkgroup) { emit_shared(var); emitted = true; } } if (emitted) statement(""); statement("inline void init(spirv_cross_shader& s)"); begin_scope(); statement(resource_type, "::init(s);"); for (auto &reg : resource_registrations) statement(reg); end_scope(); resource_registrations.clear(); end_scope_decl(); statement(""); statement("Resources* __res;"); if (execution.model == ExecutionModelGLCompute) statement("ComputePrivateResources __priv_res;"); statement(""); // Emit regular globals which are allocated per invocation. emitted = false; for (auto global : global_variables) { auto &var = get<SPIRVariable>(global); if (var.storage == StorageClassPrivate) { if (var.storage == StorageClassWorkgroup) emit_shared(var); else statement(variable_decl(var), ";"); emitted = true; } } if (emitted) statement(""); } string CompilerCPP::compile() { // Do not deal with ES-isms like precision, older extensions and such. options.es = false; options.version = 450; backend.float_literal_suffix = true; backend.uint32_t_literal_suffix = true; backend.basic_int_type = "int32_t"; backend.basic_uint_type = "uint32_t"; backend.swizzle_is_function = true; backend.shared_is_implied = true; uint32_t pass_count = 0; do { if (pass_count >= 2) throw CompilerError("Over 2 compilation loops detected. Must be a bug!"); resource_registrations.clear(); reset(); // Move constructor for this type is broken on GCC 4.9 ... buffer = unique_ptr<ostringstream>(new ostringstream()); emit_header(); emit_resources(); emit_function(get<SPIRFunction>(execution.entry_point), 0); pass_count++; } while (force_recompile); // Match opening scope of emit_header(). end_scope_decl(); // namespace end_scope(); // Emit C entry points emit_c_linkage(); return buffer->str(); } void CompilerCPP::emit_c_linkage() { statement(""); statement("spirv_cross_shader_t* spirv_cross_construct(void)"); begin_scope(); statement("return new ", impl_type, "();"); end_scope(); statement(""); statement("void spirv_cross_destruct(spirv_cross_shader_t *shader)"); begin_scope(); statement("delete static_cast<", impl_type, "*>(shader);"); end_scope(); statement(""); statement("void spirv_cross_invoke(spirv_cross_shader_t *shader)"); begin_scope(); statement("static_cast<", impl_type, "*>(shader)->invoke();"); end_scope(); statement(""); statement("static const struct spirv_cross_interface vtable ="); begin_scope(); statement("spirv_cross_construct,"); statement("spirv_cross_destruct,"); statement("spirv_cross_invoke,"); end_scope_decl(); statement(""); statement("const struct spirv_cross_interface* spirv_cross_get_interface(void)"); begin_scope(); statement("return &vtable;"); end_scope(); } void CompilerCPP::emit_function_prototype(SPIRFunction &func, uint64_t) { local_variables.clear(); string decl; auto &type = get<SPIRType>(func.return_type); decl += "inline "; decl += type_to_glsl(type); decl += " "; if (func.self == execution.entry_point) { decl += "main"; processing_entry_point = true; } else decl += to_name(func.self); decl += "("; for (auto &arg : func.arguments) { add_local_variable(arg.id); decl += argument_decl(arg); if (&arg != &func.arguments.back()) decl += ", "; // Hold a pointer to the parameter so we can invalidate the readonly field if needed. auto *var = maybe_get<SPIRVariable>(arg.id); if (var) var->parameter = &arg; } decl += ")"; statement(decl); } string CompilerCPP::argument_decl(const SPIRFunction::Parameter &arg) { auto &type = expression_type(arg.id); bool constref = !type.pointer || arg.write_count == 0; auto &var = get<SPIRVariable>(arg.id); return join(constref ? "const " : "", type_to_glsl(type), "& ", to_name(var.self), type_to_array_glsl(type)); } void CompilerCPP::emit_header() { statement("// This C++ shader is autogenerated by spirv-cross."); statement("#include \"spirv_cross/internal_interface.hpp\""); statement("#include \"spirv_cross/external_interface.h\""); statement("#include <stdint.h>"); statement(""); statement("using namespace spirv_cross;"); statement("using namespace glm;"); statement(""); statement("namespace Impl"); begin_scope(); switch (execution.model) { case ExecutionModelGeometry: case ExecutionModelTessellationControl: case ExecutionModelTessellationEvaluation: case ExecutionModelGLCompute: case ExecutionModelFragment: case ExecutionModelVertex: statement("struct Shader"); begin_scope(); break; default: throw CompilerError("Unsupported execution model."); } switch (execution.model) { case ExecutionModelGeometry: impl_type = "GeometryShader<Impl::Shader, Impl::Shader::Resources>"; resource_type = "GeometryResources"; break; case ExecutionModelVertex: impl_type = "VertexShader<Impl::Shader, Impl::Shader::Resources>"; resource_type = "VertexResources"; break; case ExecutionModelFragment: impl_type = "FragmentShader<Impl::Shader, Impl::Shader::Resources>"; resource_type = "FragmentResources"; break; case ExecutionModelGLCompute: impl_type = join("ComputeShader<Impl::Shader, Impl::Shader::Resources, ", execution.workgroup_size.x, ", ", execution.workgroup_size.y, ", ", execution.workgroup_size.z, ">"); resource_type = "ComputeResources"; break; case ExecutionModelTessellationControl: impl_type = "TessControlShader<Impl::Shader, Impl::Shader::Resources>"; resource_type = "TessControlResources"; break; case ExecutionModelTessellationEvaluation: impl_type = "TessEvaluationShader<Impl::Shader, Impl::Shader::Resources>"; resource_type = "TessEvaluationResources"; break; default: throw CompilerError("Unsupported execution model."); } }
/* * Copyright 2015-2016 ARM Limited * * 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 "spirv_cpp.hpp" using namespace spv; using namespace spirv_cross; using namespace std; void CompilerCPP::emit_buffer_block(const SPIRVariable &var) { auto &type = get<SPIRType>(var.basetype); auto instance_name = to_name(var.self); uint32_t set = meta[var.self].decoration.set; uint32_t binding = meta[var.self].decoration.binding; emit_struct(type); statement("internal::Resource<", type_to_glsl(type), type_to_array_glsl(type), "> ", instance_name, "__;"); statement_no_indent("#define ", instance_name, " __res->", instance_name, "__.get()"); resource_registrations.push_back(join("s.register_resource(", instance_name, "__", ", ", set, ", ", binding, ");")); statement(""); } void CompilerCPP::emit_interface_block(const SPIRVariable &var) { auto &type = get<SPIRType>(var.basetype); const char *qual = var.storage == StorageClassInput ? "StageInput" : "StageOutput"; const char *lowerqual = var.storage == StorageClassInput ? "stage_input" : "stage_output"; auto instance_name = to_name(var.self); uint32_t location = meta[var.self].decoration.location; auto flags = meta[type.self].decoration.decoration_flags; if (flags & (1ull << DecorationBlock)) emit_struct(type); statement("internal::", qual, "<", type_to_glsl(type), type_to_array_glsl(type), "> ", instance_name, "__;"); statement_no_indent("#define ", instance_name, " __res->", instance_name, "__.get()"); resource_registrations.push_back(join("s.register_", lowerqual, "(", instance_name, "__", ", ", location, ");")); statement(""); } void CompilerCPP::emit_shared(const SPIRVariable &var) { auto instance_name = to_name(var.self); statement(variable_decl(var), ";"); statement_no_indent("#define ", instance_name, " __res->", instance_name); } void CompilerCPP::emit_uniform(const SPIRVariable &var) { auto &type = get<SPIRType>(var.basetype); auto instance_name = to_name(var.self); uint32_t set = meta[var.self].decoration.set; uint32_t binding = meta[var.self].decoration.binding; uint32_t location = meta[var.self].decoration.location; if (type.basetype == SPIRType::Image || type.basetype == SPIRType::SampledImage || type.basetype == SPIRType::AtomicCounter) { statement("internal::Resource<", type_to_glsl(type), type_to_array_glsl(type), "> ", instance_name, "__;"); statement_no_indent("#define ", instance_name, " __res->", instance_name, "__.get()"); resource_registrations.push_back(join("s.register_resource(", instance_name, "__", ", ", set, ", ", binding, ");")); } else { statement("internal::UniformConstant<", type_to_glsl(type), type_to_array_glsl(type), "> ", instance_name, "__;"); statement_no_indent("#define ", instance_name, " __res->", instance_name, "__.get()"); resource_registrations.push_back(join("s.register_uniform_constant(", instance_name, "__", ", ", location, ");")); } statement(""); } void CompilerCPP::emit_push_constant_block(const SPIRVariable &var) { auto &type = get<SPIRType>(var.basetype); auto &flags = meta[var.self].decoration.decoration_flags; if ((flags & (1ull << DecorationBinding)) || (flags & (1ull << DecorationDescriptorSet))) throw CompilerError("Push constant blocks cannot be compiled to GLSL with Binding or Set syntax. " "Remap to location with reflection API first or disable these decorations."); emit_struct(type); auto instance_name = to_name(var.self); statement("internal::PushConstant<", type_to_glsl(type), type_to_array_glsl(type), "> ", instance_name, ";"); statement_no_indent("#define ", instance_name, " __res->", instance_name, ".get()"); resource_registrations.push_back(join("s.register_push_constant(", instance_name, "__", ");")); statement(""); } void CompilerCPP::emit_resources() { // Output all basic struct types which are not Block or BufferBlock as these are declared inplace // when such variables are instantiated. for (auto &id : ids) { if (id.get_type() == TypeType) { auto &type = id.get<SPIRType>(); if (type.basetype == SPIRType::Struct && type.array.empty() && !type.pointer && (meta[type.self].decoration.decoration_flags & ((1ull << DecorationBlock) | (1ull << DecorationBufferBlock))) == 0) { emit_struct(type); } } } statement("struct Resources : ", resource_type); begin_scope(); // Output UBOs and SSBOs for (auto &id : ids) { if (id.get_type() == TypeVariable) { auto &var = id.get<SPIRVariable>(); auto &type = get<SPIRType>(var.basetype); if (type.pointer && type.storage == StorageClassUniform && !is_builtin_variable(var) && (meta[type.self].decoration.decoration_flags & ((1ull << DecorationBlock) | (1ull << DecorationBufferBlock)))) { emit_buffer_block(var); } } } // Output push constant blocks for (auto &id : ids) { if (id.get_type() == TypeVariable) { auto &var = id.get<SPIRVariable>(); auto &type = get<SPIRType>(var.basetype); if (type.pointer && type.storage == StorageClassPushConstant) emit_push_constant_block(var); } } // Output in/out interfaces. for (auto &id : ids) { if (id.get_type() == TypeVariable) { auto &var = id.get<SPIRVariable>(); auto &type = get<SPIRType>(var.basetype); if (!is_builtin_variable(var) && !var.remapped_variable && type.pointer && (var.storage == StorageClassInput || var.storage == StorageClassOutput)) { emit_interface_block(var); } } } // Output Uniform Constants (values, samplers, images, etc). for (auto &id : ids) { if (id.get_type() == TypeVariable) { auto &var = id.get<SPIRVariable>(); auto &type = get<SPIRType>(var.basetype); if (!is_builtin_variable(var) && !var.remapped_variable && type.pointer && (type.storage == StorageClassUniformConstant || type.storage == StorageClassAtomicCounter)) { emit_uniform(var); } } } // Global variables. bool emitted = false; for (auto global : global_variables) { auto &var = get<SPIRVariable>(global); if (var.storage == StorageClassWorkgroup) { emit_shared(var); emitted = true; } } if (emitted) statement(""); statement("inline void init(spirv_cross_shader& s)"); begin_scope(); statement(resource_type, "::init(s);"); for (auto &reg : resource_registrations) statement(reg); end_scope(); resource_registrations.clear(); end_scope_decl(); statement(""); statement("Resources* __res;"); if (execution.model == ExecutionModelGLCompute) statement("ComputePrivateResources __priv_res;"); statement(""); // Emit regular globals which are allocated per invocation. emitted = false; for (auto global : global_variables) { auto &var = get<SPIRVariable>(global); if (var.storage == StorageClassPrivate) { if (var.storage == StorageClassWorkgroup) emit_shared(var); else statement(variable_decl(var), ";"); emitted = true; } } if (emitted) statement(""); } string CompilerCPP::compile() { // Do not deal with ES-isms like precision, older extensions and such. options.es = false; options.version = 450; backend.float_literal_suffix = true; backend.uint32_t_literal_suffix = true; backend.basic_int_type = "int32_t"; backend.basic_uint_type = "uint32_t"; backend.swizzle_is_function = true; backend.shared_is_implied = true; uint32_t pass_count = 0; do { if (pass_count >= 3) throw CompilerError("Over 3 compilation loops detected. Must be a bug!"); resource_registrations.clear(); reset(); // Move constructor for this type is broken on GCC 4.9 ... buffer = unique_ptr<ostringstream>(new ostringstream()); emit_header(); emit_resources(); emit_function(get<SPIRFunction>(execution.entry_point), 0); pass_count++; } while (force_recompile); // Match opening scope of emit_header(). end_scope_decl(); // namespace end_scope(); // Emit C entry points emit_c_linkage(); return buffer->str(); } void CompilerCPP::emit_c_linkage() { statement(""); statement("spirv_cross_shader_t* spirv_cross_construct(void)"); begin_scope(); statement("return new ", impl_type, "();"); end_scope(); statement(""); statement("void spirv_cross_destruct(spirv_cross_shader_t *shader)"); begin_scope(); statement("delete static_cast<", impl_type, "*>(shader);"); end_scope(); statement(""); statement("void spirv_cross_invoke(spirv_cross_shader_t *shader)"); begin_scope(); statement("static_cast<", impl_type, "*>(shader)->invoke();"); end_scope(); statement(""); statement("static const struct spirv_cross_interface vtable ="); begin_scope(); statement("spirv_cross_construct,"); statement("spirv_cross_destruct,"); statement("spirv_cross_invoke,"); end_scope_decl(); statement(""); statement("const struct spirv_cross_interface* spirv_cross_get_interface(void)"); begin_scope(); statement("return &vtable;"); end_scope(); } void CompilerCPP::emit_function_prototype(SPIRFunction &func, uint64_t) { local_variables.clear(); string decl; auto &type = get<SPIRType>(func.return_type); decl += "inline "; decl += type_to_glsl(type); decl += " "; if (func.self == execution.entry_point) { decl += "main"; processing_entry_point = true; } else decl += to_name(func.self); decl += "("; for (auto &arg : func.arguments) { add_local_variable(arg.id); decl += argument_decl(arg); if (&arg != &func.arguments.back()) decl += ", "; // Hold a pointer to the parameter so we can invalidate the readonly field if needed. auto *var = maybe_get<SPIRVariable>(arg.id); if (var) var->parameter = &arg; } decl += ")"; statement(decl); } string CompilerCPP::argument_decl(const SPIRFunction::Parameter &arg) { auto &type = expression_type(arg.id); bool constref = !type.pointer || arg.write_count == 0; auto &var = get<SPIRVariable>(arg.id); return join(constref ? "const " : "", type_to_glsl(type), "& ", to_name(var.self), type_to_array_glsl(type)); } void CompilerCPP::emit_header() { statement("// This C++ shader is autogenerated by spirv-cross."); statement("#include \"spirv_cross/internal_interface.hpp\""); statement("#include \"spirv_cross/external_interface.h\""); statement("#include <stdint.h>"); statement(""); statement("using namespace spirv_cross;"); statement("using namespace glm;"); statement(""); statement("namespace Impl"); begin_scope(); switch (execution.model) { case ExecutionModelGeometry: case ExecutionModelTessellationControl: case ExecutionModelTessellationEvaluation: case ExecutionModelGLCompute: case ExecutionModelFragment: case ExecutionModelVertex: statement("struct Shader"); begin_scope(); break; default: throw CompilerError("Unsupported execution model."); } switch (execution.model) { case ExecutionModelGeometry: impl_type = "GeometryShader<Impl::Shader, Impl::Shader::Resources>"; resource_type = "GeometryResources"; break; case ExecutionModelVertex: impl_type = "VertexShader<Impl::Shader, Impl::Shader::Resources>"; resource_type = "VertexResources"; break; case ExecutionModelFragment: impl_type = "FragmentShader<Impl::Shader, Impl::Shader::Resources>"; resource_type = "FragmentResources"; break; case ExecutionModelGLCompute: impl_type = join("ComputeShader<Impl::Shader, Impl::Shader::Resources, ", execution.workgroup_size.x, ", ", execution.workgroup_size.y, ", ", execution.workgroup_size.z, ">"); resource_type = "ComputeResources"; break; case ExecutionModelTessellationControl: impl_type = "TessControlShader<Impl::Shader, Impl::Shader::Resources>"; resource_type = "TessControlResources"; break; case ExecutionModelTessellationEvaluation: impl_type = "TessEvaluationShader<Impl::Shader, Impl::Shader::Resources>"; resource_type = "TessEvaluationResources"; break; default: throw CompilerError("Unsupported execution model."); } }
Bump number of compilation loops to 3 in C++ as well.
Bump number of compilation loops to 3 in C++ as well.
C++
apache-2.0
h3xl3r/SPIRV-Cross,h3xl3r/SPIRV-Cross,KhronosGroup/SPIRV-Cross,KhronosGroup/SPIRV-Cross,KhronosGroup/SPIRV-Cross,KhronosGroup/SPIRV-Cross,h3xl3r/SPIRV-Cross,h3xl3r/SPIRV-Cross,KhronosGroup/SPIRV-Cross,h3xl3r/SPIRV-Cross,KhronosGroup/SPIRV-Cross
73339b63faf4e25eeb39f709d8398c7948ea5908
src/win32/window_engine.cpp
src/win32/window_engine.cpp
#include "window_engine.h" using namespace junior; using namespace junior::_win32; int window_engine::_window_count = 0; window_engine::window_engine(window* owner, const wchar_t* title, const UINT32 background_color) : _owner(owner), _d2d_factory(nullptr), _dwrite_factory(nullptr), _screen_target(nullptr), _canvas_target(nullptr), _text_format(nullptr), _default_brush(nullptr), _background_color(D2D1::ColorF(background_color)) { _create_device_independent_resources(); _create_window(title); } window_engine::~window_engine() { if (_handle) DestroyWindow(_handle); } void window_engine::_create_window(const wchar_t* title) { WNDCLASSEXW wcex = { 0 }; wcex.cbSize = sizeof(WNDCLASSEX); wcex.hInstance = GetModuleHandleW(nullptr); wcex.hCursor = LoadCursorW(nullptr, IDC_ARROW); wcex.lpszClassName = L"junior_window"; wcex.lpfnWndProc = [](HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { auto target = (window_engine*)GetWindowLongPtrW(hwnd, GWLP_USERDATA); return target ? target->_window_proc(msg, wp, lp) : DefWindowProcW(hwnd, msg, wp, lp); }; RegisterClassExW(&wcex); _handle = CreateWindowExW(0, wcex.lpszClassName, title, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, GetModuleHandleW(nullptr), nullptr); if (_handle) { _window_count++; SetWindowLongPtrW(_handle, GWLP_USERDATA, (LONG_PTR)this); _create_device_resources(); ShowWindow(_handle, SW_SHOWDEFAULT); UpdateWindow(_handle); } } LRESULT window_engine::_window_proc(const UINT msg, const WPARAM wParam, const WPARAM lParam) { switch (msg) { case WM_SIZE: if (_canvas_target) { auto buffer_size = _canvas_target->GetSize(); if (buffer_size.width < LOWORD(lParam) || buffer_size.height < HIWORD(lParam)) _resize_canvas(D2D1::SizeF(max(buffer_size.width, LOWORD(lParam)), max(buffer_size.height, HIWORD(lParam)))); } if (_screen_target) { _screen_target->Resize(D2D1::SizeU(LOWORD(lParam), HIWORD(lParam))); InvalidateRect(_handle, nullptr, FALSE); } return 0; case WM_DISPLAYCHANGE: InvalidateRect(_handle, nullptr, FALSE); return 0; case WM_PAINT: _update_screen(); return 0; case WM_DESTROY: PostMessageW(nullptr, WM_USER + 1, 0, (LPARAM)_owner); if (!--_window_count) PostQuitMessage(0); return 0; } return DefWindowProcW(_handle, msg, wParam, lParam); } std::wstring window_engine::get_title() const { wchar_t buffer[1024]; GetWindowTextW(_handle, buffer, 1024); return std::wstring(buffer); } void window_engine::set_owner(window* new_owner) { _owner = new_owner; } window* window_engine::get_owner(const HWND hWnd) { auto target = (window_engine*)GetWindowLongPtrW(hWnd, GWLP_USERDATA); return target ? target->_owner : nullptr; } HRESULT window_engine::_create_device_independent_resources() { if (CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED) == S_FALSE) CoUninitialize(); HRESULT hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &_d2d_factory); if (SUCCEEDED(hr)) hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(_dwrite_factory), reinterpret_cast<IUnknown**>(&_dwrite_factory)); if (SUCCEEDED(hr)) hr = _dwrite_factory->CreateTextFormat(L"Segoe UI", nullptr, DWRITE_FONT_WEIGHT_THIN, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 24.0f, L"", &_text_format); return hr; } HRESULT window_engine::_create_device_resources() { if (_canvas_target) return S_FALSE; if (!_handle || !_d2d_factory) return E_NOT_VALID_STATE; RECT rc; GetClientRect(_handle, &rc); D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top); HRESULT hr = _d2d_factory->CreateHwndRenderTarget(D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties(_handle, size), &_screen_target); if (SUCCEEDED(hr)) hr = _screen_target->CreateCompatibleRenderTarget(&_canvas_target); if (SUCCEEDED(hr)) { _canvas_target->BeginDraw(); _canvas_target->Clear(_background_color); hr = _canvas_target->EndDraw(); } if (SUCCEEDED(hr)) hr = _canvas_target->CreateSolidColorBrush(D2D1::ColorF(0), &_default_brush); _queued_drawing = false; return hr; } void window_engine::_discard_device_resources() { _screen_target = nullptr; _canvas_target = nullptr; _default_brush = nullptr; _queued_drawing = false; } HRESULT window_engine::_update_screen() { HRESULT hr = _create_device_resources(); if (FAILED(hr)) return E_NOT_VALID_STATE; RECT rc; GetUpdateRect(_handle, &rc, FALSE); CComPtr<ID2D1Bitmap> canvas; hr = _canvas_target->GetBitmap(&canvas); if (SUCCEEDED(hr)) { auto rect = D2D1::RectF((float)rc.left, (float)rc.top, (float)rc.right, (float)rc.bottom); _screen_target->BeginDraw(); _screen_target->DrawBitmap(canvas, rect, 1, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, rect); hr = _screen_target->EndDraw(); } if (SUCCEEDED(hr)) { ValidateRect(_handle, &rc); } if (hr == D2DERR_RECREATE_TARGET) { _discard_device_resources(); hr = S_OK; } return hr; } HRESULT window_engine::_resize_canvas(D2D1_SIZE_F new_size) { if (!_screen_target || !_canvas_target) return E_NOT_VALID_STATE; bool middle_of_queue = _queued_drawing; if (middle_of_queue) end_draw(); CComPtr<ID2D1BitmapRenderTarget> new_target; HRESULT hr = _screen_target->CreateCompatibleRenderTarget(new_size, &new_target); if (SUCCEEDED(hr)) { new_target->BeginDraw(); new_target->Clear(_background_color); hr = new_target->EndDraw(); } CComPtr<ID2D1Bitmap> current_canvas; CComPtr<ID2D1Bitmap> new_canvas; if (SUCCEEDED(hr)) hr = _canvas_target->GetBitmap(&current_canvas); if (SUCCEEDED(hr)) hr = new_target->GetBitmap(&new_canvas); if (SUCCEEDED(hr)) hr = new_canvas->CopyFromBitmap(nullptr, current_canvas, nullptr); if (SUCCEEDED(hr)) { _canvas_target = new_target; if (middle_of_queue) hr = begin_draw() ? S_OK : E_FAIL; } return hr; } CComPtr<ID2D1SolidColorBrush> window_engine::_get_brush(const UINT32 rgb) { if (!_default_brush) return nullptr; _default_brush->SetColor(D2D1::ColorF(rgb, 1.f)); return _default_brush; } bool window_engine::begin_draw() { if (_queued_drawing) return false; // TODO: warn user about begin/end draw mismatch HRESULT hr = _create_device_resources(); if (SUCCEEDED(hr)) { _canvas_target->BeginDraw(); _queued_drawing = true; } return SUCCEEDED(hr); } bool window_engine::end_draw() { if (!_canvas_target) return false; if (!_queued_drawing) return false; // TODO: warn user about begin/end draw mismatch HRESULT hr = _canvas_target->EndDraw(); if (hr == D2DERR_RECREATE_TARGET) { _discard_device_resources(); hr = S_OK; } if (SUCCEEDED(hr)) { InvalidateRect(_handle, nullptr, FALSE); } _queued_drawing = false; return SUCCEEDED(hr); } void window_engine::clear(const UINT32 rgb) { // TODO: implement clear() } void window_engine::draw_line(const float x1, const float y1, const float x2, const float y2, const UINT32 rgb, const float width) { _draw([&]() { _canvas_target->DrawLine(D2D1::Point2F(x1, y1), D2D1::Point2F(x2, y2), _get_brush(rgb), width); }); } void window_engine::draw_ellipse(const float x, const float y, const float rx, const float ry, const UINT32 rgb, const float width) { _draw([&]() { _canvas_target->DrawEllipse(D2D1::Ellipse(D2D1::Point2F(x, y), rx, ry), _get_brush(rgb), width); }); } void window_engine::fill_ellipse(const float x, const float y, const float rx, const float ry, const UINT32 rgb) { _draw([&]() { _canvas_target->FillEllipse(D2D1::Ellipse(D2D1::Point2F(x, y), rx, ry), _get_brush(rgb)); }); } void window_engine::write(const wchar_t* text, const float x, const float y, const UINT32 rgb) { _draw([&]() { if (_text_format) { auto target_size = _canvas_target->GetSize(); auto layout_rect = D2D1::RectF(x, y, target_size.width - 10, target_size.height); _text_format->SetReadingDirection(DWRITE_READING_DIRECTION_LEFT_TO_RIGHT); _canvas_target->DrawTextW(text, lstrlen(text), _text_format, layout_rect, _get_brush(rgb)); } }); } void window_engine::write(const wchar_t* text, const UINT32 rgb) { static float margin = 10; _draw([&]() { if (_text_format) { auto target_size = _canvas_target->GetSize(); bool is_arabic = text[0] && ((text[0] >= 0x0600 && text[0] <= 0x06ff) || (text[0] >= 0x08a0 && text[0] <= 0x08ff) || (text[0] >= 0xfb50 && text[0] <= 0xfdff) || (text[0] >= 0xfe70 && text[0] <= 0xfeff)); _text_format->SetReadingDirection(is_arabic ? DWRITE_READING_DIRECTION_RIGHT_TO_LEFT : DWRITE_READING_DIRECTION_LEFT_TO_RIGHT); CComPtr<IDWriteTextLayout> layout; HRESULT hr = _dwrite_factory->CreateTextLayout(text, lstrlen(text), _text_format, target_size.width - 2 * margin, target_size.height - _cursor_y - margin, &layout); if (SUCCEEDED(hr)) { _canvas_target->DrawTextLayout(D2D1::Point2F(margin, _cursor_y), layout, _get_brush(rgb)); DWRITE_TEXT_METRICS metrics; layout->GetMetrics(&metrics); _cursor_y += metrics.height; } } }); }
#include "window_engine.h" using namespace junior; using namespace junior::_win32; int window_engine::_window_count = 0; window_engine::window_engine(window* owner, const wchar_t* title, const UINT32 background_color) : _owner(owner), _d2d_factory(nullptr), _dwrite_factory(nullptr), _screen_target(nullptr), _canvas_target(nullptr), _text_format(nullptr), _default_brush(nullptr), _background_color(D2D1::ColorF(background_color)) { _create_device_independent_resources(); _create_window(title); } window_engine::~window_engine() { if (_handle) DestroyWindow(_handle); } void window_engine::_create_window(const wchar_t* title) { WNDCLASSEXW wcex = { 0 }; wcex.cbSize = sizeof(WNDCLASSEX); wcex.hInstance = GetModuleHandleW(nullptr); wcex.hCursor = LoadCursorW(nullptr, IDC_ARROW); wcex.lpszClassName = L"junior_window"; wcex.lpfnWndProc = [](HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { auto target = (window_engine*)GetWindowLongPtrW(hwnd, GWLP_USERDATA); return target ? target->_window_proc(msg, wp, lp) : DefWindowProcW(hwnd, msg, wp, lp); }; RegisterClassExW(&wcex); _handle = CreateWindowExW(0, wcex.lpszClassName, title, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, GetModuleHandleW(nullptr), nullptr); if (_handle) { _window_count++; SetWindowLongPtrW(_handle, GWLP_USERDATA, (LONG_PTR)this); _create_device_resources(); ShowWindow(_handle, SW_SHOWDEFAULT); UpdateWindow(_handle); } } LRESULT window_engine::_window_proc(const UINT msg, const WPARAM wParam, const WPARAM lParam) { switch (msg) { case WM_SIZE: if (_screen_target) { _resize_canvas(D2D1::SizeF((float)LOWORD(lParam), (float)HIWORD(lParam))); _screen_target->Resize(D2D1::SizeU(LOWORD(lParam), HIWORD(lParam))); InvalidateRect(_handle, nullptr, FALSE); } return 0; case WM_DISPLAYCHANGE: InvalidateRect(_handle, nullptr, FALSE); return 0; case WM_PAINT: _update_screen(); return 0; case WM_DESTROY: PostMessageW(nullptr, WM_USER + 1, 0, (LPARAM)_owner); if (!--_window_count) PostQuitMessage(0); return 0; } return DefWindowProcW(_handle, msg, wParam, lParam); } std::wstring window_engine::get_title() const { wchar_t buffer[1024]; GetWindowTextW(_handle, buffer, 1024); return std::wstring(buffer); } void window_engine::set_owner(window* new_owner) { _owner = new_owner; } window* window_engine::get_owner(const HWND hWnd) { auto target = (window_engine*)GetWindowLongPtrW(hWnd, GWLP_USERDATA); return target ? target->_owner : nullptr; } HRESULT window_engine::_create_device_independent_resources() { if (CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED) == S_FALSE) CoUninitialize(); HRESULT hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &_d2d_factory); if (SUCCEEDED(hr)) hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(_dwrite_factory), reinterpret_cast<IUnknown**>(&_dwrite_factory)); if (SUCCEEDED(hr)) hr = _dwrite_factory->CreateTextFormat(L"Segoe UI", nullptr, DWRITE_FONT_WEIGHT_THIN, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 24.0f, L"", &_text_format); return hr; } HRESULT window_engine::_create_device_resources() { if (_canvas_target) return S_FALSE; if (!_handle || !_d2d_factory) return E_NOT_VALID_STATE; RECT rc; GetClientRect(_handle, &rc); D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top); HRESULT hr = _d2d_factory->CreateHwndRenderTarget(D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties(_handle, size), &_screen_target); if (SUCCEEDED(hr)) hr = _screen_target->CreateCompatibleRenderTarget(&_canvas_target); if (SUCCEEDED(hr)) { _canvas_target->BeginDraw(); _canvas_target->Clear(_background_color); hr = _canvas_target->EndDraw(); } if (SUCCEEDED(hr)) hr = _canvas_target->CreateSolidColorBrush(D2D1::ColorF(0), &_default_brush); _queued_drawing = false; return hr; } void window_engine::_discard_device_resources() { _screen_target = nullptr; _canvas_target = nullptr; _default_brush = nullptr; _queued_drawing = false; } HRESULT window_engine::_update_screen() { HRESULT hr = _create_device_resources(); if (FAILED(hr)) return E_NOT_VALID_STATE; RECT rc; GetUpdateRect(_handle, &rc, FALSE); CComPtr<ID2D1Bitmap> canvas; hr = _canvas_target->GetBitmap(&canvas); if (SUCCEEDED(hr)) { auto rect = D2D1::RectF((float)rc.left, (float)rc.top, (float)rc.right, (float)rc.bottom); _screen_target->BeginDraw(); _screen_target->DrawBitmap(canvas, rect, 1, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, rect); hr = _screen_target->EndDraw(); } if (SUCCEEDED(hr)) { ValidateRect(_handle, &rc); } if (hr == D2DERR_RECREATE_TARGET) { _discard_device_resources(); hr = S_OK; } return hr; } HRESULT window_engine::_resize_canvas(D2D1_SIZE_F screen_size) { if (!_screen_target || !_canvas_target) return E_NOT_VALID_STATE; auto canvas_size = _canvas_target->GetSize(); if (canvas_size.width >= screen_size.width && canvas_size.height >= screen_size.height) return S_FALSE; auto new_size = D2D1::SizeF(max(canvas_size.width, screen_size.width), max(canvas_size.height, screen_size.height)); bool middle_of_queue = _queued_drawing; if (middle_of_queue) end_draw(); CComPtr<ID2D1BitmapRenderTarget> new_target; HRESULT hr = _screen_target->CreateCompatibleRenderTarget(new_size, &new_target); if (SUCCEEDED(hr)) { new_target->BeginDraw(); new_target->Clear(_background_color); hr = new_target->EndDraw(); } CComPtr<ID2D1Bitmap> current_canvas; CComPtr<ID2D1Bitmap> new_canvas; if (SUCCEEDED(hr)) hr = _canvas_target->GetBitmap(&current_canvas); if (SUCCEEDED(hr)) hr = new_target->GetBitmap(&new_canvas); if (SUCCEEDED(hr)) hr = new_canvas->CopyFromBitmap(nullptr, current_canvas, nullptr); if (SUCCEEDED(hr)) { _canvas_target = new_target; if (middle_of_queue) hr = begin_draw() ? S_OK : E_FAIL; } return hr; } CComPtr<ID2D1SolidColorBrush> window_engine::_get_brush(const UINT32 rgb) { if (!_default_brush) return nullptr; _default_brush->SetColor(D2D1::ColorF(rgb, 1.f)); return _default_brush; } bool window_engine::begin_draw() { if (_queued_drawing) return false; // TODO: warn user about begin/end draw mismatch HRESULT hr = _create_device_resources(); if (SUCCEEDED(hr)) { _canvas_target->BeginDraw(); _queued_drawing = true; } return SUCCEEDED(hr); } bool window_engine::end_draw() { if (!_canvas_target) return false; if (!_queued_drawing) return false; // TODO: warn user about begin/end draw mismatch HRESULT hr = _canvas_target->EndDraw(); if (hr == D2DERR_RECREATE_TARGET) { _discard_device_resources(); hr = S_OK; } if (SUCCEEDED(hr)) { InvalidateRect(_handle, nullptr, FALSE); } _queued_drawing = false; return SUCCEEDED(hr); } void window_engine::clear(const UINT32 rgb) { // TODO: implement clear() } void window_engine::draw_line(const float x1, const float y1, const float x2, const float y2, const UINT32 rgb, const float width) { _draw([&]() { _canvas_target->DrawLine(D2D1::Point2F(x1, y1), D2D1::Point2F(x2, y2), _get_brush(rgb), width); }); } void window_engine::draw_ellipse(const float x, const float y, const float rx, const float ry, const UINT32 rgb, const float width) { _draw([&]() { _canvas_target->DrawEllipse(D2D1::Ellipse(D2D1::Point2F(x, y), rx, ry), _get_brush(rgb), width); }); } void window_engine::fill_ellipse(const float x, const float y, const float rx, const float ry, const UINT32 rgb) { _draw([&]() { _canvas_target->FillEllipse(D2D1::Ellipse(D2D1::Point2F(x, y), rx, ry), _get_brush(rgb)); }); } void window_engine::write(const wchar_t* text, const float x, const float y, const UINT32 rgb) { _draw([&]() { if (_text_format) { auto target_size = _canvas_target->GetSize(); auto layout_rect = D2D1::RectF(x, y, target_size.width - 10, target_size.height); _text_format->SetReadingDirection(DWRITE_READING_DIRECTION_LEFT_TO_RIGHT); _canvas_target->DrawTextW(text, lstrlen(text), _text_format, layout_rect, _get_brush(rgb)); } }); } void window_engine::write(const wchar_t* text, const UINT32 rgb) { static float margin = 10; _draw([&]() { if (_text_format) { auto target_size = _canvas_target->GetSize(); bool is_arabic = text[0] && ((text[0] >= 0x0600 && text[0] <= 0x06ff) || (text[0] >= 0x08a0 && text[0] <= 0x08ff) || (text[0] >= 0xfb50 && text[0] <= 0xfdff) || (text[0] >= 0xfe70 && text[0] <= 0xfeff)); _text_format->SetReadingDirection(is_arabic ? DWRITE_READING_DIRECTION_RIGHT_TO_LEFT : DWRITE_READING_DIRECTION_LEFT_TO_RIGHT); CComPtr<IDWriteTextLayout> layout; HRESULT hr = _dwrite_factory->CreateTextLayout(text, lstrlen(text), _text_format, target_size.width - 2 * margin, target_size.height - _cursor_y - margin, &layout); if (SUCCEEDED(hr)) { _canvas_target->DrawTextLayout(D2D1::Point2F(margin, _cursor_y), layout, _get_brush(rgb)); DWRITE_TEXT_METRICS metrics; layout->GetMetrics(&metrics); _cursor_y += metrics.height; } } }); }
Check size (to only resize if needed) inside the _resize method #3
Check size (to only resize if needed) inside the _resize method #3
C++
mit
labandierra/junior,labandierra/junior
156b4cfb6060c977b89aec00247c4b9e59698cc6
alloutil/alloutil/al_OITFbo.hpp
alloutil/alloutil/al_OITFbo.hpp
#pragma once /* Order Independent Transparency (OIT) Original algorithm by Morgan McGuire AlloSystem version written by Keehong Youn [email protected] - Uses OpenGL compatibility profile - Provides transparency without sorting of the objects - By default uses flat non-lighting shader Override "vertCode" & "fragCode" to use custom shader use: OITFbo oit; oit.init(w, h); oit.beginOpaque(); // render opaque things oit.endOpaque(); oit.beginAccum(); // render transparent things oit.endAccum(); oit.beginReveal(); // render transparent things oit.endReveal(); oit.composite(); // now use "oit.result()" to get texture with rendered result Reference: - http://casual-effects.blogspot.com/2015/03/implemented-weighted-blended-order.html - http://casual-effects.blogspot.com/2015/03/colored-blended-order-independent.html */ #include "allocore/graphics/al_OpenGL.hpp" #include "allocore/graphics/al_Graphics.hpp" #include "allocore/graphics/al_FBO.hpp" #include "allocore/graphics/al_Shader.hpp" #include "allocore/graphics/al_Texture.hpp" #include <string> namespace al { class OITFbo { public: // private: // three render target: opaque, accum, and reveal // four shader pass: opaque, accum, reveal, and composite static const int opaque = 0; static const int accum = 1; static const int reveal = 2; static const int comp = 3; int w, h; FBO fbo; // one FBO with Texture tex[3]; // three color attachment textures and Texture tex_depth; // one common depth texture ShaderProgram shader[4]; Graphics g; public: OITFbo() {}; ~OITFbo() {}; void init(int _w, int _h) { w = _w; h = _h; tex_depth = Texture(w, h, Graphics::DEPTH_COMPONENT, Graphics::FLOAT); tex_depth.submit(); // this actually makes texture registered at gpu fbo.attachTexture2D(tex_depth.id(), FBO::DEPTH_ATTACHMENT); for (int i = 0; i < 3; i++) { tex[i] = Texture(w, h, Graphics::RGBA, Graphics::FLOAT); tex[i].submit(); } // would be nice if could FBO::COLOR_ATTACHMENT0 + i, but can't fbo.attachTexture2D(tex[opaque].id(), FBO::COLOR_ATTACHMENT0); fbo.attachTexture2D(tex[accum].id(), FBO::COLOR_ATTACHMENT1); fbo.attachTexture2D(tex[reveal].id(), FBO::COLOR_ATTACHMENT2); shader[opaque].compile(vertRenderCode().c_str(), fragOpaqueCode().c_str()); shader[accum].compile(vertRenderCode().c_str(), fragAccumCode().c_str()); shader[reveal].compile(vertRenderCode().c_str(), fragRevealCode().c_str()); shader[comp].compile(vertCompositeCode().c_str(), fragCompsiteCode().c_str()); ShaderProgram& c = shader[comp]; c.begin(); c.uniform("tex_accum", 0); c.uniform("tex_reveal", 1); c.end(); } void beginOpaque() { glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glDisable(GL_BLEND); bindFBO(); renderToOpaque(); clearDepth(); shader[opaque].begin(); } void endOpaque() { shader[opaque].end(); unbindFBO(); } void beginAccum() { glDepthMask(GL_FALSE); // depth test enabled but not masking glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // src, dst bindFBO(); renderToAccum(); clearColor(); // but don't clear depth from opaque rendering shader[accum].begin(); } void endAccum() { shader[accum].end(); unbindFBO(); } void beginReveal() { glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); bindFBO(); renderToReveal(); clearColor(); shader[reveal].begin(); } void endReveal() { shader[reveal].end(); unbindFBO(); } void composite() { glDisable(GL_DEPTH_TEST); glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); bindFBO(); renderToOpaque(); shader[comp].begin(); tex[accum].bind(0); tex[reveal].bind(1); quadViewport(); // push pixels for entire screen tex[accum].unbind(0); // it is important to unbind tex[reveal].unbind(1); shader[comp].end(); unbindFBO(); } Texture& result() { return tex[opaque]; } virtual std::string vertRenderCode(); virtual std::string fragOpaqueCode(); virtual std::string fragAccumCode(); virtual std::string fragRevealCode(); virtual std::string vertCompositeCode(); virtual std::string fragCompsiteCode(); private: void bindFBO() { fbo.begin(); } void unbindFBO() { fbo.end(); } void renderToOpaque() { glDrawBuffer(GL_COLOR_ATTACHMENT0); } void renderToAccum() { glDrawBuffer(GL_COLOR_ATTACHMENT1); } void renderToReveal() { glDrawBuffer(GL_COLOR_ATTACHMENT2); } void quadViewport(); void clearColor(float r=0, float g=0, float b=0, float a=0); void clearDepth(float d=1); }; inline std::string OITFbo::vertRenderCode() { return R"( varying vec4 color; void main(){ color = gl_Color; gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; } )"; } inline std::string OITFbo::fragOpaqueCode() { return R"( varying vec4 color; void main(){ gl_FragColor = color; } )"; } inline std::string OITFbo::fragAccumCode() { return R"( varying vec4 color; void main() { vec4 premult = vec4(color.rgb * color.a, color.a); vec3 transmit = color.rgb * (1.0 - color.a); premult.a *= 1.0 - clamp((transmit.r + transmit.g + transmit.b) / 3.0, 0.0, 1.0); float tmp = (min(premult.a, 1.0) * 8.0 + 0.01) * (1.0 - gl_FragCoord.z * 0.95); float w = clamp(tmp * tmp * tmp * 1e3, 1e-2, 3e2); gl_FragColor = premult * w / 100.0; // divide by 100 so we write a val less than 1.0 } )"; } inline std::string OITFbo::fragRevealCode() { return R"( varying vec4 color; void main() { vec4 premult = vec4(color.rgb * color.a, color.a); vec3 transmit = color.rgb * (1.0 - color.a); premult.a *= 1.0 - clamp((transmit.r + transmit.g + transmit.b) / 3.0, 0.0, 1.0); // all ouput we want is one value but we gotta write to 4 channels gl_FragColor = vec4(premult.a); } )"; } inline std::string OITFbo::vertCompositeCode() { return R"( void main(){ gl_TexCoord[0] = gl_MultiTexCoord0; gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; } )"; } inline std::string OITFbo::fragCompsiteCode() { return R"( uniform sampler2D tex_accum; uniform sampler2D tex_reveal; void main(){ vec4 accum = texture2D(tex_accum, gl_TexCoord[0].st) * 100.0; float revealage = texture2D(tex_reveal, gl_TexCoord[0].st).a; gl_FragColor = vec4(accum.rgb / max(accum.a, 0.00001), revealage); } )"; } inline void OITFbo::quadViewport() { g.pushMatrix(g.PROJECTION); g.loadIdentity(); g.pushMatrix(g.MODELVIEW); g.loadIdentity(); g.depthMask(0); // write only to color buffer al::Mesh& m = g.mesh(); m.reset(); m.primitive(g.TRIANGLE_STRIP); m.vertex(-1, -1, 0); m.texCoord(0, 0); m.vertex(1, -1, 0); m.texCoord(1, 0); m.vertex(-1, 1, 0); m.texCoord(0, 1); m.vertex(1, 1, 0); m.texCoord(1, 1); g.draw(m); g.depthMask(1); g.popMatrix(g.PROJECTION); g.popMatrix(g.MODELVIEW); } inline void OITFbo::clearColor(float r, float g, float b, float a) { glClearColor(r, g, b, a); glClear(GL_COLOR_BUFFER_BIT); } inline void OITFbo::clearDepth(float d) { glClearDepth(d); glClear(GL_DEPTH_BUFFER_BIT); } }
#pragma once /* Order Independent Transparency (OIT) Original algorithm by Morgan McGuire AlloSystem version written by Keehong Youn [email protected] - Uses OpenGL compatibility profile - Provides transparency without sorting of the objects - By default uses flat non-lighting shader Override "vertCode" & "fragCode" to use custom shader use: OITFbo oit; oit.init(w, h); oit.beginOpaque(); // render opaque things oit.endOpaque(); oit.beginAccum(); // render transparent things oit.endAccum(); oit.beginReveal(); // render transparent things oit.endReveal(); oit.composite(); // now use "oit.result()" to get texture with rendered result Reference: - http://casual-effects.blogspot.com/2015/03/implemented-weighted-blended-order.html - http://casual-effects.blogspot.com/2015/03/colored-blended-order-independent.html */ #include "allocore/graphics/al_OpenGL.hpp" #include "allocore/graphics/al_Graphics.hpp" #include "allocore/graphics/al_FBO.hpp" #include "allocore/graphics/al_Shader.hpp" #include "allocore/graphics/al_Texture.hpp" #include <string> namespace al { class OITFbo { public: // private: // three render target: opaque, accum, and reveal // four shader pass: opaque, accum, reveal, and composite static const int opaque = 0; static const int accum = 1; static const int reveal = 2; static const int comp = 3; int w, h; FBO fbo; // one FBO with Texture tex[3]; // three color attachment textures and Texture tex_depth; // one common depth texture ShaderProgram shader[4]; Graphics g; public: OITFbo() {}; ~OITFbo() {}; void init(int _w, int _h) { w = _w; h = _h; tex_depth = Texture(w, h, Graphics::DEPTH_COMPONENT, Graphics::FLOAT); tex_depth.submit(); // this actually makes texture registered at gpu fbo.attachTexture2D(tex_depth.id(), FBO::DEPTH_ATTACHMENT); for (int i = 0; i < 3; i++) { tex[i] = Texture(w, h, Graphics::RGBA, Graphics::FLOAT); tex[i].submit(); } // would be nice if could FBO::COLOR_ATTACHMENT0 + i, but can't fbo.attachTexture2D(tex[opaque].id(), FBO::COLOR_ATTACHMENT0); fbo.attachTexture2D(tex[accum].id(), FBO::COLOR_ATTACHMENT1); fbo.attachTexture2D(tex[reveal].id(), FBO::COLOR_ATTACHMENT2); shader[opaque].compile(vertRenderCode().c_str(), fragOpaqueCode().c_str()); shader[accum].compile(vertRenderCode().c_str(), fragAccumCode().c_str()); shader[reveal].compile(vertRenderCode().c_str(), fragRevealCode().c_str()); shader[comp].compile(vertCompositeCode().c_str(), fragCompsiteCode().c_str()); ShaderProgram& c = shader[comp]; c.begin(); c.uniform("tex_accum", 0); c.uniform("tex_reveal", 1); c.end(); } void beginOpaque() { glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glDisable(GL_BLEND); bindFBO(); renderToOpaque(); clearDepth(); shader[opaque].begin(); } void endOpaque() { shader[opaque].end(); unbindFBO(); } void beginAccum() { glDepthMask(GL_FALSE); // depth test enabled but not masking glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // src, dst bindFBO(); renderToAccum(); clearColor(); // but don't clear depth from opaque rendering shader[accum].begin(); } void endAccum() { shader[accum].end(); unbindFBO(); } void beginReveal() { glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); bindFBO(); renderToReveal(); clearColor(); shader[reveal].begin(); } void endReveal() { shader[reveal].end(); unbindFBO(); } void composite() { glDisable(GL_DEPTH_TEST); glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); bindFBO(); renderToOpaque(); shader[comp].begin(); tex[accum].bind(0); tex[reveal].bind(1); quadViewport(); // push pixels for entire screen tex[accum].unbind(0); // it is important to unbind tex[reveal].unbind(1); shader[comp].end(); unbindFBO(); } ShaderProgram& opaqueShader() { return shader[opaque]; } ShaderProgram& accumShader() { return shader[accum]; } ShaderProgram& revealShader() { return shader[reveal]; } ShaderProgram& compShader() { return shader[comp]; } Texture& result() { return tex[opaque]; } virtual std::string vertRenderCode(); virtual std::string fragOpaqueCode(); virtual std::string fragAccumCode(); virtual std::string fragRevealCode(); virtual std::string vertCompositeCode(); virtual std::string fragCompsiteCode(); private: void bindFBO() { fbo.begin(); } void unbindFBO() { fbo.end(); } void renderToOpaque() { glDrawBuffer(GL_COLOR_ATTACHMENT0); } void renderToAccum() { glDrawBuffer(GL_COLOR_ATTACHMENT1); } void renderToReveal() { glDrawBuffer(GL_COLOR_ATTACHMENT2); } void quadViewport(); void clearColor(float r=0, float g=0, float b=0, float a=0); void clearDepth(float d=1); }; inline std::string OITFbo::vertRenderCode() { return R"( varying vec4 color; void main(){ color = gl_Color; gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; } )"; } inline std::string OITFbo::fragOpaqueCode() { return R"( varying vec4 color; void main(){ gl_FragColor = color; } )"; } inline std::string OITFbo::fragAccumCode() { return R"( varying vec4 color; void main() { vec4 premult = vec4(color.rgb * color.a, color.a); vec3 transmit = color.rgb * (1.0 - color.a); premult.a *= 1.0 - clamp((transmit.r + transmit.g + transmit.b) / 3.0, 0.0, 1.0); float tmp = (min(premult.a, 1.0) * 8.0 + 0.01) * (1.0 - gl_FragCoord.z * 0.95); float w = clamp(tmp * tmp * tmp * 1e3, 1e-2, 3e2); gl_FragColor = premult * w / 100.0; // divide by 100 so we write a val less than 1.0 } )"; } inline std::string OITFbo::fragRevealCode() { return R"( varying vec4 color; void main() { vec4 premult = vec4(color.rgb * color.a, color.a); vec3 transmit = color.rgb * (1.0 - color.a); premult.a *= 1.0 - clamp((transmit.r + transmit.g + transmit.b) / 3.0, 0.0, 1.0); // all ouput we want is one value but we gotta write to 4 channels gl_FragColor = vec4(premult.a); } )"; } inline std::string OITFbo::vertCompositeCode() { return R"( void main(){ gl_TexCoord[0] = gl_MultiTexCoord0; gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; } )"; } inline std::string OITFbo::fragCompsiteCode() { return R"( uniform sampler2D tex_accum; uniform sampler2D tex_reveal; void main(){ vec4 accum = texture2D(tex_accum, gl_TexCoord[0].st) * 100.0; float revealage = texture2D(tex_reveal, gl_TexCoord[0].st).a; gl_FragColor = vec4(accum.rgb / max(accum.a, 0.00001), revealage); } )"; } inline void OITFbo::quadViewport() { g.pushMatrix(g.PROJECTION); g.loadIdentity(); g.pushMatrix(g.MODELVIEW); g.loadIdentity(); g.depthMask(0); // write only to color buffer al::Mesh& m = g.mesh(); m.reset(); m.primitive(g.TRIANGLE_STRIP); m.vertex(-1, -1, 0); m.texCoord(0, 0); m.vertex(1, -1, 0); m.texCoord(1, 0); m.vertex(-1, 1, 0); m.texCoord(0, 1); m.vertex(1, 1, 0); m.texCoord(1, 1); g.draw(m); g.depthMask(1); g.popMatrix(g.PROJECTION); g.popMatrix(g.MODELVIEW); } inline void OITFbo::clearColor(float r, float g, float b, float a) { glClearColor(r, g, b, a); glClear(GL_COLOR_BUFFER_BIT); } inline void OITFbo::clearDepth(float d) { glClearDepth(d); glClear(GL_DEPTH_BUFFER_BIT); } }
add getters for shaders
OITFbo: add getters for shaders
C++
bsd-3-clause
AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem
968e653683d2af2f790807be9a48ac8a81ea4e47
src/Polygon.cpp
src/Polygon.cpp
/* * File: Polygon.cpp * Author: florent * * Created on 25 juin 2015, 20:22 */ #include "Constants.hpp" #include "Segment.hpp" #include "Polygon.hpp" #include "Exception.hpp" #include <list> #include <cmath> #include <algorithm> #include <iostream> using namespace Cromod::GeomAPI; using namespace Cromod::Tools; using namespace std; Polygon::Polygon() { } Polygon::Polygon(const Polygon& polygon) { listSeg_ = polygon.listSeg_ ; } Polygon::Polygon(const vector<Point>& listPoints) { unsigned int size = listPoints.size(); Segment segment; if (size > 0) { for(int i=0; i<size; i++) { if (i < size-1) segment.setPoints(listPoints[i],listPoints[i+1]); else if (i == size-1) segment.setPoints(listPoints[i],(*this)[0].getOne()); if (segment.isSegment()) this->addSegment(segment); } } else Exception::logWarning("Empty list of Point type in Polygon constructor" ,__FILE__,__LINE__); } Polygon::~Polygon() { } Segment& Polygon::operator[](const unsigned int& i) { return listSeg_[i]; } Polygon& Polygon::operator=(const Polygon &polygon) { listSeg_ = polygon.listSeg_ ; } unsigned int Polygon::size() { return listSeg_.size(); } void Polygon::addSegment(Segment seg) { if (this->size()>0) { Point point1 = listSeg_.back().getTwo(); Point point2 = seg.getOne(); Segment seg_test(point1,point2); if (seg_test.getLength()>GEOM_TOLERANCE) { throw(Exception("Non-adjacent Segment argument in Polygon::addSegment" ,__FILE__,__LINE__)) ; } else { seg.setOne(point1); listSeg_.push_back(seg); } } else listSeg_.push_back(seg); } void Polygon::delSegment() { if (this->size()>0) listSeg_.pop_back(); else throw(Exception("Nothing to delete with Polygon::delSegment" ,__FILE__,__LINE__)) ; } void Polygon::deleteAll() { if (this->size()==0) throw(Exception("Nothing to delete with Polygon::deleteAll" ,__FILE__,__LINE__)) ; while (this->size()>0) this->delSegment(); } void Polygon::addPoint(const Point& point) { if (listSeg_.size()>0) { Point point_back = listSeg_.back().getTwo(); Segment new_seg(point_back,point); listSeg_.push_back(new_seg); } else { throw(Exception("Adding a Point type is impossible with Polygon::addPoint" ,__FILE__,__LINE__)) ; } } vector<Segment> Polygon::getList() { return listSeg_; } void Polygon::setList(const vector<Segment>& listSeg) { listSeg_ = listSeg; } bool Polygon::isClosed() { Polygon pol(*this); unsigned int size = pol.size(); if (size == 0) { Exception::logWarning("No Segment object in Polygon",__FILE__,__LINE__); return false; } if (pol[size-1].getTwo()!=pol[0].getOne()) return false; for(int i=0 ; i<(size-1) ; i++) { if (pol[i].getTwo()!=pol[i+1].getOne()) return false; } return true; } void Polygon::close() { unsigned int size = this->size(); if (size > 0) { Segment segment((*this)[size-1].getTwo(),(*this)[0].getOne()); if (segment.getLength()>GEOM_TOLERANCE) this->addSegment(segment); } else Exception::logWarning("Nothing to close with Polygon::close" ,__FILE__,__LINE__); } vector<Point> Polygon::getPoints() { unsigned int size = this->size(); vector<Point> listPoints; for(int i=0; i<size; i++) { listPoints.push_back((*this)[i].getOne()); } if (!(this->isClosed())) { Exception::logWarning("Using Polygon::getPoints with unclosed Polygon object" ,__FILE__,__LINE__); listPoints.push_back((*this)[size-1].getTwo()); } return listPoints; } Point Polygon::getOutside() { double pt[] = {INFINITY,0.}; Point point(pt,2); return point; } map<string,double> Polygon::getBottom() { unsigned int size = this->size(); if ( size == 0 ) { throw(Exception("Nothing to get with Polygon::getBottom" ,__FILE__,__LINE__)) ; } vector<Point> list = this->getPoints(); double xmax(list[0][0]), xmin(list[0][0]); double ymax(list[0][1]), ymin(list[0][1]); for(vector<Point>::iterator pt=list.begin(); pt!=list.end(); ++pt) { xmax = max(xmax,(*pt)[0]); xmin = min(xmin,(*pt)[0]); ymax = max(ymax,(*pt)[1]); ymin = min(ymin,(*pt)[1]); } map<string,double> coord; coord["xmax"]=xmax; coord["xmin"]=xmin; coord["ymax"]=ymax; coord["ymin"]=ymin; return coord; } bool Polygon::isSelfIntersect() { Polygon pol(*this); if (!pol.isClosed()) { throw(Exception("Polygon object is not closed in Polygon::isSelfIntersect" ,__FILE__,__LINE__)) ; } unsigned int size = pol.size(); if ( size < 2 ) { throw(Exception("Nothing to check with Polygon::isSelfIntersect" ,__FILE__,__LINE__)) ; } for(int i=0; i<size; i++) { list<int> listIndex; for(int j=0; j<size; j++) listIndex.push_back(j); listIndex.remove(i); if (i>0 && i<(size-1)) { listIndex.remove(i-1); listIndex.remove(i+1); } else if (i==0) { listIndex.remove(1); listIndex.remove(size-1); } else if (i==size-1) { listIndex.remove(0); listIndex.remove(i-1); } for(list<int>::iterator it=listIndex.begin(); it!=listIndex.end(); ++it) { if ((pol[i]).checkIntersect(pol[*it])) return true; } } return false; } int Polygon::getNbIntersect(const Segment& segment) { int nb_int(0); Polygon pol(*this); unsigned int size = pol.size(); bool intersect; bool intersect_next; for(int i=0; i<size; i++) { intersect = pol[i].checkIntersect(segment) && !(pol[i].checkParallel(segment)); if (i<size-1) { intersect_next = pol[i+1].checkIntersect(segment) && !(pol[i+1].checkParallel(segment)); } else { intersect_next = pol[0].checkIntersect(segment) && !(pol[0].checkParallel(segment)); } if ( intersect && !intersect_next ) nb_int += 1; } return nb_int; } bool Polygon::isOnEdge(const Point& point) { Polygon pol(*this); unsigned int size = pol.size(); for(int i=0; i<size; i++) { if ( pol[i].checkInclude(point) ) return true; } return false; } bool Polygon::isInside(const Point& point_in) { Point point_out = this->getOutside(); Segment segment(point_in,point_out); if (this->isOnEdge(point_in)) { //cout << "On edge" << endl; return true; } else if ( (this->getNbIntersect(segment)) % 2 != 0 ) { //cout << "Nb of intersection = " << this->getNbIntersect(segment) << endl; return true; } else return false; }
/* * File: Polygon.cpp * Author: florent * * Created on 25 juin 2015, 20:22 */ #include "Constants.hpp" #include "Segment.hpp" #include "Polygon.hpp" #include "Exception.hpp" #include <list> #include <cmath> #include <algorithm> #include <iostream> using namespace Cromod::GeomAPI; using namespace Cromod::Tools; using namespace std; Polygon::Polygon() { } Polygon::Polygon(const Polygon& polygon) { listSeg_ = polygon.listSeg_ ; } Polygon::Polygon(const vector<Point>& listPoints) { unsigned int size = listPoints.size(); Segment segment; if (size > 0) { for(int i=0; i<size; i++) { if (i < size-1) segment.setPoints(listPoints[i],listPoints[i+1]); else if (i == size-1) segment.setPoints(listPoints[i],(*this)[0].getOne()); if (segment.isSegment()) this->addSegment(segment); } } else Exception::logWarning("Empty list of Point type in Polygon constructor" ,__FILE__,__LINE__); } Polygon::~Polygon() { } Segment& Polygon::operator[](const unsigned int& i) { if (this->size()<0) return listSeg_[i]; else throw(Exception("Nothing to get with Polygon::operator[]" ,__FILE__,__LINE__)) ; } Polygon& Polygon::operator=(const Polygon &polygon) { listSeg_ = polygon.listSeg_ ; } unsigned int Polygon::size() { return listSeg_.size(); } void Polygon::addSegment(Segment seg) { if (this->size()>0) { Point point1 = listSeg_.back().getTwo(); Point point2 = seg.getOne(); Segment seg_test(point1,point2); if (seg_test.getLength()>GEOM_TOLERANCE) { throw(Exception("Non-adjacent Segment argument in Polygon::addSegment" ,__FILE__,__LINE__)) ; } else { seg.setOne(point1); listSeg_.push_back(seg); } } else listSeg_.push_back(seg); } void Polygon::delSegment() { if (this->size()>0) listSeg_.pop_back(); else throw(Exception("Nothing to delete with Polygon::delSegment" ,__FILE__,__LINE__)) ; } void Polygon::deleteAll() { if (this->size()==0) throw(Exception("Nothing to delete with Polygon::deleteAll" ,__FILE__,__LINE__)) ; while (this->size()>0) this->delSegment(); } void Polygon::addPoint(const Point& point) { if (listSeg_.size()>0) { Point point_back = listSeg_.back().getTwo(); Segment new_seg(point_back,point); listSeg_.push_back(new_seg); } else { throw(Exception("Adding a Point type is impossible with Polygon::addPoint" ,__FILE__,__LINE__)) ; } } vector<Segment> Polygon::getList() { return listSeg_; } void Polygon::setList(const vector<Segment>& listSeg) { listSeg_ = listSeg; } bool Polygon::isClosed() { Polygon pol(*this); unsigned int size = pol.size(); if (size == 0) { Exception::logWarning("No Segment object in Polygon",__FILE__,__LINE__); return false; } if (pol[size-1].getTwo()!=pol[0].getOne()) return false; for(int i=0 ; i<(size-1) ; i++) { if (pol[i].getTwo()!=pol[i+1].getOne()) return false; } return true; } void Polygon::close() { unsigned int size = this->size(); if (size > 0) { Segment segment((*this)[size-1].getTwo(),(*this)[0].getOne()); if (segment.getLength()>GEOM_TOLERANCE) this->addSegment(segment); } else Exception::logWarning("Nothing to close with Polygon::close" ,__FILE__,__LINE__); } vector<Point> Polygon::getPoints() { unsigned int size = this->size(); vector<Point> listPoints; for(int i=0; i<size; i++) { listPoints.push_back((*this)[i].getOne()); } if (!(this->isClosed())) { Exception::logWarning("Using Polygon::getPoints with unclosed Polygon object" ,__FILE__,__LINE__); listPoints.push_back((*this)[size-1].getTwo()); } return listPoints; } Point Polygon::getOutside() { double pt[] = {INFINITY,0.}; Point point(pt,2); return point; } map<string,double> Polygon::getBottom() { unsigned int size = this->size(); if ( size == 0 ) { throw(Exception("Nothing to get with Polygon::getBottom" ,__FILE__,__LINE__)) ; } vector<Point> list = this->getPoints(); double xmax(list[0][0]), xmin(list[0][0]); double ymax(list[0][1]), ymin(list[0][1]); for(vector<Point>::iterator pt=list.begin(); pt!=list.end(); ++pt) { xmax = max(xmax,(*pt)[0]); xmin = min(xmin,(*pt)[0]); ymax = max(ymax,(*pt)[1]); ymin = min(ymin,(*pt)[1]); } map<string,double> coord; coord["xmax"]=xmax; coord["xmin"]=xmin; coord["ymax"]=ymax; coord["ymin"]=ymin; return coord; } bool Polygon::isSelfIntersect() { Polygon pol(*this); if (!pol.isClosed()) { throw(Exception("Polygon object is not closed in Polygon::isSelfIntersect" ,__FILE__,__LINE__)) ; } unsigned int size = pol.size(); if ( size < 2 ) { throw(Exception("Nothing to check with Polygon::isSelfIntersect" ,__FILE__,__LINE__)) ; } for(int i=0; i<size; i++) { list<int> listIndex; for(int j=0; j<size; j++) listIndex.push_back(j); listIndex.remove(i); if (i>0 && i<(size-1)) { listIndex.remove(i-1); listIndex.remove(i+1); } else if (i==0) { listIndex.remove(1); listIndex.remove(size-1); } else if (i==size-1) { listIndex.remove(0); listIndex.remove(i-1); } for(list<int>::iterator it=listIndex.begin(); it!=listIndex.end(); ++it) { if ((pol[i]).checkIntersect(pol[*it])) return true; } } return false; } int Polygon::getNbIntersect(const Segment& segment) { int nb_int(0); Polygon pol(*this); unsigned int size = pol.size(); bool intersect; bool intersect_next; for(int i=0; i<size; i++) { intersect = pol[i].checkIntersect(segment) && !(pol[i].checkParallel(segment)); if (i<size-1) { intersect_next = pol[i+1].checkIntersect(segment) && !(pol[i+1].checkParallel(segment)); } else { intersect_next = pol[0].checkIntersect(segment) && !(pol[0].checkParallel(segment)); } if ( intersect && !intersect_next ) nb_int += 1; } return nb_int; } bool Polygon::isOnEdge(const Point& point) { Polygon pol(*this); unsigned int size = pol.size(); for(int i=0; i<size; i++) { if ( pol[i].checkInclude(point) ) return true; } return false; } bool Polygon::isInside(const Point& point_in) { Point point_out = this->getOutside(); Segment segment(point_in,point_out); if (this->isOnEdge(point_in)) { //cout << "On edge" << endl; return true; } else if ( (this->getNbIntersect(segment)) % 2 != 0 ) { //cout << "Nb of intersection = " << this->getNbIntersect(segment) << endl; return true; } else return false; }
Add an exception in Polygon::operator[]
Add an exception in Polygon::operator[]
C++
lgpl-2.1
cromod/CROMOD
2b66e48bcf3b12dd21c0c448bd0f11f6e3399ed4
src/plugins/subversion/subversionclient.cpp
src/plugins/subversion/subversionclient.cpp
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "subversionclient.h" #include "subversionconstants.h" #include "subversionplugin.h" #include "subversionsettings.h" #include <vcsbase/vcscommand.h> #include <vcsbase/vcsbaseconstants.h> #include <vcsbase/vcsbaseeditor.h> #include <vcsbase/vcsbaseeditorparameterwidget.h> #include <vcsbase/vcsbaseplugin.h> #include <utils/qtcassert.h> #include <utils/synchronousprocess.h> #include <diffeditor/diffeditorcontroller.h> #include <diffeditor/diffutils.h> #include <coreplugin/editormanager/editormanager.h> #include <QDir> #include <QFileInfo> #include <QTextStream> #include <QDebug> using namespace Core; using namespace DiffEditor; using namespace Utils; using namespace VcsBase; namespace Subversion { namespace Internal { class SubversionLogParameterWidget : public VcsBaseEditorParameterWidget { Q_OBJECT public: SubversionLogParameterWidget(VcsBaseClientSettings &settings, QWidget *parent = 0) : VcsBaseEditorParameterWidget(parent) { mapSetting(addToggleButton(QLatin1String("--verbose"), tr("Verbose"), tr("Show files changed in each revision")), settings.boolPointer(SubversionSettings::logVerboseKey)); } }; SubversionClient::SubversionClient() : VcsBaseClient(new SubversionSettings) { setLogParameterWidgetCreator([this] { return new SubversionLogParameterWidget(settings()); }); } VcsCommand *SubversionClient::createCommitCmd(const QString &repositoryRoot, const QStringList &files, const QString &commitMessageFile, const QStringList &extraOptions) const { const QStringList svnExtraOptions = QStringList(extraOptions) << SubversionClient::addAuthenticationOptions(settings()) << QLatin1String(Constants::NON_INTERACTIVE_OPTION) << QLatin1String("--encoding") << QLatin1String("utf8") << QLatin1String("--file") << commitMessageFile; VcsCommand *cmd = createCommand(repositoryRoot); cmd->addFlags(VcsCommand::ShowStdOut); QStringList args(vcsCommandString(CommitCommand)); cmd->addJob(vcsBinary(), args << svnExtraOptions << files); return cmd; } void SubversionClient::commit(const QString &repositoryRoot, const QStringList &files, const QString &commitMessageFile, const QStringList &extraOptions) { if (Subversion::Constants::debug) qDebug() << Q_FUNC_INFO << commitMessageFile << files; VcsCommand *cmd = createCommitCmd(repositoryRoot, files, commitMessageFile, extraOptions); cmd->execute(); } Id SubversionClient::vcsEditorKind(VcsCommandTag cmd) const { switch (cmd) { case VcsBaseClient::LogCommand: return Constants::SUBVERSION_LOG_EDITOR_ID; case VcsBaseClient::AnnotateCommand: return Constants::SUBVERSION_BLAME_EDITOR_ID; default: return Id(); } } // Add authorization options to the command line arguments. QStringList SubversionClient::addAuthenticationOptions(const VcsBaseClientSettings &settings) { if (!static_cast<const SubversionSettings &>(settings).hasAuthentication()) return QStringList(); const QString userName = settings.stringValue(SubversionSettings::userKey); const QString password = settings.stringValue(SubversionSettings::passwordKey); if (userName.isEmpty()) return QStringList(); QStringList rc; rc.push_back(QLatin1String("--username")); rc.push_back(userName); if (!password.isEmpty()) { rc.push_back(QLatin1String("--password")); rc.push_back(password); } return rc; } QString SubversionClient::synchronousTopic(const QString &repository) { QStringList args; args << QLatin1String("info"); QByteArray stdOut; if (!vcsFullySynchronousExec(repository, args, &stdOut)) return QString(); const QString revisionString = QLatin1String("Revision: "); // stdOut is ASCII only (at least in those areas we care about). QString output = commandOutputFromLocal8Bit(stdOut); foreach (const QString &line, output.split(QLatin1Char('\n'))) { if (line.startsWith(revisionString)) return QString::fromLatin1("r") + line.mid(revisionString.count()); } return QString(); } class DiffController : public DiffEditorController { Q_OBJECT public: DiffController(IDocument *document, const SubversionClient *client, const QString &directory); void setFilesList(const QStringList &filesList); void setChangeNumber(int changeNumber); protected: void reload(); private slots: void slotTextualDiffOutputReceived(const QString &contents); private: QString getDescription() const; void postCollectTextualDiffOutput(); QProcessEnvironment processEnvironment() const; const SubversionClient *m_client; QString m_workingDirectory; QStringList m_filesList; int m_changeNumber; }; DiffController::DiffController(IDocument *document, const SubversionClient *client, const QString &directory) : DiffEditorController(document), m_client(client), m_workingDirectory(directory), m_changeNumber(0) { forceContextLineCount(3); // SVN can not change that when using internal diff } QProcessEnvironment DiffController::processEnvironment() const { return m_client->processEnvironment(); } void DiffController::setFilesList(const QStringList &filesList) { if (isReloading()) return; m_filesList = filesList; } void DiffController::setChangeNumber(int changeNumber) { if (isReloading()) return; m_changeNumber = qMax(changeNumber, 0); } QString DiffController::getDescription() const { QStringList args(QLatin1String("log")); args << SubversionClient::addAuthenticationOptions(m_client->settings()); args << QLatin1String("-r"); args << QString::number(m_changeNumber); const SubversionResponse logResponse = SubversionPlugin::instance()->runSvn(m_workingDirectory, args, m_client->vcsTimeoutS(), VcsCommand::SshPasswordPrompt); if (logResponse.error) return QString(); return logResponse.stdOut; } void DiffController::postCollectTextualDiffOutput() { auto command = new VcsCommand(m_workingDirectory, processEnvironment()); command->setCodec(EditorManager::defaultTextCodec()); connect(command, SIGNAL(output(QString)), this, SLOT(slotTextualDiffOutputReceived(QString))); // command->addFlags(diffExecutionFlags()); QStringList args; args << QLatin1String("diff"); args << m_client->addAuthenticationOptions(m_client->settings()); args << QLatin1String("--internal-diff"); if (ignoreWhitespace()) args << QLatin1String("-x") << QLatin1String("-uw"); if (m_changeNumber) { args << QLatin1String("-r") << QString::number(m_changeNumber - 1) + QLatin1String(":") + QString::number(m_changeNumber); } else { args << m_filesList; } command->addJob(m_client->vcsBinary(), args, m_client->vcsTimeoutS()); command->execute(); } void DiffController::slotTextualDiffOutputReceived(const QString &contents) { bool ok; QList<FileData> fileDataList = DiffUtils::readPatch(contents, &ok); setDiffFiles(fileDataList, m_workingDirectory); reloadFinished(true); } void DiffController::reload() { const QString description = m_changeNumber ? getDescription() : QString(); postCollectTextualDiffOutput(); setDescription(description); } DiffController *SubversionClient::findOrCreateDiffEditor(const QString &documentId, const QString &source, const QString &title, const QString &workingDirectory) const { IDocument *document = DiffEditorController::findOrCreateDocument(documentId, title); DiffController *controller = qobject_cast<DiffController *>( DiffEditorController::controller(document)); if (!controller) controller = new DiffController(document, this, workingDirectory); VcsBasePlugin::setSource(document, source); return controller; } void SubversionClient::diff(const QString &workingDirectory, const QStringList &files, const QStringList &extraOptions) { Q_UNUSED(extraOptions); const QString vcsCmdString = vcsCommandString(DiffCommand); const QString documentId = VcsBaseEditor::getTitleId(workingDirectory, files); const QString title = vcsEditorTitle(vcsCmdString, documentId); DiffController *controller = findOrCreateDiffEditor(documentId, workingDirectory, title, workingDirectory); controller->setFilesList(files); controller->requestReload(); } void SubversionClient::log(const QString &workingDir, const QStringList &files, const QStringList &extraOptions, bool enableAnnotationContextMenu) { const auto logCount = settings().intValue(SubversionSettings::logCountKey); QStringList svnExtraOptions = QStringList(extraOptions) << SubversionClient::addAuthenticationOptions(settings()); if (logCount > 0) svnExtraOptions << QLatin1String("-l") << QString::number(logCount); QStringList nativeFiles; foreach (const QString& file, files) nativeFiles.append(QDir::toNativeSeparators(file)); // subversion stores log in UTF-8 and returns it back in user system locale. // So we do not need to encode it. VcsBaseClient::log(workingDir, files, svnExtraOptions, enableAnnotationContextMenu); } void SubversionClient::describe(const QString &workingDirectory, int changeNumber, const QString &title) { const QString documentId = VcsBaseEditor::editorTag(DiffOutput, workingDirectory, QStringList(), QString::number(changeNumber)); DiffController *controller = findOrCreateDiffEditor(documentId, workingDirectory, title, workingDirectory); controller->setChangeNumber(changeNumber); controller->requestReload(); } QString SubversionClient::findTopLevelForFile(const QFileInfo &file) const { Q_UNUSED(file) return QString(); } QStringList SubversionClient::revisionSpec(const QString &revision) const { Q_UNUSED(revision) return QStringList(); } VcsBaseClient::StatusItem SubversionClient::parseStatusLine(const QString &line) const { Q_UNUSED(line) return VcsBaseClient::StatusItem(); } } // namespace Internal } // namespace Subversion #include "subversionclient.moc"
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "subversionclient.h" #include "subversionconstants.h" #include "subversionplugin.h" #include "subversionsettings.h" #include <vcsbase/vcscommand.h> #include <vcsbase/vcsbaseconstants.h> #include <vcsbase/vcsbaseeditor.h> #include <vcsbase/vcsbaseeditorparameterwidget.h> #include <vcsbase/vcsbaseplugin.h> #include <utils/qtcassert.h> #include <utils/synchronousprocess.h> #include <diffeditor/diffeditorcontroller.h> #include <diffeditor/diffutils.h> #include <coreplugin/editormanager/editormanager.h> #include <QDir> #include <QFileInfo> #include <QTextStream> #include <QDebug> using namespace Core; using namespace DiffEditor; using namespace Utils; using namespace VcsBase; namespace Subversion { namespace Internal { class SubversionLogParameterWidget : public VcsBaseEditorParameterWidget { Q_OBJECT public: SubversionLogParameterWidget(VcsBaseClientSettings &settings, QWidget *parent = 0) : VcsBaseEditorParameterWidget(parent) { mapSetting(addToggleButton(QLatin1String("--verbose"), tr("Verbose"), tr("Show files changed in each revision")), settings.boolPointer(SubversionSettings::logVerboseKey)); } }; SubversionClient::SubversionClient() : VcsBaseClient(new SubversionSettings) { setLogParameterWidgetCreator([this] { return new SubversionLogParameterWidget(settings()); }); } VcsCommand *SubversionClient::createCommitCmd(const QString &repositoryRoot, const QStringList &files, const QString &commitMessageFile, const QStringList &extraOptions) const { const QStringList svnExtraOptions = QStringList(extraOptions) << SubversionClient::addAuthenticationOptions(settings()) << QLatin1String(Constants::NON_INTERACTIVE_OPTION) << QLatin1String("--encoding") << QLatin1String("utf8") << QLatin1String("--file") << commitMessageFile; VcsCommand *cmd = createCommand(repositoryRoot); cmd->addFlags(VcsCommand::ShowStdOut); QStringList args(vcsCommandString(CommitCommand)); cmd->addJob(vcsBinary(), args << svnExtraOptions << files); return cmd; } void SubversionClient::commit(const QString &repositoryRoot, const QStringList &files, const QString &commitMessageFile, const QStringList &extraOptions) { if (Subversion::Constants::debug) qDebug() << Q_FUNC_INFO << commitMessageFile << files; VcsCommand *cmd = createCommitCmd(repositoryRoot, files, commitMessageFile, extraOptions); cmd->execute(); } Id SubversionClient::vcsEditorKind(VcsCommandTag cmd) const { switch (cmd) { case VcsBaseClient::LogCommand: return Constants::SUBVERSION_LOG_EDITOR_ID; case VcsBaseClient::AnnotateCommand: return Constants::SUBVERSION_BLAME_EDITOR_ID; default: return Id(); } } // Add authorization options to the command line arguments. QStringList SubversionClient::addAuthenticationOptions(const VcsBaseClientSettings &settings) { if (!static_cast<const SubversionSettings &>(settings).hasAuthentication()) return QStringList(); const QString userName = settings.stringValue(SubversionSettings::userKey); const QString password = settings.stringValue(SubversionSettings::passwordKey); if (userName.isEmpty()) return QStringList(); QStringList rc; rc.push_back(QLatin1String("--username")); rc.push_back(userName); if (!password.isEmpty()) { rc.push_back(QLatin1String("--password")); rc.push_back(password); } return rc; } QString SubversionClient::synchronousTopic(const QString &repository) { QStringList args; args << QLatin1String("info"); QByteArray stdOut; if (!vcsFullySynchronousExec(repository, args, &stdOut)) return QString(); const QString revisionString = QLatin1String("Revision: "); // stdOut is ASCII only (at least in those areas we care about). QString output = commandOutputFromLocal8Bit(stdOut); foreach (const QString &line, output.split(QLatin1Char('\n'))) { if (line.startsWith(revisionString)) return QString::fromLatin1("r") + line.mid(revisionString.count()); } return QString(); } class DiffController : public DiffEditorController { Q_OBJECT public: DiffController(IDocument *document, const SubversionClient *client, const QString &directory); void setFilesList(const QStringList &filesList); void setChangeNumber(int changeNumber); protected: void reload(); private slots: void slotTextualDiffOutputReceived(const QString &contents); private: QString getDescription() const; void postCollectTextualDiffOutput(); QProcessEnvironment processEnvironment() const; const SubversionClient *m_client; QString m_workingDirectory; QStringList m_filesList; int m_changeNumber; }; DiffController::DiffController(IDocument *document, const SubversionClient *client, const QString &directory) : DiffEditorController(document), m_client(client), m_workingDirectory(directory), m_changeNumber(0) { forceContextLineCount(3); // SVN can not change that when using internal diff } QProcessEnvironment DiffController::processEnvironment() const { return m_client->processEnvironment(); } void DiffController::setFilesList(const QStringList &filesList) { if (isReloading()) return; m_filesList = filesList; } void DiffController::setChangeNumber(int changeNumber) { if (isReloading()) return; m_changeNumber = qMax(changeNumber, 0); } QString DiffController::getDescription() const { QStringList args(QLatin1String("log")); args << SubversionClient::addAuthenticationOptions(m_client->settings()); args << QLatin1String("-r"); args << QString::number(m_changeNumber); const SubversionResponse logResponse = SubversionPlugin::instance()->runSvn(m_workingDirectory, args, m_client->vcsTimeoutS(), VcsCommand::SshPasswordPrompt); if (logResponse.error) return QString(); return logResponse.stdOut; } void DiffController::postCollectTextualDiffOutput() { auto command = new VcsCommand(m_workingDirectory, processEnvironment()); command->setCodec(EditorManager::defaultTextCodec()); connect(command, &VcsCommand::output, this, &DiffController::slotTextualDiffOutputReceived); // command->addFlags(diffExecutionFlags()); QStringList args; args << QLatin1String("diff"); args << m_client->addAuthenticationOptions(m_client->settings()); args << QLatin1String("--internal-diff"); if (ignoreWhitespace()) args << QLatin1String("-x") << QLatin1String("-uw"); if (m_changeNumber) { args << QLatin1String("-r") << QString::number(m_changeNumber - 1) + QLatin1String(":") + QString::number(m_changeNumber); } else { args << m_filesList; } command->addJob(m_client->vcsBinary(), args, m_client->vcsTimeoutS()); command->execute(); } void DiffController::slotTextualDiffOutputReceived(const QString &contents) { bool ok; QList<FileData> fileDataList = DiffUtils::readPatch(contents, &ok); setDiffFiles(fileDataList, m_workingDirectory); reloadFinished(true); } void DiffController::reload() { const QString description = m_changeNumber ? getDescription() : QString(); postCollectTextualDiffOutput(); setDescription(description); } DiffController *SubversionClient::findOrCreateDiffEditor(const QString &documentId, const QString &source, const QString &title, const QString &workingDirectory) const { IDocument *document = DiffEditorController::findOrCreateDocument(documentId, title); DiffController *controller = qobject_cast<DiffController *>( DiffEditorController::controller(document)); if (!controller) controller = new DiffController(document, this, workingDirectory); VcsBasePlugin::setSource(document, source); return controller; } void SubversionClient::diff(const QString &workingDirectory, const QStringList &files, const QStringList &extraOptions) { Q_UNUSED(extraOptions); const QString vcsCmdString = vcsCommandString(DiffCommand); const QString documentId = VcsBaseEditor::getTitleId(workingDirectory, files); const QString title = vcsEditorTitle(vcsCmdString, documentId); DiffController *controller = findOrCreateDiffEditor(documentId, workingDirectory, title, workingDirectory); controller->setFilesList(files); controller->requestReload(); } void SubversionClient::log(const QString &workingDir, const QStringList &files, const QStringList &extraOptions, bool enableAnnotationContextMenu) { const auto logCount = settings().intValue(SubversionSettings::logCountKey); QStringList svnExtraOptions = QStringList(extraOptions) << SubversionClient::addAuthenticationOptions(settings()); if (logCount > 0) svnExtraOptions << QLatin1String("-l") << QString::number(logCount); QStringList nativeFiles; foreach (const QString& file, files) nativeFiles.append(QDir::toNativeSeparators(file)); // subversion stores log in UTF-8 and returns it back in user system locale. // So we do not need to encode it. VcsBaseClient::log(workingDir, files, svnExtraOptions, enableAnnotationContextMenu); } void SubversionClient::describe(const QString &workingDirectory, int changeNumber, const QString &title) { const QString documentId = VcsBaseEditor::editorTag(DiffOutput, workingDirectory, QStringList(), QString::number(changeNumber)); DiffController *controller = findOrCreateDiffEditor(documentId, workingDirectory, title, workingDirectory); controller->setChangeNumber(changeNumber); controller->requestReload(); } QString SubversionClient::findTopLevelForFile(const QFileInfo &file) const { Q_UNUSED(file) return QString(); } QStringList SubversionClient::revisionSpec(const QString &revision) const { Q_UNUSED(revision) return QStringList(); } VcsBaseClient::StatusItem SubversionClient::parseStatusLine(const QString &line) const { Q_UNUSED(line) return VcsBaseClient::StatusItem(); } } // namespace Internal } // namespace Subversion #include "subversionclient.moc"
Use Qt5 style connect
SubversionClient: Use Qt5 style connect Change-Id: I88f1de02edcb6c4406de64745ccc4cfc85f3d562 Reviewed-by: Orgad Shaneh <[email protected]>
C++
lgpl-2.1
martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,xianian/qt-creator,xianian/qt-creator,xianian/qt-creator,xianian/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,xianian/qt-creator,xianian/qt-creator,xianian/qt-creator,xianian/qt-creator,martyone/sailfish-qtcreator
846853e67aa9ac929f3d4e05ccdb9d30cc1aa551
mainwindow.cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); mjpeg.set_qlabel(ui->mjpeg_label); QObject::connect(&mjpeg, SIGNAL(connected()), this, SLOT(change_status())); QObject::connect(&mjpeg, SIGNAL(connected()), this, SLOT(send_request())); QObject::connect(&mjpeg, SIGNAL(disconnected()), this, SLOT(change_status())); QObject::connect(&mjpeg, SIGNAL(updated_fps(float)), this, SLOT(updated_fps(float))); QObject::connect(&mjpeg, SIGNAL(error(QMJpegViewer::MJpegViewerError)), this, SLOT(process_error(QMJpegViewer::MJpegViewerError))); QObject::connect(ui->connect_button, SIGNAL(clicked()), this, SLOT(connect_btn_clicked())); QObject::connect(ui->ratio_combo_box, SIGNAL(currentIndexChanged(int)), this, SLOT(set_ratio())); QObject::connect(ui->fps_frames_spin_box, SIGNAL(valueChanged(int)), this, SLOT(set_fps_frames())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::connect_btn_clicked() { if( mjpeg.state() == QAbstractSocket::UnconnectedState ) connect_to_dev(); else disconnect_from_dev(); } void MainWindow::connect_to_dev() { ui->connect_button->setEnabled(false); mjpeg.connect_to_host(ui->IP_line_edit->text(), ui->port_spin_box->value()); } void MainWindow::disconnect_from_dev() { ui->connect_button->setEnabled(false); mjpeg.disconnect_from_host(); } void MainWindow::send_request() { mjpeg.send_request(ui->request_edit->text().toLatin1()); } void MainWindow::set_ratio() { switch(ui->ratio_combo_box->currentIndex()) { case Qt::IgnoreAspectRatio: mjpeg.aspect_ratio = Qt::IgnoreAspectRatio; break; case Qt::KeepAspectRatio: mjpeg.aspect_ratio = Qt::KeepAspectRatio; break; case Qt::KeepAspectRatioByExpanding: mjpeg.aspect_ratio = Qt::KeepAspectRatioByExpanding; break; default: mjpeg.aspect_ratio = Qt::KeepAspectRatio; break; } } void MainWindow::change_status() { ui->connect_button->setEnabled(true); if( mjpeg.state() == QAbstractSocket::ConnectedState ) { ui->statusBar->showMessage(QString("Connected")); ui->connect_button->setText("Disconnect"); return; } ui->statusBar->showMessage(QString("Disconnected")); ui->connect_button->setText("Connect"); } void MainWindow::set_fps_frames() { mjpeg.fps_max_frames = ui->fps_frames_spin_box->value(); } void MainWindow::updated_fps(float new_fps) { ui->statusBar->showMessage(QString("Connected FPS: %1").arg(new_fps)); } void MainWindow::process_error(QMJpegViewer::MJpegViewerError error) { //show error if( error == QMJpegViewer::InnerSocketError ) ui->statusBar->showMessage( QString("Error: %1 socket error: %2").arg(error).arg(mjpeg.socket_error()) ); else ui->statusBar->showMessage( QString("Error: %1").arg(error) ); //we do not handle errors simply close mjpeg.disconnect_from_host(); }
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); mjpeg.set_qlabel(ui->mjpeg_label); QObject::connect(&mjpeg, SIGNAL(connected()), this, SLOT(change_status())); QObject::connect(&mjpeg, SIGNAL(connected()), this, SLOT(send_request())); QObject::connect(&mjpeg, SIGNAL(disconnected()), this, SLOT(change_status())); QObject::connect(&mjpeg, SIGNAL(updated_fps(float)), this, SLOT(updated_fps(float))); QObject::connect(&mjpeg, SIGNAL(error(QMJpegViewer::MJpegViewerError)), this, SLOT(process_error(QMJpegViewer::MJpegViewerError))); QObject::connect(ui->connect_button, SIGNAL(clicked()), this, SLOT(connect_btn_clicked())); QObject::connect(ui->ratio_combo_box, SIGNAL(currentIndexChanged(int)), this, SLOT(set_ratio())); QObject::connect(ui->fps_frames_spin_box, SIGNAL(valueChanged(int)), this, SLOT(set_fps_frames())); } MainWindow::~MainWindow() { //disconnect all signals and slots for mjpeg QObject::disconnect(&mjpeg, 0, 0, 0); delete ui; } void MainWindow::connect_btn_clicked() { if( mjpeg.state() == QAbstractSocket::UnconnectedState ) connect_to_dev(); else disconnect_from_dev(); } void MainWindow::connect_to_dev() { ui->connect_button->setEnabled(false); mjpeg.connect_to_host(ui->IP_line_edit->text(), ui->port_spin_box->value()); } void MainWindow::disconnect_from_dev() { ui->connect_button->setEnabled(false); mjpeg.disconnect_from_host(); } void MainWindow::send_request() { mjpeg.send_request(ui->request_edit->text().toLatin1()); } void MainWindow::set_ratio() { switch(ui->ratio_combo_box->currentIndex()) { case Qt::IgnoreAspectRatio: mjpeg.aspect_ratio = Qt::IgnoreAspectRatio; break; case Qt::KeepAspectRatio: mjpeg.aspect_ratio = Qt::KeepAspectRatio; break; case Qt::KeepAspectRatioByExpanding: mjpeg.aspect_ratio = Qt::KeepAspectRatioByExpanding; break; default: mjpeg.aspect_ratio = Qt::KeepAspectRatio; break; } } void MainWindow::change_status() { ui->connect_button->setEnabled(true); if( mjpeg.state() == QAbstractSocket::ConnectedState ) { ui->statusBar->showMessage(QString("Connected")); ui->connect_button->setText("Disconnect"); return; } ui->statusBar->showMessage(QString("Disconnected")); ui->connect_button->setText("Connect"); } void MainWindow::set_fps_frames() { mjpeg.fps_max_frames = ui->fps_frames_spin_box->value(); } void MainWindow::updated_fps(float new_fps) { ui->statusBar->showMessage(QString("Connected FPS: %1").arg(new_fps)); } void MainWindow::process_error(QMJpegViewer::MJpegViewerError error) { //show error if( error == QMJpegViewer::InnerSocketError ) ui->statusBar->showMessage( QString("Error: %1 socket error: %2").arg(error).arg(mjpeg.socket_error()) ); else ui->statusBar->showMessage( QString("Error: %1").arg(error) ); //we do not handle errors simply close mjpeg.disconnect_from_host(); }
Fix destructor for MainWindow
Fix destructor for MainWindow
C++
bsd-3-clause
KoynovStas/QMJpeg_viewer