text
stringlengths
54
60.6k
<commit_before>/* Copyright 2016 Mitchell Young 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 "UnitTest++/UnitTest++.h" #include <iostream> #include "pugixml.hpp" #include "core/pin_mesh.hpp" using namespace mocc; TEST(test_rect) { std::string xml_input = "<mesh type=\"rect\" id=\"1\" pitch=\"1.26\"><sub_x>5</sub_x><sub_y>" "4</sub_y>"; pugi::xml_document xml; xml.load_string(xml_input.c_str()); auto pm = PinMeshFactory(xml.child("mesh")); CHECK(pm); std::cout << *pm << std::endl; // Check the origin. Should be on a y-normal CHECK_EQUAL(12, pm->find_reg(Point2(0.0, 0.0), Direction(PI / 4.0, HPI))); CHECK_EQUAL(7, pm->find_reg(Point2(0.0, 0.0), Direction(5.0 * PI / 4.0, HPI))); // Check somewhere on an X-normal CHECK_EQUAL( 19, pm->find_reg(Point2(0.378, 0.4), Direction(1.0 * PI / 4.0, HPI))); CHECK_EQUAL( 18, pm->find_reg(Point2(0.378, 0.4), Direction(3.0 * PI / 4.0, HPI))); // Check somewhere on a corner CHECK_EQUAL(6, pm->find_reg(Point2(-0.378, -0.315), Direction(1.0 * PI / 4.0, HPI))); CHECK_EQUAL(5, pm->find_reg(Point2(-0.378, -0.315), Direction(3.0 * PI / 4.0, HPI))); CHECK_EQUAL(0, pm->find_reg(Point2(-0.378, -0.315), Direction(5.0 * PI / 4.0, HPI))); CHECK_EQUAL(1, pm->find_reg(Point2(-0.378, -0.315), Direction(7.0 * PI / 4.0, HPI))); // Check along the edges // on top edge, pointing out CHECK_EQUAL(-1, pm->find_reg(Point2(0.0, 0.63), Direction())); // on top edge, pointing in CHECK_EQUAL( 17, pm->find_reg(Point2(0.0, 0.63), Direction(5.0 * PI / 4.0, HPI))); // on bottom edge, pointing in CHECK_EQUAL(3, pm->find_reg(Point2(0.252, -0.63), Direction())); // on bottom edge, pointing out CHECK_EQUAL( -1, pm->find_reg(Point2(0.252, -0.63), Direction(5.0 * PI / 4.0, HPI))); // on right edge, pointing out CHECK_EQUAL(-1, pm->find_reg(Point2(0.63, 0.0), Direction())); // on bottom edge, pointing in CHECK_EQUAL( 14, pm->find_reg(Point2(0.63, 0.0), Direction(3.0 * PI / 4.0, HPI))); CHECK_EQUAL( 9, pm->find_reg(Point2(0.63, 0.0), Direction(5.0 * PI / 4.0, HPI))); } int main() { return UnitTest::RunAllTests(); } <commit_msg>Add test_fin_mesh TEST for very fine mesh test.<commit_after>/* Copyright 2016 Mitchell Young 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 "UnitTest++/UnitTest++.h" #include <iostream> #include "pugixml.hpp" #include "core/pin_mesh.hpp" using namespace mocc; TEST(test_rect) { std::string xml_input = "<mesh type=\"rect\" id=\"1\" pitch=\"1.26\"><sub_x>5</sub_x><sub_y>" "4</sub_y>"; pugi::xml_document xml; xml.load_string(xml_input.c_str()); auto pm = PinMeshFactory(xml.child("mesh")); CHECK(pm); std::cout << *pm << std::endl; // Check the origin. Should be on a y-normal CHECK_EQUAL(12, pm->find_reg(Point2(0.0, 0.0), Direction(PI / 4.0, HPI))); CHECK_EQUAL(7, pm->find_reg(Point2(0.0, 0.0), Direction(5.0 * PI / 4.0, HPI))); // Check somewhere on an X-normal CHECK_EQUAL( 19, pm->find_reg(Point2(0.378, 0.4), Direction(1.0 * PI / 4.0, HPI))); CHECK_EQUAL( 18, pm->find_reg(Point2(0.378, 0.4), Direction(3.0 * PI / 4.0, HPI))); // Check somewhere on a corner CHECK_EQUAL(6, pm->find_reg(Point2(-0.378, -0.315), Direction(1.0 * PI / 4.0, HPI))); CHECK_EQUAL(5, pm->find_reg(Point2(-0.378, -0.315), Direction(3.0 * PI / 4.0, HPI))); CHECK_EQUAL(0, pm->find_reg(Point2(-0.378, -0.315), Direction(5.0 * PI / 4.0, HPI))); CHECK_EQUAL(1, pm->find_reg(Point2(-0.378, -0.315), Direction(7.0 * PI / 4.0, HPI))); // Check along the edges // on top edge, pointing out CHECK_EQUAL(-1, pm->find_reg(Point2(0.0, 0.63), Direction())); // on top edge, pointing in CHECK_EQUAL( 17, pm->find_reg(Point2(0.0, 0.63), Direction(5.0 * PI / 4.0, HPI))); // on bottom edge, pointing in CHECK_EQUAL(3, pm->find_reg(Point2(0.252, -0.63), Direction())); // on bottom edge, pointing out CHECK_EQUAL( -1, pm->find_reg(Point2(0.252, -0.63), Direction(5.0 * PI / 4.0, HPI))); // on right edge, pointing out CHECK_EQUAL(-1, pm->find_reg(Point2(0.63, 0.0), Direction())); // on bottom edge, pointing in CHECK_EQUAL( 14, pm->find_reg(Point2(0.63, 0.0), Direction(3.0 * PI / 4.0, HPI))); CHECK_EQUAL( 9, pm->find_reg(Point2(0.63, 0.0), Direction(5.0 * PI / 4.0, HPI))); } TEST(test_fine_mesh) { std::string xml_input = "<mesh id=\"1\" type=\"rect\" pitch=\"10\">" " <sub_x>80</sub_x>" " <sub_y>80</sub_y>" "</mesh>"; pugi::xml_document xml; xml.load_string(xml_input.c_str()); auto pm = PinMeshFactory(xml.child("mesh")); CHECK(pm); std::cout << *pm << std::endl; // test two points for legitimate region index assertion test CHECK_EQUAL(50,pm->find_reg(Point2(1.250000000000004,-4.9999999999999432))); CHECK_EQUAL(6319,pm->find_reg(Point2(4.9375,4.8456249999999992))); } int main() { return UnitTest::RunAllTests(); } <|endoftext|>
<commit_before>/* * RmatGenerator.cpp * * Created on: 18.03.2014 * Author: Henning */ #include "RmatGenerator.h" #include "../auxiliary/Random.h" namespace NetworKit { RmatGenerator::RmatGenerator(count scale, count edgeFactor, double a, double b, double c, double d): scale(scale), edgeFactor(edgeFactor), a(a), b(b), c(c), d(d) { defaultEdgeWeight = 1.0; } RmatGenerator::~RmatGenerator() { } // TODO: make faster Graph RmatGenerator::generate() { count n = (1 << scale); count numEdges = n * edgeFactor; Graph G(n, true); auto quadrant([&]() { double r = Aux::Random::probability(); if (r <= a) { return 0; } else if (r <= a + b) { return 1; } else if (r <= a + b + c) { return 2; } else return 3; }); auto drawEdge([&]() { node u = 0; node v = 0; for (index i = 0; i < scale; ++i) { count q = quadrant(); u = u << 1; v = v << 1; u = u | (q & 1); v = v | (q & 2); } return std::make_pair(u, v); }); for (index e = 0; e < numEdges; ++e) { std::pair<node, node> drawnEdge = drawEdge(); TRACE("edge drawn: ", drawnEdge.first, " - ", drawnEdge.second); G.increaseWeight(drawnEdge.first, drawnEdge.second, defaultEdgeWeight); } return G; } } /* namespace NetworKit */ <commit_msg>R-MAT generator (to be tested thoroughly and to be accelerated)<commit_after>/* * RmatGenerator.cpp * * Created on: 18.03.2014 * Author: Henning */ #include "RmatGenerator.h" #include "../auxiliary/Random.h" namespace NetworKit { RmatGenerator::RmatGenerator(count scale, count edgeFactor, double a, double b, double c, double d): scale(scale), edgeFactor(edgeFactor), a(a), b(b), c(c), d(d) { defaultEdgeWeight = 1.0; } RmatGenerator::~RmatGenerator() { } // TODO: make faster Graph RmatGenerator::generate() { count n = (1 << scale); count numEdges = n * edgeFactor; Graph G(n, true); auto quadrant([&]() { double r = Aux::Random::probability(); if (r <= a) { return 0; } else if (r <= a + b) { return 1; } else if (r <= a + b + c) { return 2; } else return 3; }); auto drawEdge([&]() { node u = 0; node v = 0; for (index i = 0; i < scale; ++i) { count q = quadrant(); u = u << 1; v = v << 1; u = u | (q & 1); v = v | (q >> 1); } return std::make_pair(u, v); }); for (index e = 0; e < numEdges; ++e) { std::pair<node, node> drawnEdge = drawEdge(); TRACE("edge drawn: ", drawnEdge.first, " - ", drawnEdge.second); G.increaseWeight(drawnEdge.first, drawnEdge.second, defaultEdgeWeight); } return G; } } /* namespace NetworKit */ <|endoftext|>
<commit_before>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Simone Benatti // ============================================================================= // // FEA for 3D beams: IGA and ANCF // // ============================================================================= #include <chrono> #include "chrono/physics/ChBodyEasy.h" #include "chrono/physics/ChLinkMate.h" #include "chrono/physics/ChLinkMotorLinearPosition.h" #include "chrono/physics/ChSystemNSC.h" #include "chrono/solver/ChSolverMINRES.h" #include "chrono/solver/ChSolverPMINRES.h" #include "chrono/timestepper/ChTimestepper.h" #include "chrono/fea/ChBuilderBeam.h" #include "chrono/fea/ChElementBeamIGA.h" #include "chrono/fea/ChLinkDirFrame.h" #include "chrono/fea/ChLinkPointFrame.h" #include "chrono/fea/ChMesh.h" #include "chrono/fea/ChVisualizationFEAmesh.h" #include "chrono/physics/ChLinkMotorRotationAngle.h" #include "chrono/physics/ChLinkMotorRotationSpeed.h" #define USE_MKL #ifdef USE_MKL #include "chrono_mkl/ChSolverMKL.h" #endif using namespace chrono; using namespace chrono::fea; int ID_current_example = 1; const float beam_tip_init_load = -2.0f; const double beamL = 0.4; const double rho = 1000.0; // Beam material density const double E_mod = 0.02e10; // Beam modulus of elasticity const double nu_rat = 0.38; // Beam material Poisson ratio const double beam_wy = 0.012; const double beam_wz = 0.025; const double k1 = 10 * (1 + nu_rat) / (12 + 11 * nu_rat); // Timoshenko coefficient const double k2 = k1; // Timoshenko coefficient double ANCF_test(ChSystem& mysys, float beam_tip_load, int NofEl) { // Clear previous demo, if any: mysys.Clear(); mysys.SetChTime(0); // Create a mesh, that is a container for groups // of elements and their referenced nodes. // Remember to add it to the system. auto my_mesh = chrono_types::make_shared<ChMesh>(); my_mesh->SetAutomaticGravity(false); mysys.GetSystem()->Add(my_mesh); auto material = chrono_types::make_shared<ChMaterialBeamANCF>(rho, E_mod, nu_rat, E_mod * nu_rat, k1, k2); ChBuilderBeamANCFFullyPar builder; builder.BuildBeam(my_mesh, material, NofEl, ChVector<>(0, 0, 0), ChVector<>(beamL, 0, 0), beam_wy, beam_wz, VECT_Y, VECT_Z); builder.GetLastBeamNodes().front()->SetFixed(true); double y_init = builder.GetLastBeamNodes().back()->GetPos().y(); // Mark completion of system construction builder.GetLastBeamNodes().back()->SetForce(ChVector<>(0, beam_tip_load, 0)); mysys.DoStaticLinear(); double numerical_displ = builder.GetLastBeamNodes().back()->GetPos().y() - y_init; return numerical_displ; } // // Example B: Automatic creation of the nodes and knots // using the ChBuilderBeamIGA tool for creating a straight // rod automatically divided in Nel elements: // void IGA_test(ChSystem& mysys, float beam_tip_load, double ANCF_res, int nsections = 32, int order = 2) { // Clear previous demo, if any: mysys.GetSystem()->Clear(); mysys.GetSystem()->SetChTime(0); // Create a mesh, that is a container for groups // of elements and their referenced nodes. // Remember to add it to the system. auto my_mesh = chrono_types::make_shared<ChMesh>(); my_mesh->SetAutomaticGravity(false); mysys.Add(my_mesh); auto melasticity = chrono_types::make_shared<ChElasticityCosseratSimple>(); melasticity->SetYoungModulus(E_mod); melasticity->SetGshearModulus(E_mod * nu_rat); melasticity->SetBeamRaleyghDamping(0.0000); auto msection = chrono_types::make_shared<ChBeamSectionCosserat>(melasticity); msection->SetDensity(rho); msection->SetAsRectangularSection(beam_wy, beam_wz); // Use the ChBuilderBeamIGA tool for creating a straight rod // divided in Nel elements: ChBuilderBeamIGA builder; builder.BuildBeam(my_mesh, // the mesh to put the elements in msection, // section of the beam nsections, // number of sections (spans) ChVector<>(0, 0, 0), // start point ChVector<>(beamL, 0, 0), // end point VECT_Y, // suggested Y direction of section order); // order (3 = cubic, etc) builder.GetLastBeamNodes().front()->SetFixed(true); builder.GetLastBeamNodes().back()->SetForce(ChVector<>(0, beam_tip_load, 0)); // This is needed if you want to see things in Irrlicht 3D view. // Do a linear static analysis. mysys.DoStaticLinear(); // For comparison with analytical results. double poisson = melasticity->GetYoungModulus() / (2.0 * melasticity->GetGshearModulus()) - 1.0; double Ks_y = 10.0 * (1.0 + poisson) / (12.0 + 11.0 * poisson); double analytic_timoshenko_displ = (beam_tip_load * pow(beamL, 3)) / (3 * melasticity->GetYoungModulus() * (1. / 12.) * beam_wz * pow(beam_wy, 3)) + (beam_tip_load * beamL) / (Ks_y * melasticity->GetGshearModulus() * beam_wz * beam_wy); // = (P*L^3)/(3*E*I) + (P*L)/(k*A*G) double numerical_displ = builder.GetLastBeamNodes().back()->GetPos().y() - builder.GetLastBeamNodes().back()->GetX0().GetPos().y(); GetLog() << "\n LINEAR STATIC IGA cantilever, order= " << order << " nsections= " << nsections << " rel.error= " << fabs((numerical_displ - analytic_timoshenko_displ) / analytic_timoshenko_displ) << "\n"; GetLog() << "\n LINEAR STATIC ANCF cantilever, nsections= " << nsections << " rel.error= " << fabs((ANCF_res - analytic_timoshenko_displ) / analytic_timoshenko_displ) << "\n"; } int main(int argc, char* argv[]) { GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n"; int test_number = 5; // Create a Chrono::Engine physical system ChSystemNSC my_system; // Solver default settings for all the sub demos: my_system.SetSolverType(ChSolver::Type::MINRES); my_system.SetSolverWarmStarting(true); // this helps a lot to speedup convergence in this class of problems my_system.SetMaxItersSolverSpeed(500); my_system.SetMaxItersSolverStab(500); my_system.SetTolForce(1e-14); auto msolver = std::static_pointer_cast<ChSolverMINRES>(my_system.GetSolver()); msolver->SetVerbose(false); msolver->SetDiagonalPreconditioning(true); #ifdef USE_MKL auto mkl_solver = chrono_types::make_shared<ChSolverMKL<>>(); my_system.SetSolver(mkl_solver); #endif // Run the sub-demos: for (int i = 1; i <= test_number; i++) { std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); double ancfres = ANCF_test(my_system, i * beam_tip_init_load, i + 2); std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now(); IGA_test(my_system, i * beam_tip_init_load, ancfres, i + 2, 3); std::chrono::high_resolution_clock::time_point t3 = std::chrono::high_resolution_clock::now(); auto ANCFduration = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count(); auto IGAduration = std::chrono::duration_cast<std::chrono::microseconds>(t3 - t2).count(); /*GetLog() << "\n ANCF Elapsed Time: " << ANCFduration << "\n\n"; GetLog() << "\n IGA Elapsed Time: " << IGAduration << "\n\n";*/ std::cout << "\n ANCF Elapsed Time: " << ANCFduration << "\n\n"; std::cout << "\n IGA Elapsed Time: " << IGAduration << "\n\n"; } return 0; } <commit_msg>Minor cleanup<commit_after>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Simone Benatti // ============================================================================= // // FEA for 3D beams: IGA and ANCF // // ============================================================================= #include <chrono> #include "chrono/physics/ChSystemNSC.h" #include "chrono/solver/ChSolverMINRES.h" #include "chrono/timestepper/ChTimestepper.h" #include "chrono/fea/ChBuilderBeam.h" #include "chrono/fea/ChElementBeamIGA.h" #include "chrono/fea/ChMesh.h" #include "chrono_mkl/ChSolverMKL.h" using namespace chrono; using namespace chrono::fea; bool use_MKL = true; int num_tests = 5; const float beam_tip_init_load = -2.0f; const double beamL = 0.4; const double rho = 1000.0; // Beam material density const double E_mod = 0.02e10; // Beam modulus of elasticity const double nu_rat = 0.38; // Beam material Poisson ratio const double beam_wy = 0.012; const double beam_wz = 0.025; const double k1 = 10 * (1 + nu_rat) / (12 + 11 * nu_rat); // Timoshenko coefficient const double k2 = k1; // Timoshenko coefficient double AnalyticalSol(float beam_tip_load) { double G_mod = E_mod * nu_rat; double poisson = E_mod / (2.0 * G_mod) - 1.0; double Ks_y = 10.0 * (1.0 + poisson) / (12.0 + 11.0 * poisson); // (P*L^3)/(3*E*I) + (P*L)/(k*A*G) double analytical_timoshenko_displ = (beam_tip_load * pow(beamL, 3)) / (3 * E_mod * (1. / 12.) * beam_wz * pow(beam_wy, 3)) + (beam_tip_load * beamL) / (Ks_y * G_mod * beam_wz * beam_wy); return analytical_timoshenko_displ; } void ANCF_test(ChSystem& mysys, float beam_tip_load, int NofEl, double analytical_displ) { // Clear previous demo, if any: mysys.Clear(); mysys.SetChTime(0); // Create a mesh, that is a container for groups // of elements and their referenced nodes. // Remember to add it to the system. auto my_mesh = chrono_types::make_shared<ChMesh>(); my_mesh->SetAutomaticGravity(false); mysys.GetSystem()->Add(my_mesh); auto material = chrono_types::make_shared<ChMaterialBeamANCF>(rho, E_mod, nu_rat, E_mod * nu_rat, k1, k2); ChBuilderBeamANCFFullyPar builder; builder.BuildBeam(my_mesh, material, NofEl, ChVector<>(0, 0, 0), ChVector<>(beamL, 0, 0), beam_wy, beam_wz, VECT_Y, VECT_Z); builder.GetLastBeamNodes().front()->SetFixed(true); builder.GetLastBeamNodes().back()->SetForce(ChVector<>(0, beam_tip_load, 0)); double y_init = builder.GetLastBeamNodes().back()->GetPos().y(); // Do a linear static analysis. mysys.DoStaticLinear(); double numerical_displ = builder.GetLastBeamNodes().back()->GetPos().y() - y_init; GetLog() << "LINEAR STATIC ANCF cantilever, num. elements = " << NofEl << " rel.error= " << fabs((numerical_displ - analytical_displ) / analytical_displ) << "\n\n"; } void IGA_test(ChSystem& mysys, float beam_tip_load, int nsections, int order, double analytical_displ) { // Clear previous demo, if any: mysys.GetSystem()->Clear(); mysys.GetSystem()->SetChTime(0); // Create a mesh, that is a container for groups // of elements and their referenced nodes. // Remember to add it to the system. auto my_mesh = chrono_types::make_shared<ChMesh>(); my_mesh->SetAutomaticGravity(false); mysys.Add(my_mesh); auto melasticity = chrono_types::make_shared<ChElasticityCosseratSimple>(); melasticity->SetYoungModulus(E_mod); melasticity->SetGshearModulus(E_mod * nu_rat); melasticity->SetBeamRaleyghDamping(0.0000); auto msection = chrono_types::make_shared<ChBeamSectionCosserat>(melasticity); msection->SetDensity(rho); msection->SetAsRectangularSection(beam_wy, beam_wz); // Use the ChBuilderBeamIGA tool for creating a straight rod divided in Nel elements ChBuilderBeamIGA builder; builder.BuildBeam(my_mesh, // the mesh to put the elements in msection, // section of the beam nsections, // number of sections (spans) ChVector<>(0, 0, 0), // start point ChVector<>(beamL, 0, 0), // end point VECT_Y, // suggested Y direction of section order); // order (3 = cubic, etc) builder.GetLastBeamNodes().front()->SetFixed(true); builder.GetLastBeamNodes().back()->SetForce(ChVector<>(0, beam_tip_load, 0)); double y_init = builder.GetLastBeamNodes().back()->GetX0().GetPos().y(); // Do a linear static analysis. mysys.DoStaticLinear(); double numerical_displ = builder.GetLastBeamNodes().back()->GetPos().y() - y_init; GetLog() << "LINEAR STATIC IGA cantilever, order= " << order << " nsections= " << nsections << " rel.error= " << fabs((numerical_displ - analytical_displ) / analytical_displ) << "\n\n"; } int main(int argc, char* argv[]) { GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n"; // Create a Chrono::Engine physical system ChSystemNSC my_system; // Solver settings if (use_MKL) { auto mkl_solver = chrono_types::make_shared<ChSolverMKL<>>(); mkl_solver->SetVerbose(true); my_system.SetSolver(mkl_solver); } else { my_system.SetSolverType(ChSolver::Type::MINRES); my_system.SetSolverWarmStarting(true); my_system.SetMaxItersSolverSpeed(500); my_system.SetMaxItersSolverStab(500); my_system.SetTolForce(1e-14); auto msolver = std::static_pointer_cast<ChSolverMINRES>(my_system.GetSolver()); msolver->SetDiagonalPreconditioning(true); msolver->SetVerbose(false); } // Run all tests for (int i = 1; i <= num_tests; i++) { std::cout << "\n============================\nTest # " << i << "\n" << std::endl; double analytical_displ = AnalyticalSol(i * beam_tip_init_load); std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); ANCF_test(my_system, i * beam_tip_init_load, i + 2, analytical_displ); std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now(); IGA_test(my_system, i * beam_tip_init_load, i + 2, 3, analytical_displ); std::chrono::high_resolution_clock::time_point t3 = std::chrono::high_resolution_clock::now(); auto ANCFduration = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count(); auto IGAduration = std::chrono::duration_cast<std::chrono::microseconds>(t3 - t2).count(); std::cout << "ANCF Elapsed Time: " << ANCFduration << "\n"; std::cout << "IGA Elapsed Time: " << IGAduration << "\n\n"; } return 0; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <gmock/gmock.h> #include <experiments/experiments.hpp> #include <tuple> #include <memory> using ::testing::DoubleEq; using ::testing::DoubleNear; typedef std::shared_ptr<crest::wave::Integrator<double>> IntegratorSharedPtr; /* * The order of convergence tests in this file simply test that the errors are close to some values * that have been verified manually when applying the Method of Manufactured Solutions. */ class homogeneous_unit_square : public ::testing::TestWithParam<std::tuple<IntegratorSharedPtr, ExperimentResult>> { }; class inhomogeneous_unit_square : public ::testing::TestWithParam<std::tuple<IntegratorSharedPtr, ExperimentResult>> { }; TEST_P(homogeneous_unit_square, order_of_convergence) { auto test_params = GetParam(); auto integrator = std::get<0>(test_params); const auto expected_result = std::get<1>(test_params); auto experiment = HomogeneousDirichletUnitSquare(); experiment.run_offline(expected_result.offline_parameters); const auto result = experiment.run_online(expected_result.online_parameters.get(), *integrator); const auto expected_online_result = expected_result.online_result.get(); ASSERT_THAT(result.error_summary.l2, DoubleNear(expected_online_result.error_summary.l2, 1e-9)); ASSERT_THAT(result.error_summary.h1_semi, DoubleNear(expected_online_result.error_summary.h1_semi, 1e-7)); ASSERT_THAT(result.error_summary.h1, DoubleNear(expected_online_result.error_summary.h1, 1e-7)); } TEST_P(inhomogeneous_unit_square, order_of_convergence) { auto test_params = GetParam(); auto integrator = std::get<0>(test_params); const auto expected_result = std::get<1>(test_params); auto experiment = InhomogeneousDirichletUnitSquare(); experiment.run_offline(expected_result.offline_parameters); const auto result = experiment.run_online(expected_result.online_parameters.get(), *integrator); const auto expected_online_result = expected_result.online_result.get(); ASSERT_THAT(result.error_summary.l2, DoubleNear(expected_online_result.error_summary.l2, 1e-9)); ASSERT_THAT(result.error_summary.h1_semi, DoubleNear(expected_online_result.error_summary.h1_semi, 1e-7)); ASSERT_THAT(result.error_summary.h1, DoubleNear(expected_online_result.error_summary.h1, 1e-7)); } ExperimentResult make_convergence_test_result(const OfflineParameters & offline, const OnlineParameters & online, const ErrorSummary & error_summary) { return ExperimentResult() .with_offline_parameters(offline) .with_online_parameters(online) .with_online_result(OnlineResult().with_error_summary(error_summary)); } INSTANTIATE_TEST_CASE_P(direct_crank_nicolson, homogeneous_unit_square, ::testing::Combine( ::testing::Values(std::make_shared<crest::wave::DirectCrankNicolson<double>>()), ::testing::Values( make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.25), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.585458541734819) .with_h1_semi(0.584669994677925) .with_l2(0.0289167538286227) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.125), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.289671336214043) .with_h1_semi(0.2895515729457) .with_l2(0.00761102062470874) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.0625), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.144437769866845) .with_h1_semi(0.144415884917059) .with_l2(0.00220311548992367) ) ))); INSTANTIATE_TEST_CASE_P(iterative_crank_nicolson, homogeneous_unit_square, ::testing::Combine( ::testing::Values(std::make_shared<crest::wave::IterativeCrankNicolson<double>>()), ::testing::Values( make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.25), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.585458541735016) .with_h1_semi(0.584669994678112) .with_l2(0.0289167538288395) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.125), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.289671336213969) .with_h1_semi(0.289551572945625) .with_l2(0.00761102062490839) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.0625), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.144437769865326) .with_h1_semi(0.14441588491555) .with_l2(0.002203115490062) ) ))); INSTANTIATE_TEST_CASE_P(direct_crank_nicolson, inhomogeneous_unit_square, ::testing::Combine( ::testing::Values(std::make_shared<crest::wave::DirectCrankNicolson<double>>()), ::testing::Values( make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.25), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.587379118139992) .with_h1_semi(0.586591995031311) .with_l2(0.0289494785208848) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.125), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.290637174136373) .with_h1_semi(0.290517800933425) .with_l2(0.00761895620278423) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.0625), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.144922764238598) .with_h1_semi(0.144901003208638) .with_l2(0.0022048870589444) ) ))); INSTANTIATE_TEST_CASE_P(iterative_crank_nicolson, inhomogeneous_unit_square, ::testing::Combine( ::testing::Values(std::make_shared<crest::wave::IterativeCrankNicolson<double>>()), ::testing::Values( make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.25), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.587379371767793) .with_h1_semi(0.586592249024436) .with_l2(0.0289494776458804) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.125), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.290636831113929) .with_h1_semi(0.290517458731212) .with_l2(0.00761894063454651) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.0625), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.144922345898392) .with_h1_semi(0.144900585264829) .with_l2(0.00220483987973394) ) ))); INSTANTIATE_TEST_CASE_P(iterative_leapfrog, inhomogeneous_unit_square, ::testing::Combine( ::testing::Values(std::make_shared<crest::wave::IterativeLeapfrog<double>>()), ::testing::Values( make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.25), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.587378020587716) .with_h1_semi(0.586590792266803) .with_l2(0.0289506641927545) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.125), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.290625227318885) .with_h1_semi(0.290505802110512) .with_l2(0.00761996738873146) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.0625), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.144948283932812) .with_h1_semi(0.144926498965492) .with_l2(0.00220611626654336) ) ))); INSTANTIATE_TEST_CASE_P(lumped_leapfrog, inhomogeneous_unit_square, ::testing::Combine( ::testing::Values(std::make_shared<crest::wave::LumpedLeapfrog<double>>()), ::testing::Values( make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.25), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.582666537765749) .with_h1_semi(0.582159646452925) .with_l2(0.0240803754481128) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.125), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.288489719319695) .with_h1_semi(0.288431743027219) .with_l2(0.0057424077081183) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.0625), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.144206934687547) .with_h1_semi(0.144197839593727) .with_l2(0.00159275434745992) ) ))); <commit_msg>Set tolerance of integration tests to match previous setting<commit_after>#include <gtest/gtest.h> #include <gmock/gmock.h> #include <experiments/experiments.hpp> #include <tuple> #include <memory> using ::testing::DoubleEq; using ::testing::DoubleNear; typedef std::shared_ptr<crest::wave::Integrator<double>> IntegratorSharedPtr; /* * The order of convergence tests in this file simply test that the errors are close to some values * that have been verified manually when applying the Method of Manufactured Solutions. */ class homogeneous_unit_square : public ::testing::TestWithParam<std::tuple<IntegratorSharedPtr, ExperimentResult>> { }; class inhomogeneous_unit_square : public ::testing::TestWithParam<std::tuple<IntegratorSharedPtr, ExperimentResult>> { }; constexpr double TOL = 1e-9; TEST_P(homogeneous_unit_square, order_of_convergence) { auto test_params = GetParam(); auto integrator = std::get<0>(test_params); integrator->set_tolerance(TOL); const auto expected_result = std::get<1>(test_params); auto experiment = HomogeneousDirichletUnitSquare(); experiment.run_offline(expected_result.offline_parameters); const auto result = experiment.run_online(expected_result.online_parameters.get(), *integrator); const auto expected_online_result = expected_result.online_result.get(); ASSERT_THAT(result.error_summary.l2, DoubleNear(expected_online_result.error_summary.l2, 1e-9)); ASSERT_THAT(result.error_summary.h1_semi, DoubleNear(expected_online_result.error_summary.h1_semi, 1e-7)); ASSERT_THAT(result.error_summary.h1, DoubleNear(expected_online_result.error_summary.h1, 1e-7)); } TEST_P(inhomogeneous_unit_square, order_of_convergence) { auto test_params = GetParam(); auto integrator = std::get<0>(test_params); integrator->set_tolerance(TOL); const auto expected_result = std::get<1>(test_params); auto experiment = InhomogeneousDirichletUnitSquare(); experiment.run_offline(expected_result.offline_parameters); const auto result = experiment.run_online(expected_result.online_parameters.get(), *integrator); const auto expected_online_result = expected_result.online_result.get(); ASSERT_THAT(result.error_summary.l2, DoubleNear(expected_online_result.error_summary.l2, 1e-9)); ASSERT_THAT(result.error_summary.h1_semi, DoubleNear(expected_online_result.error_summary.h1_semi, 1e-7)); ASSERT_THAT(result.error_summary.h1, DoubleNear(expected_online_result.error_summary.h1, 1e-7)); } ExperimentResult make_convergence_test_result(const OfflineParameters & offline, const OnlineParameters & online, const ErrorSummary & error_summary) { return ExperimentResult() .with_offline_parameters(offline) .with_online_parameters(online) .with_online_result(OnlineResult().with_error_summary(error_summary)); } INSTANTIATE_TEST_CASE_P(direct_crank_nicolson, homogeneous_unit_square, ::testing::Combine( ::testing::Values(std::make_shared<crest::wave::DirectCrankNicolson<double>>()), ::testing::Values( make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.25), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.585458541734819) .with_h1_semi(0.584669994677925) .with_l2(0.0289167538286227) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.125), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.289671336214043) .with_h1_semi(0.2895515729457) .with_l2(0.00761102062470874) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.0625), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.144437769866845) .with_h1_semi(0.144415884917059) .with_l2(0.00220311548992367) ) ))); INSTANTIATE_TEST_CASE_P(iterative_crank_nicolson, homogeneous_unit_square, ::testing::Combine( ::testing::Values(std::make_shared<crest::wave::IterativeCrankNicolson<double>>()), ::testing::Values( make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.25), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.585458541735016) .with_h1_semi(0.584669994678112) .with_l2(0.0289167538288395) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.125), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.289671336213969) .with_h1_semi(0.289551572945625) .with_l2(0.00761102062490839) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.0625), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.144437769865326) .with_h1_semi(0.14441588491555) .with_l2(0.002203115490062) ) ))); INSTANTIATE_TEST_CASE_P(direct_crank_nicolson, inhomogeneous_unit_square, ::testing::Combine( ::testing::Values(std::make_shared<crest::wave::DirectCrankNicolson<double>>()), ::testing::Values( make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.25), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.587379118139992) .with_h1_semi(0.586591995031311) .with_l2(0.0289494785208848) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.125), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.290637174136373) .with_h1_semi(0.290517800933425) .with_l2(0.00761895620278423) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.0625), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.144922764238598) .with_h1_semi(0.144901003208638) .with_l2(0.0022048870589444) ) ))); INSTANTIATE_TEST_CASE_P(iterative_crank_nicolson, inhomogeneous_unit_square, ::testing::Combine( ::testing::Values(std::make_shared<crest::wave::IterativeCrankNicolson<double>>()), ::testing::Values( make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.25), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.587379371767793) .with_h1_semi(0.586592249024436) .with_l2(0.0289494776458804) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.125), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.290636831113929) .with_h1_semi(0.290517458731212) .with_l2(0.00761894063454651) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.0625), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.144922345898392) .with_h1_semi(0.144900585264829) .with_l2(0.00220483987973394) ) ))); INSTANTIATE_TEST_CASE_P(iterative_leapfrog, inhomogeneous_unit_square, ::testing::Combine( ::testing::Values(std::make_shared<crest::wave::IterativeLeapfrog<double>>()), ::testing::Values( make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.25), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.587378020587716) .with_h1_semi(0.586590792266803) .with_l2(0.0289506641927545) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.125), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.290625227318885) .with_h1_semi(0.290505802110512) .with_l2(0.00761996738873146) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.0625), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.144948283932812) .with_h1_semi(0.144926498965492) .with_l2(0.00220611626654336) ) ))); INSTANTIATE_TEST_CASE_P(lumped_leapfrog, inhomogeneous_unit_square, ::testing::Combine( ::testing::Values(std::make_shared<crest::wave::LumpedLeapfrog<double>>()), ::testing::Values( make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.25), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.582666537765749) .with_h1_semi(0.582159646452925) .with_l2(0.0240803754481128) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.125), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.288489719319695) .with_h1_semi(0.288431743027219) .with_l2(0.0057424077081183) ), make_convergence_test_result( OfflineParameters() .with_mesh_resolution(0.0625), OnlineParameters() .with_end_time(0.5) .with_sample_count(401), ErrorSummary() .with_h1(0.144206934687547) .with_h1_semi(0.144197839593727) .with_l2(0.00159275434745992) ) ))); <|endoftext|>
<commit_before>#include "../../source/thewizardplusplus/wizard_parser/parser/rule_parser.hpp" #include "../../source/thewizardplusplus/wizard_parser/parser/exception_parser.hpp" #include "../../source/thewizardplusplus/wizard_parser/lexer/token.hpp" #include "../../source/thewizardplusplus/wizard_parser/parser/ast_node.hpp" #include "../vendor/catch/catch.hpp" #include "../vendor/fakeit/fakeit.hpp" TEST_CASE("parser::exception_parser class", "[parser]") { using namespace thewizardplusplus::wizard_parser; using namespace thewizardplusplus::wizard_parser::parser::operators; SECTION("without tokens") { auto left_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(left_mock_parser, parse)) .Return(parser::parsing_result{}); fakeit::Fake(Dtor(left_mock_parser)); auto right_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(right_mock_parser, parse)) .Return(parser::parsing_result{}); fakeit::Fake(Dtor(right_mock_parser)); const auto exception_parser = parser::rule_parser::pointer{&left_mock_parser.get()} - parser::rule_parser::pointer{&right_mock_parser.get()}; const auto [ast, rest_tokens] = exception_parser->parse({}); CHECK(!ast.has_value()); CHECK(rest_tokens.empty()); fakeit::Verify(Method(left_mock_parser, parse)).Once(); fakeit::Verify(Method(right_mock_parser, parse)).Once(); } SECTION("without matches") { auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}}; auto left_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(left_mock_parser, parse)) .Return(parser::parsing_result{{}, tokens}); fakeit::Fake(Dtor(left_mock_parser)); auto right_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(right_mock_parser, parse)) .Return(parser::parsing_result{{}, tokens}); fakeit::Fake(Dtor(right_mock_parser)); const auto exception_parser = parser::rule_parser::pointer{&left_mock_parser.get()} - parser::rule_parser::pointer{&right_mock_parser.get()}; const auto [ast, rest_tokens] = exception_parser->parse(tokens); CHECK(!ast.has_value()); CHECK(rest_tokens == lexer::token_span{tokens}); fakeit::Verify(Method(left_mock_parser, parse)).Once(); fakeit::Verify(Method(right_mock_parser, parse)).Once(); } SECTION("with a left match") { auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}}; auto left_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(left_mock_parser, parse)) .Return(parser::parsing_result{ parser::ast_node{"one", "two", {}, 1}, lexer::token_span{tokens}.subspan(1) }); fakeit::Fake(Dtor(left_mock_parser)); auto right_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(right_mock_parser, parse)) .Return(parser::parsing_result{{}, tokens}); fakeit::Fake(Dtor(right_mock_parser)); const auto exception_parser = parser::rule_parser::pointer{&left_mock_parser.get()} - parser::rule_parser::pointer{&right_mock_parser.get()}; const auto [ast, rest_tokens] = exception_parser->parse(tokens); REQUIRE(ast.has_value()); CHECK(*ast == parser::ast_node{"one", "two", {}, 1}); CHECK(rest_tokens == lexer::token_span{tokens}.subspan(1)); fakeit::Verify(Method(left_mock_parser, parse)).Once(); fakeit::Verify(Method(right_mock_parser, parse)).Once(); } SECTION("with a right match") { auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}}; auto left_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(left_mock_parser, parse)) .Return(parser::parsing_result{{}, tokens}); fakeit::Fake(Dtor(left_mock_parser)); auto right_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(right_mock_parser, parse)) .Return(parser::parsing_result{ parser::ast_node{"one", "two", {}, 1}, lexer::token_span{tokens}.subspan(1) }); fakeit::Fake(Dtor(right_mock_parser)); const auto exception_parser = parser::rule_parser::pointer{&left_mock_parser.get()} - parser::rule_parser::pointer{&right_mock_parser.get()}; const auto [ast, rest_tokens] = exception_parser->parse(tokens); CHECK(!ast.has_value()); CHECK(rest_tokens == lexer::token_span{tokens}); fakeit::Verify(Method(left_mock_parser, parse)).Once(); fakeit::Verify(Method(right_mock_parser, parse)).Once(); } SECTION("with left and right matches") { auto tokens = lexer::token_group{ {"one", "two", 1}, {"three", "four", 4}, {"five", "six", 8} }; auto left_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(left_mock_parser, parse)) .Return(parser::parsing_result{ parser::ast_node{"one", "two", {}, 1}, lexer::token_span{tokens}.subspan(1) }); fakeit::Fake(Dtor(left_mock_parser)); auto right_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(right_mock_parser, parse)) .Return(parser::parsing_result{ parser::ast_node{"three", "four", {}, 4}, lexer::token_span{tokens}.subspan(2) }); fakeit::Fake(Dtor(right_mock_parser)); const auto exception_parser = parser::rule_parser::pointer{&left_mock_parser.get()} - parser::rule_parser::pointer{&right_mock_parser.get()}; const auto [ast, rest_tokens] = exception_parser->parse(tokens); CHECK(!ast.has_value()); CHECK(rest_tokens == lexer::token_span{tokens}.subspan(2)); fakeit::Verify(Method(left_mock_parser, parse)).Once(); fakeit::Verify(Method(right_mock_parser, parse)).Once(); } } <commit_msg>Upgrade and improve tests of the `parser::exception_parser` class<commit_after>#include "../../source/thewizardplusplus/wizard_parser/parser/rule_parser.hpp" #include "../../source/thewizardplusplus/wizard_parser/parser/exception_parser.hpp" #include "../../source/thewizardplusplus/wizard_parser/lexer/token.hpp" #include "../../source/thewizardplusplus/wizard_parser/parser/ast_node.hpp" #include "../vendor/catch/catch.hpp" #include "../vendor/fakeit/fakeit.hpp" TEST_CASE("parser::exception_parser class", "[parser]") { using namespace thewizardplusplus::wizard_parser; using namespace thewizardplusplus::wizard_parser::parser::operators; SECTION("without tokens") { auto left_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(left_mock_parser, parse)) .Return(parser::parsing_result{}); fakeit::Fake(Dtor(left_mock_parser)); auto right_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(right_mock_parser, parse)) .Return(parser::parsing_result{}); fakeit::Fake(Dtor(right_mock_parser)); const auto exception_parser = parser::rule_parser::pointer{&left_mock_parser.get()} - parser::rule_parser::pointer{&right_mock_parser.get()}; const auto [ast, rest_tokens] = exception_parser->parse({}); CHECK(!ast.has_value()); CHECK(rest_tokens.empty()); fakeit::Verify(Method(left_mock_parser, parse)).Once(); } SECTION("without matches") { auto tokens = lexer::token_group{ {"one", "two", 1}, {"three", "four", 4}, {"five", "six", 8} }; auto left_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(left_mock_parser, parse)) .Return(parser::parsing_result{{}, lexer::token_span{tokens}.subspan(1)}); fakeit::Fake(Dtor(left_mock_parser)); auto right_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(right_mock_parser, parse)) .Return(parser::parsing_result{{}, lexer::token_span{tokens}.subspan(2)}); fakeit::Fake(Dtor(right_mock_parser)); const auto exception_parser = parser::rule_parser::pointer{&left_mock_parser.get()} - parser::rule_parser::pointer{&right_mock_parser.get()}; const auto [ast, rest_tokens] = exception_parser->parse(tokens); CHECK(!ast.has_value()); CHECK(rest_tokens == lexer::token_span{tokens}.subspan(1)); fakeit::Verify(Method(left_mock_parser, parse)).Once(); } SECTION("with a left match") { auto tokens = lexer::token_group{ {"one", "two", 1}, {"three", "four", 4}, {"five", "six", 8} }; auto left_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(left_mock_parser, parse)) .Return(parser::parsing_result{ parser::ast_node{"one", "two", {}, 1}, lexer::token_span{tokens}.subspan(1) }); fakeit::Fake(Dtor(left_mock_parser)); auto right_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(right_mock_parser, parse)) .Return(parser::parsing_result{{}, lexer::token_span{tokens}.subspan(2)}); fakeit::Fake(Dtor(right_mock_parser)); const auto exception_parser = parser::rule_parser::pointer{&left_mock_parser.get()} - parser::rule_parser::pointer{&right_mock_parser.get()}; const auto [ast, rest_tokens] = exception_parser->parse(tokens); REQUIRE(ast.has_value()); CHECK(*ast == parser::ast_node{"one", "two", {}, 1}); CHECK(rest_tokens == lexer::token_span{tokens}.subspan(1)); fakeit::Verify(Method(left_mock_parser, parse)).Once(); fakeit::Verify(Method(right_mock_parser, parse)).Once(); } SECTION("with a right match") { auto tokens = lexer::token_group{ {"one", "two", 1}, {"three", "four", 4}, {"five", "six", 8} }; auto left_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(left_mock_parser, parse)) .Return(parser::parsing_result{{}, lexer::token_span{tokens}.subspan(1)}); fakeit::Fake(Dtor(left_mock_parser)); auto right_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(right_mock_parser, parse)) .Return(parser::parsing_result{ parser::ast_node{"three", "four", {}, 4}, lexer::token_span{tokens}.subspan(2) }); fakeit::Fake(Dtor(right_mock_parser)); const auto exception_parser = parser::rule_parser::pointer{&left_mock_parser.get()} - parser::rule_parser::pointer{&right_mock_parser.get()}; const auto [ast, rest_tokens] = exception_parser->parse(tokens); CHECK(!ast.has_value()); CHECK(rest_tokens == lexer::token_span{tokens}.subspan(1)); fakeit::Verify(Method(left_mock_parser, parse)).Once(); } SECTION("with left and right matches") { auto tokens = lexer::token_group{ {"one", "two", 1}, {"three", "four", 4}, {"five", "six", 8} }; auto left_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(left_mock_parser, parse)) .Return(parser::parsing_result{ parser::ast_node{"one", "two", {}, 1}, lexer::token_span{tokens}.subspan(1) }); fakeit::Fake(Dtor(left_mock_parser)); auto right_mock_parser = fakeit::Mock<parser::rule_parser>{}; fakeit::When(Method(right_mock_parser, parse)) .Return(parser::parsing_result{ parser::ast_node{"three", "four", {}, 4}, lexer::token_span{tokens}.subspan(2) }); fakeit::Fake(Dtor(right_mock_parser)); const auto exception_parser = parser::rule_parser::pointer{&left_mock_parser.get()} - parser::rule_parser::pointer{&right_mock_parser.get()}; const auto [ast, rest_tokens] = exception_parser->parse(tokens); CHECK(!ast.has_value()); CHECK(rest_tokens == lexer::token_span{tokens}); fakeit::Verify(Method(left_mock_parser, parse)).Once(); fakeit::Verify(Method(right_mock_parser, parse)).Once(); } } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "mazeprinter.h" #include "mazesearcher.h" #include "mazedata.h" #include "maze.h" class SearcherTest : public ::testing::Test { /* This gets run before each test */ virtual void SetUp() { maze = new Maze(16); maze->copyMazeFromFileData(japan2007, 256); barney = new MazeSearcher; // MazePrinter::printPlain(&testMaze); // char testMazeName[] = "../mazefiles/minos03f.maz"; // MazeResetWalls(); // SetGoal (DefaultGoal()); // FloodMazeClassic (DefaultGoal()); // ReadRealWallsFromFile (testMazeName); // UpdateEntireMazeFromRealWalls (); // FloodMazeClassic (DefaultGoal()); // MazeRemoveWall (Location (2, 0), NORTH); // EXPECT_EQ (0, Cost (DefaultGoal())); // EXPECT_EQ (46, Cost (Home())); // EXPECT_EQ (EAST, Direction (Location (2, 0))); // MouseInit(); } virtual void TearDown() { delete barney; delete maze; } protected: MazeSearcher *barney; Maze *maze; }; TEST_F (SearcherTest, Constructor) { EXPECT_EQ(0, barney->location()); EXPECT_EQ(NORTH, barney->heading()); EXPECT_EQ(NULL, barney->realMaze()); } TEST_F (SearcherTest, MouseSetPosition_PositionAsSet) { barney->setLocation(0x99); EXPECT_EQ(0x99, barney->location()); } TEST_F (SearcherTest, MouseSetHeading_HeadingAsSet) { barney->setHeading(EAST); EXPECT_EQ(EAST, barney->heading()); } TEST_F (SearcherTest, moveWithMaze_ChangeLocationOnly) { barney->setMazeWalls(japan2007, 256); barney->setLocation(0x00); barney->setHeading(NORTH); barney->move(); EXPECT_EQ(0x01, barney->location()); EXPECT_EQ(NORTH,barney->heading()); } TEST_F (SearcherTest, moveWithMaze_smallCircuitReturnToStart) { barney->setMazeWalls(japan2007, 256); barney->setLocation(0x39); barney->move(); barney->setHeading(EAST); barney->move(); barney->setHeading(SOUTH); barney->move(); barney->setHeading(WEST); barney->move(); barney->setHeading(NORTH); EXPECT_EQ(0x39, barney->location()); EXPECT_EQ(NORTH,barney->heading()); } /* * Tests whether the mouse can successfully follow a correctly setup * direction array and stop at the appropriate mLocation */ TEST_F (SearcherTest, MouseRunTo_EmptyMaze_StartToGoal_MouseAtGoal) { barney->setMazeWalls(emptyMaze, 256); int steps = barney->runTo(0x77); EXPECT_EQ(14,steps); EXPECT_EQ(0x77,barney->location()) << "{" << barney->location() << ", " << +barney->heading() << "}"; } /* * Tests whether the mouse can successfully follow a correctly setup * direction array and stop at the appropriate mLocation */ TEST_F (SearcherTest, MouseRunTo_EmptyMaze_ToGoalFromAnywhere) { barney->setMazeWalls(japan2007, 256); maze->copyMazeFromFileData(japan2007,256); maze->flood(0x77); int steps = barney->runTo(0x77); EXPECT_EQ(72,steps); for(uint16_t loc = 0; loc < maze->numCells(); loc++) { barney->setLocation(loc); barney->setHeading(WEST); barney->runTo(0x77); EXPECT_EQ(0x77, barney->location()) << "{" << barney->location() << ", " << +barney->heading() << "}"; } } /* * Tests whether the mouse can successfully follow a correctly setup * direction array and stop at the appropriate mLocation */ TEST_F (SearcherTest, MouseRunTo_EmptyMaze_ToStartFromAnywhere) { barney->setMazeWalls(japan2007, 256); maze->copyMazeFromFileData(japan2007,256); maze->flood(maze->home()); barney->setLocation(0x01); int steps = barney->runTo(maze->home()); EXPECT_EQ(1,steps); for(uint16_t loc = 1; loc < maze->numCells(); loc++) { barney->setLocation(loc); barney->setHeading(WEST); int steps = barney->runTo(maze->home()); EXPECT_EQ(maze->home(), barney->location()) << "{" << barney->location() << ", " << +barney->heading() << "}"; EXPECT_GT(steps,0); } } /* * Tests mouse getting lost in a cell with invalid direction * Taiwan2015 maze has closed in cells at 0x5C and 0x5D */ TEST_F (SearcherTest, MouseRunTo_RunToGoal_StartClosedIn_Error) { barney->setMazeWalls(taiwan2015, 256); barney->setLocation(0x5D); int steps = barney->runTo(maze->goal()); EXPECT_EQ(int(MazeSearcher::E_NO_ROUTE),steps); } /* * Tests mouse getting lost in a cell with invalid direction * Taiwan2015 maze has closed in cells at 0x5C and 0x5D */ TEST_F (SearcherTest, MouseRunTo_RunToGoal_TargetClosedIn_Error) { barney->setMazeWalls(taiwan2015, 256); int steps = barney->runTo(0x5C); EXPECT_EQ(int(MazeSearcher::E_NO_ROUTE),steps); } /* * Tests mouse getting lost because path is too long * Simulate by setting target outside maze */ //TEST_F (SearcherTest, MouseRunTo_RunToGoal_TargetTooFar_Error) { // barney->setMazeWalls(taiwan2015, 256); // int steps = barney->runTo(0x200); // EXPECT_EQ(int(MazeSearcher::E_ROUTE_TOO_LONG),steps); //} /* * Tests mouse search */ TEST_F (SearcherTest, MouseSearchTo_EmptyMaze_Success) { Maze * testMaze = new Maze(16); testMaze->setWall(0x07,EAST); barney->setRealMaze(testMaze); maze->setFloodType(Maze::MANHATTAN_FLOOD); int steps = barney->searchTo(0x77); EXPECT_EQ(16,steps); } /* * verbose mode prints out the maze after each step. */ TEST_F (SearcherTest, MouseRunTo_SearchToTarget_VerboseMode) { Maze * testMaze = new Maze(16); barney->setRealMaze(testMaze); //barney->setVerbose(true); barney->maze()->setFloodType(Maze::MANHATTAN_FLOOD); int steps = barney->searchTo(0x7); EXPECT_EQ(7,steps); } /* * */ TEST_F (SearcherTest, MouseRunTo_SearchToTarget_ManhattanFlood) { barney->setRealMaze(maze); barney->maze()->setFloodType(Maze::MANHATTAN_FLOOD); int steps = barney->searchTo(0x77); EXPECT_EQ(130,steps); // MazePrinter::printVisitedDirs(barney->maze()); } /* * */ TEST_F (SearcherTest, MouseSearchToTarget_RunLengthFlood) { barney->setRealMaze(maze); barney->maze()->setFloodType(Maze::RUNLENGTH_FLOOD); int steps = barney->searchTo(0x77); EXPECT_EQ(142,steps); // MazePrinter::printVisitedDirs(barney->maze()); } /* * */ TEST_F (SearcherTest, MouseSearchToTarget_LeftWall_Fail) { maze->copyMazeFromFileData(emptyMaze,256); barney->setVerbose(false); barney->setRealMaze(maze); barney->maze()->setFloodType(Maze::RUNLENGTH_FLOOD); barney->setSearchMethod(MazeSearcher::SEARCH_LEFT_WALL); int steps = barney->searchTo(0x77); EXPECT_EQ(MazeSearcher::E_ROUTE_TOO_LONG,steps); } /* * */ TEST_F (SearcherTest, MouseSearchToTarget_LeftWall_Succeed) { maze->copyMazeFromFileData(japan2007,256); barney->setRealMaze(maze); barney->maze()->setFloodType(Maze::RUNLENGTH_FLOOD); barney->setSearchMethod(MazeSearcher::SEARCH_LEFT_WALL); int steps = barney->searchTo(0x77); EXPECT_EQ(84,steps); } /* * */ TEST_F (SearcherTest, MouseRunTo_SearchOutAndIn_RunLengthFlood) { barney->setRealMaze(maze); maze->copyMazeFromFileData(japan2007,256); int steps = 0; std::cout << "\n\nRunlength pass 0: "; barney->maze()->testForSolution(); std::cout << barney->maze()->costDifference() << " " << steps << " steps" << std::endl; barney->maze()->setFloodType(Maze::RUNLENGTH_FLOOD); steps += barney->searchTo(0x77); steps += barney->searchTo(0x00); EXPECT_EQ(228,steps) << "The solution is not always correct. This is not right"; barney->maze()->testForSolution(); std::cout << "Runlength pass 1: "; std::cout << barney->maze()->costDifference() << " " << steps << " steps" << std::endl; steps += barney->searchTo(0x77); steps += barney->searchTo(0x00); barney->maze()->testForSolution(); std::cout << "Runlength pass 2: "; std::cout << barney->maze()->costDifference() << " " << steps << " steps" << std::endl; } /* * */ TEST_F (SearcherTest, MouseRunTo_SearchOutAndIn_ManhattanFlood) { barney->setRealMaze(maze); barney->maze()->setFloodType(Maze::MANHATTAN_FLOOD); int steps=0; std::cout << "\n\nManhattan pass 0: "; barney->maze()->testForSolution(); std::cout << barney->maze()->costDifference() << " " << steps << " steps" << std::endl; steps += barney->searchTo(0x77); steps += barney->searchTo(0x00); EXPECT_EQ(208,steps) << "The solution is not always correct. This is not right"; //MazePrinter::printVisitedDirs(barney->maze()); barney->maze()->testForSolution(); std::cout << "Manhattan pass 1: "; std::cout << barney->maze()->costDifference() << " " << steps << " steps" << std::endl; steps += barney->searchTo(0x77); steps += barney->searchTo(0x00); barney->maze()->testForSolution(); std::cout << "Manhattan pass 2: "; std::cout << barney->maze()->costDifference() << " " << steps << " steps" << std::endl; } <commit_msg>update MazeSearcher tests<commit_after>#include "gtest/gtest.h" #include "mazeprinter.h" #include "mazesearcher.h" #include "mazedata.h" #include "maze.h" class SearcherTest : public ::testing::Test { /* This gets run before each test */ virtual void SetUp() { maze = new Maze(16); maze->copyMazeFromFileData(japan2007, 256); searcher = new MazeSearcher; searcher->setRealMaze(maze); // MazePrinter::printPlain(&testMaze); // char testMazeName[] = "../mazefiles/minos03f.maz"; // MazeResetWalls(); // SetGoal (DefaultGoal()); // FloodMazeClassic (DefaultGoal()); // ReadRealWallsFromFile (testMazeName); // UpdateEntireMazeFromRealWalls (); // FloodMazeClassic (DefaultGoal()); // MazeRemoveWall (Location (2, 0), NORTH); // EXPECT_EQ (0, Cost (DefaultGoal())); // EXPECT_EQ (46, Cost (Home())); // EXPECT_EQ (EAST, Direction (Location (2, 0))); // MouseInit(); } virtual void TearDown() { delete searcher; delete maze; } protected: MazeSearcher *searcher; Maze *maze; }; TEST_F (SearcherTest, Constructor) { EXPECT_EQ(0, searcher->location()); EXPECT_EQ(NORTH, searcher->heading()); EXPECT_NE(nullptr, searcher->realMaze()); searcher->map()->flood(0x77); EXPECT_EQ(14,searcher->map()->cost(0x00)); } TEST_F (SearcherTest, MouseSetPosition_PositionAsSet) { searcher->setLocation(0x99); EXPECT_EQ(0x99, searcher->location()); } TEST_F (SearcherTest, MouseSetHeading_HeadingAsSet) { searcher->setHeading(EAST); EXPECT_EQ(EAST, searcher->heading()); } TEST_F (SearcherTest, moveWithMaze_ChangeLocationOnly) { searcher->move(); EXPECT_EQ(0x01, searcher->location()); EXPECT_EQ(NORTH,searcher->heading()); } TEST_F (SearcherTest, Turning_ChangeHeadingOnly) { searcher->setLocation(0x44); EXPECT_EQ(NORTH,searcher->heading()); searcher->turnRight(); EXPECT_EQ(EAST,searcher->heading()); searcher->turnRight(); EXPECT_EQ(SOUTH,searcher->heading()); searcher->turnRight(); EXPECT_EQ(WEST,searcher->heading()); searcher->turnRight(); EXPECT_EQ(NORTH,searcher->heading()); searcher->turnLeft(); EXPECT_EQ(WEST,searcher->heading()); searcher->turnLeft(); EXPECT_EQ(SOUTH,searcher->heading()); searcher->turnLeft(); EXPECT_EQ(EAST,searcher->heading()); searcher->turnLeft(); EXPECT_EQ(NORTH,searcher->heading()); searcher->turnAround(); EXPECT_EQ(SOUTH,searcher->heading()); EXPECT_EQ(0x44,searcher->location()); } TEST_F (SearcherTest, moveWithMaze_smallCircuitReturnToStart) { searcher->setLocation(0x39); searcher->move(); searcher->setHeading(EAST); searcher->move(); searcher->setHeading(SOUTH); searcher->move(); searcher->setHeading(WEST); searcher->move(); searcher->setHeading(NORTH); EXPECT_EQ(0x39, searcher->location()); EXPECT_EQ(NORTH,searcher->heading()); } /* * Tests whether the mouse can successfully follow a correctly setup * direction array and stop at the appropriate mLocation */ TEST_F (SearcherTest, MouseRunTo_EmptyMaze_StartToGoal_MouseAtGoal) { searcher->setMapFromFileData(emptyMaze, 256); int steps = searcher->runTo(0x77); EXPECT_EQ(14,steps); EXPECT_EQ(0x77,searcher->location()) << "{" << searcher->location() << ", " << +searcher->heading() << "}"; } /* * Tests whether the mouse can successfully follow a correctly setup * direction array and stop at the appropriate mLocation */ TEST_F (SearcherTest, MouseRunTo_EmptyMaze_ToGoalFromAnywhere) { searcher->setMapFromFileData(japan2007, 256); maze->copyMazeFromFileData(japan2007,256); maze->flood(0x77); int steps = searcher->runTo(0x77); EXPECT_EQ(72,steps); for(uint16_t loc = 0; loc < maze->numCells(); loc++) { searcher->setLocation(loc); searcher->setHeading(WEST); searcher->runTo(0x77); EXPECT_EQ(0x77, searcher->location()) << "{" << searcher->location() << ", " << +searcher->heading() << "}"; } } /* * Tests whether the mouse can successfully follow a correctly setup * direction array and stop at the appropriate mLocation */ TEST_F (SearcherTest, MouseRunTo_EmptyMaze_ToStartFromAnywhere) { searcher->setMapFromFileData(japan2007, 256); maze->copyMazeFromFileData(japan2007,256); maze->flood(maze->home()); searcher->setLocation(0x01); int steps = searcher->runTo(maze->home()); EXPECT_EQ(1,steps); for(uint16_t loc = 1; loc < maze->numCells(); loc++) { searcher->setLocation(loc); searcher->setHeading(WEST); int steps = searcher->runTo(maze->home()); EXPECT_EQ(maze->home(), searcher->location()) << "{" << searcher->location() << ", " << +searcher->heading() << "}"; EXPECT_GT(steps,0); } } /* * Tests mouse getting lost in a cell with invalid direction * Taiwan2015 maze has closed in cells at 0x5C and 0x5D */ TEST_F (SearcherTest, MouseRunTo_RunToGoal_StartClosedIn_Error) { searcher->setMapFromFileData(taiwan2015, 256); searcher->setLocation(0x5D); int steps = searcher->runTo(maze->goal()); EXPECT_EQ(int(MazeSearcher::E_NO_ROUTE),steps); } /* * Tests mouse getting lost in a cell with invalid direction * Taiwan2015 maze has closed in cells at 0x5C and 0x5D */ TEST_F (SearcherTest, MouseRunTo_RunToGoal_TargetClosedIn_Error) { searcher->setMapFromFileData(taiwan2015, 256); int steps = searcher->runTo(0x5C); EXPECT_EQ(int(MazeSearcher::E_NO_ROUTE),steps); } /* * Tests mouse getting lost because path is too long * Simulate by setting target outside maze */ //TEST_F (SearcherTest, MouseRunTo_RunToGoal_TargetTooFar_Error) { // barney->setMazeWalls(taiwan2015, 256); // int steps = barney->runTo(0x200); // EXPECT_EQ(int(MazeSearcher::E_ROUTE_TOO_LONG),steps); //} /* * Tests mouse search */ TEST_F (SearcherTest, MouseSearchTo_EmptyMaze_Success) { Maze * testMaze = new Maze(16); testMaze->setWall(0x07,EAST); testMaze->setFloodType(Maze::MANHATTAN_FLOOD); searcher->setRealMaze(testMaze); int steps = searcher->searchTo(0x77); EXPECT_EQ(16,steps); } /* * verbose mode prints out the maze after each step. */ TEST_F (SearcherTest, MouseRunTo_SearchToTarget_VerboseMode) { Maze * testMaze = new Maze(16); searcher->setRealMaze(testMaze); //barney->setVerbose(true); searcher->map()->setFloodType(Maze::MANHATTAN_FLOOD); int steps = searcher->searchTo(0x7); EXPECT_EQ(7,steps); } /* * */ TEST_F (SearcherTest, MouseRunTo_SearchToTarget_ManhattanFlood) { maze->copyMazeFromFileData(japan2007,256); searcher->setRealMaze(maze); searcher->map()->setFloodType(Maze::MANHATTAN_FLOOD); int steps = searcher->searchTo(0x77); EXPECT_EQ(130,steps); // MazePrinter::printVisitedDirs(barney->maze()); } /* * */ TEST_F (SearcherTest, MouseSearchToTarget_RunLengthFlood) { maze->copyMazeFromFileData(japan2007,256); searcher->setRealMaze(maze); searcher->setSearchMethod(MazeSearcher::SEARCH_NORMAL); searcher->map()->setFloodType(Maze::RUNLENGTH_FLOOD); int steps = searcher->searchTo(0x77); EXPECT_EQ(142,steps); } /* * */ TEST_F (SearcherTest, MouseSearchToTarget_LeftWall_Fail) { maze->copyMazeFromFileData(emptyMaze,256); searcher->setRealMaze(maze); searcher->map()->setFloodType(Maze::RUNLENGTH_FLOOD); searcher->setSearchMethod(MazeSearcher::SEARCH_LEFT_WALL); int steps = searcher->searchTo(0x77); EXPECT_EQ(MazeSearcher::E_ROUTE_TOO_LONG,steps); } /* * */ TEST_F (SearcherTest, MouseSearchToTarget_LeftWall_Succeed) { maze->copyMazeFromFileData(japan2007,256); searcher->setRealMaze(maze); searcher->map()->setFloodType(Maze::RUNLENGTH_FLOOD); searcher->setSearchMethod(MazeSearcher::SEARCH_LEFT_WALL); int steps = searcher->searchTo(0x77); EXPECT_EQ(84,steps); } /* * */ TEST_F (SearcherTest, MouseRunTo_SearchOutAndIn_RunLengthFlood) { searcher->map()->setFloodType(Maze::RUNLENGTH_FLOOD); int steps = 0; steps += searcher->searchTo(0x77); steps += searcher->searchTo(0x00); EXPECT_EQ(228,steps) << "The solution is not always correct. This is not right"; steps = 0; steps += searcher->searchTo(0x77); steps += searcher->searchTo(0x00); EXPECT_EQ(150,steps) << "The solution is not always correct. This is not right"; steps = searcher->searchTo(0x77); EXPECT_EQ(72,steps) << "The solution is not always correct. This is not right"; steps = searcher->searchTo(0x00); EXPECT_EQ(72,steps) << "The solution is not always correct. This is not right"; } /* * */ TEST_F (SearcherTest, MouseRunTo_SearchOutAndIn_ManhattanFlood) { searcher->map()->setFloodType(Maze::MANHATTAN_FLOOD); int steps=0; steps += searcher->searchTo(0x77); steps += searcher->searchTo(0x00); EXPECT_EQ(208,steps) << "The solution is not always correct. This is not right"; steps = 0; steps += searcher->searchTo(0x77); steps += searcher->searchTo(0x00); EXPECT_EQ(164,steps) << "The solution is not always correct. This is not right"; steps = searcher->searchTo(0x77); EXPECT_EQ(72,steps) << "The solution is not always correct. This is not right"; steps = searcher->searchTo(0x00); EXPECT_EQ(72,steps) << "The solution is not always correct. This is not right"; } <|endoftext|>
<commit_before>#include <Core/Resources/Resources.hpp> #include <Core/Utils/StdFilesystem.hpp> #include <Gui/Utils/KeyMappingManager.hpp> #include <catch2/catch.hpp> #include <QtGlobal> using namespace Ra; using namespace Ra::Gui; using Idx = KeyMappingManager::KeyMappingAction; using Ctx = KeyMappingManager::Context; class Dummy : public KeyMappingManageable<Dummy> { public: Dummy(); friend class KeyMappingManageable<Dummy>; private: bool checkIntegrity( const std::string& mess ) const; static void configureKeyMapping_impl(); // here in public for testing purpose public: #define KeyMappingDummy \ KMA_VALUE( TEST1 ) \ KMA_VALUE( TEST2 ) #define KMA_VALUE( XX ) static KeyMappingManager::KeyMappingAction XX; KeyMappingDummy #undef KMA_VALUE }; using KeyMapping = KeyMappingManageable<Dummy>; #define KMA_VALUE( XX ) Gui::KeyMappingManager::KeyMappingAction Dummy::XX; KeyMappingDummy #undef KMA_VALUE void Dummy::configureKeyMapping_impl() { KeyMapping::setContext( Gui::KeyMappingManager::getInstance()->getContext( "DummyContext" ) ); if ( Dummy::getContext().isInvalid() ) { LOG( Ra::Core::Utils::logINFO ) << "DummyContext not defined (maybe the configuration file do not contains it)"; return; } #define KMA_VALUE( XX ) \ XX = Gui::KeyMappingManager::getInstance()->getActionIndex( KeyMapping::getContext(), #XX ); KeyMappingDummy #undef KMA_VALUE } TEST_CASE( "Gui/Utils/KeyMappingManager", "[Gui][Gui/Utils][KeyMappingManager]" ) { QSettings settings( "RadiumUnitTests", "KeyMappingManager" ); settings.clear(); KeyMappingManager::createInstance(); auto mgr = Gui::KeyMappingManager::getInstance(); auto optionalPath {Core::Resources::getRadiumResourcesPath()}; auto resourcesRootDir {optionalPath.value_or( "[[Default resrouces path not found]]" )}; ///\todo how to check here ? auto defaultConfigFile = resourcesRootDir + #ifndef OS_MACOS std::string( "Configs/default.xml" ) #else std::string( "Configs/macos.xml" ) #endif ; SECTION( "key mapping file load" ) { REQUIRE( defaultConfigFile == mgr->getLoadedFilename() ); mgr->loadConfiguration( "dummy" ); REQUIRE( defaultConfigFile == mgr->getLoadedFilename() ); std::cout << std::filesystem::current_path() << "\n"; mgr->loadConfiguration( "data/keymapping-valid.xml" ); REQUIRE( "data/keymapping-valid.xml" == mgr->getLoadedFilename() ); // invalid xml should not be loaded, and switch to default mgr->loadConfiguration( "data/keymapping-invalid.xml" ); REQUIRE( defaultConfigFile == mgr->getLoadedFilename() ); // while config error are loaded, with error message mgr->loadConfiguration( "data/keymapping-double-actions.xml" ); REQUIRE( "data/keymapping-double-actions.xml" == mgr->getLoadedFilename() ); // bad tag load defaults mgr->loadConfiguration( "data/keymapping-bad-tag.xml" ); REQUIRE( defaultConfigFile == mgr->getLoadedFilename() ); // bad main tag loads with a warning mgr->loadConfiguration( "data/keymapping-bad-main.xml" ); REQUIRE( "data/keymapping-bad-main.xml" == mgr->getLoadedFilename() ); } SECTION( "getAction" ) { mgr->loadConfiguration( "data/keymapping-valid.xml" ); // check context auto cameraContext {mgr->getContext( "CameraContext" )}; REQUIRE( cameraContext.isValid() ); REQUIRE( mgr->getContextName( cameraContext ) == "CameraContext" ); auto viewerContext {mgr->getContext( "ViewerContext" )}; REQUIRE( viewerContext.isValid() ); REQUIRE( viewerContext != cameraContext ); auto invalidContext {mgr->getContext( "InvalidContext" )}; REQUIRE( invalidContext.isInvalid() ); // invalidContext index returns "Invalid" context name REQUIRE( mgr->getContextName( Ctx {} ) == "Invalid" ); REQUIRE( mgr->getContextName( Ctx {42} ) == "Invalid" ); // test on action auto validAction {mgr->getAction( cameraContext, Qt::LeftButton, Qt::NoModifier, -1 )}; REQUIRE( validAction.isValid() ); REQUIRE( validAction == mgr->getActionIndex( cameraContext, "TRACKBALLCAMERA_ROTATE" ) ); REQUIRE( mgr->getActionIndex( Ctx {}, "TRACKBALLCAMERA_ROTATE" ).isInvalid() ); REQUIRE( mgr->getActionIndex( Ctx {42}, "TRACKBALLCAMERA_ROTATE" ).isInvalid() ); REQUIRE( mgr->getActionName( cameraContext, validAction ) == "TRACKBALLCAMERA_ROTATE" ); // invalid action index returns "Invalid" action name REQUIRE( mgr->getActionName( cameraContext, Idx {} ) == "Invalid" ); // modifiers as key are ignored validAction = mgr->getAction( cameraContext, Qt::LeftButton, Qt::ShiftModifier, -1 ); auto action2 { mgr->getAction( cameraContext, Qt::LeftButton, Qt::ShiftModifier, Qt::Key_Shift )}; REQUIRE( validAction == action2 ); // tests some invalid actions auto invalidAction {mgr->getAction( cameraContext, Qt::LeftButton, Qt::AltModifier, -1 )}; REQUIRE( invalidAction.isInvalid() ); REQUIRE( invalidAction != mgr->getActionIndex( cameraContext, "TRACKBALLCAMERA_ROTATE" ) ); REQUIRE( mgr->getAction( Idx {}, Qt::LeftButton, Qt::AltModifier, -1 ).isInvalid() ); REQUIRE( mgr->getAction( Idx {}, Qt::LeftButton, Qt::AltModifier, 1 ).isInvalid() ); REQUIRE( mgr->getAction( Idx {}, Qt::LeftButton, Qt::NoModifier, -1 ).isInvalid() ); REQUIRE( mgr->getAction( Idx {}, Qt::RightButton, Qt::AltModifier, -1 ).isInvalid() ); // with key and modifiers validAction = mgr->getAction( viewerContext, Qt::RightButton, Qt::NoModifier, Qt::Key_V ); REQUIRE( validAction.isValid() ); REQUIRE( validAction == mgr->getActionIndex( viewerContext, "VIEWER_PICKING_VERTEX" ) ); // action index REQUIRE( mgr->getActionIndex( viewerContext, "UnkownAction" ).isInvalid() ); validAction = mgr->getAction( viewerContext, Qt::NoButton, Qt::ControlModifier, Qt::Key_W ); REQUIRE( validAction.isValid() ); REQUIRE( validAction == mgr->getActionIndex( viewerContext, "VIEWER_TOGGLE_WIREFRAME" ) ); // action are context dependent invalidAction = mgr->getAction( viewerContext, Qt::LeftButton, Qt::NoModifier, -1 ); REQUIRE( invalidAction.isInvalid() ); REQUIRE( mgr->getActionIndex( cameraContext, "VIEWER_TOGGLE_WIREFRAME" ).isInvalid() ); } SECTION( "listener" ) { // dummy1.xml // LeftButton triggers TEST1, RightButton triggers TEST2 // (with index TEST1 : 0, TEST2: 1) // dummy2.xml is the other way round dummy2.xml // LeftButton triggers TEST2, RightButton triggers TEST1 // (with index TEST2: 0, TEST1: 1) auto didx = mgr->addListener( Dummy::configureKeyMapping ); mgr->loadConfiguration( "data/dummy1.xml" ); // action index correspond to configuration auto test1Idx = mgr->getActionIndex( Dummy::getContext(), "TEST1" ); auto test2Idx = mgr->getActionIndex( Dummy::getContext(), "TEST2" ); REQUIRE( test1Idx == mgr->getAction( Dummy::getContext(), Qt::LeftButton, Qt::NoModifier, -1 ) ); REQUIRE( test2Idx == mgr->getAction( Dummy::getContext(), Qt::RightButton, Qt::NoModifier, -1 ) ); // and set in Dummy class REQUIRE( Dummy::TEST1 == test1Idx ); REQUIRE( Dummy::TEST2 == test2Idx ); // reload trigger configureKeyMapping and update binding/action index mgr->loadConfiguration( "data/dummy2.xml" ); auto test1Idx2 = mgr->getActionIndex( Dummy::getContext(), "TEST1" ); auto test2Idx2 = mgr->getActionIndex( Dummy::getContext(), "TEST2" ); // action index have been updated in Dummy class (by observation) REQUIRE( Dummy::TEST1 == mgr->getAction( Dummy::getContext(), Qt::RightButton, Qt::NoModifier, -1 ) ); REQUIRE( Dummy::TEST2 == mgr->getAction( Dummy::getContext(), Qt::LeftButton, Qt::NoModifier, -1 ) ); // and do not corresponds to the old one REQUIRE( test1Idx != Dummy::TEST1 ); REQUIRE( test2Idx != Dummy::TEST2 ); // remove listener and relaod do not update action index mgr->removeListener( didx ); mgr->loadConfiguration( "data/dummy1.xml" ); // action index have been reverted REQUIRE( test1Idx == mgr->getAction( Dummy::getContext(), Qt::LeftButton, Qt::NoModifier, -1 ) ); REQUIRE( test2Idx == mgr->getAction( Dummy::getContext(), Qt::RightButton, Qt::NoModifier, -1 ) ); // but not updated in Dummy class REQUIRE( Dummy::TEST1 != test1Idx ); REQUIRE( Dummy::TEST1 == test1Idx2 ); REQUIRE( Dummy::TEST2 != test2Idx ); REQUIRE( Dummy::TEST2 == test2Idx2 ); } } <commit_msg>[tests] Store QSettings org and app name globally.<commit_after>#include <Core/Resources/Resources.hpp> #include <Core/Utils/StdFilesystem.hpp> #include <Gui/Utils/KeyMappingManager.hpp> #include <catch2/catch.hpp> #include <QtGlobal> using namespace Ra; using namespace Ra::Gui; using Idx = KeyMappingManager::KeyMappingAction; using Ctx = KeyMappingManager::Context; class Dummy : public KeyMappingManageable<Dummy> { public: Dummy(); friend class KeyMappingManageable<Dummy>; private: bool checkIntegrity( const std::string& mess ) const; static void configureKeyMapping_impl(); // here in public for testing purpose public: #define KeyMappingDummy \ KMA_VALUE( TEST1 ) \ KMA_VALUE( TEST2 ) #define KMA_VALUE( XX ) static KeyMappingManager::KeyMappingAction XX; KeyMappingDummy #undef KMA_VALUE }; using KeyMapping = KeyMappingManageable<Dummy>; #define KMA_VALUE( XX ) Gui::KeyMappingManager::KeyMappingAction Dummy::XX; KeyMappingDummy #undef KMA_VALUE void Dummy::configureKeyMapping_impl() { KeyMapping::setContext( Gui::KeyMappingManager::getInstance()->getContext( "DummyContext" ) ); if ( Dummy::getContext().isInvalid() ) { LOG( Ra::Core::Utils::logINFO ) << "DummyContext not defined (maybe the configuration file do not contains it)"; return; } #define KMA_VALUE( XX ) \ XX = Gui::KeyMappingManager::getInstance()->getActionIndex( KeyMapping::getContext(), #XX ); KeyMappingDummy #undef KMA_VALUE } TEST_CASE( "Gui/Utils/KeyMappingManager", "[Gui][Gui/Utils][KeyMappingManager]" ) { QCoreApplication::setOrganizationName( "RadiumUnitTests" ); QCoreApplication::setApplicationName( "KeyMappingManager" ); QSettings settings; settings.clear(); KeyMappingManager::createInstance(); auto mgr = Gui::KeyMappingManager::getInstance(); auto optionalPath {Core::Resources::getRadiumResourcesPath()}; auto resourcesRootDir {optionalPath.value_or( "[[Default resrouces path not found]]" )}; ///\todo how to check here ? auto defaultConfigFile = resourcesRootDir + #ifndef OS_MACOS std::string( "Configs/default.xml" ) #else std::string( "Configs/macos.xml" ) #endif ; SECTION( "key mapping file load" ) { REQUIRE( defaultConfigFile == mgr->getLoadedFilename() ); mgr->loadConfiguration( "dummy" ); REQUIRE( defaultConfigFile == mgr->getLoadedFilename() ); std::cout << std::filesystem::current_path() << "\n"; mgr->loadConfiguration( "data/keymapping-valid.xml" ); REQUIRE( "data/keymapping-valid.xml" == mgr->getLoadedFilename() ); // invalid xml should not be loaded, and switch to default mgr->loadConfiguration( "data/keymapping-invalid.xml" ); REQUIRE( defaultConfigFile == mgr->getLoadedFilename() ); // while config error are loaded, with error message mgr->loadConfiguration( "data/keymapping-double-actions.xml" ); REQUIRE( "data/keymapping-double-actions.xml" == mgr->getLoadedFilename() ); // bad tag load defaults mgr->loadConfiguration( "data/keymapping-bad-tag.xml" ); REQUIRE( defaultConfigFile == mgr->getLoadedFilename() ); // bad main tag loads with a warning mgr->loadConfiguration( "data/keymapping-bad-main.xml" ); REQUIRE( "data/keymapping-bad-main.xml" == mgr->getLoadedFilename() ); } SECTION( "getAction" ) { mgr->loadConfiguration( "data/keymapping-valid.xml" ); // check context auto cameraContext {mgr->getContext( "CameraContext" )}; REQUIRE( cameraContext.isValid() ); REQUIRE( mgr->getContextName( cameraContext ) == "CameraContext" ); auto viewerContext {mgr->getContext( "ViewerContext" )}; REQUIRE( viewerContext.isValid() ); REQUIRE( viewerContext != cameraContext ); auto invalidContext {mgr->getContext( "InvalidContext" )}; REQUIRE( invalidContext.isInvalid() ); // invalidContext index returns "Invalid" context name REQUIRE( mgr->getContextName( Ctx {} ) == "Invalid" ); REQUIRE( mgr->getContextName( Ctx {42} ) == "Invalid" ); // test on action auto validAction {mgr->getAction( cameraContext, Qt::LeftButton, Qt::NoModifier, -1 )}; REQUIRE( validAction.isValid() ); REQUIRE( validAction == mgr->getActionIndex( cameraContext, "TRACKBALLCAMERA_ROTATE" ) ); REQUIRE( mgr->getActionIndex( Ctx {}, "TRACKBALLCAMERA_ROTATE" ).isInvalid() ); REQUIRE( mgr->getActionIndex( Ctx {42}, "TRACKBALLCAMERA_ROTATE" ).isInvalid() ); REQUIRE( mgr->getActionName( cameraContext, validAction ) == "TRACKBALLCAMERA_ROTATE" ); // invalid action index returns "Invalid" action name REQUIRE( mgr->getActionName( cameraContext, Idx {} ) == "Invalid" ); // modifiers as key are ignored validAction = mgr->getAction( cameraContext, Qt::LeftButton, Qt::ShiftModifier, -1 ); auto action2 { mgr->getAction( cameraContext, Qt::LeftButton, Qt::ShiftModifier, Qt::Key_Shift )}; REQUIRE( validAction == action2 ); // tests some invalid actions auto invalidAction {mgr->getAction( cameraContext, Qt::LeftButton, Qt::AltModifier, -1 )}; REQUIRE( invalidAction.isInvalid() ); REQUIRE( invalidAction != mgr->getActionIndex( cameraContext, "TRACKBALLCAMERA_ROTATE" ) ); REQUIRE( mgr->getAction( Idx {}, Qt::LeftButton, Qt::AltModifier, -1 ).isInvalid() ); REQUIRE( mgr->getAction( Idx {}, Qt::LeftButton, Qt::AltModifier, 1 ).isInvalid() ); REQUIRE( mgr->getAction( Idx {}, Qt::LeftButton, Qt::NoModifier, -1 ).isInvalid() ); REQUIRE( mgr->getAction( Idx {}, Qt::RightButton, Qt::AltModifier, -1 ).isInvalid() ); // with key and modifiers validAction = mgr->getAction( viewerContext, Qt::RightButton, Qt::NoModifier, Qt::Key_V ); REQUIRE( validAction.isValid() ); REQUIRE( validAction == mgr->getActionIndex( viewerContext, "VIEWER_PICKING_VERTEX" ) ); // action index REQUIRE( mgr->getActionIndex( viewerContext, "UnkownAction" ).isInvalid() ); validAction = mgr->getAction( viewerContext, Qt::NoButton, Qt::ControlModifier, Qt::Key_W ); REQUIRE( validAction.isValid() ); REQUIRE( validAction == mgr->getActionIndex( viewerContext, "VIEWER_TOGGLE_WIREFRAME" ) ); // action are context dependent invalidAction = mgr->getAction( viewerContext, Qt::LeftButton, Qt::NoModifier, -1 ); REQUIRE( invalidAction.isInvalid() ); REQUIRE( mgr->getActionIndex( cameraContext, "VIEWER_TOGGLE_WIREFRAME" ).isInvalid() ); } SECTION( "listener" ) { // dummy1.xml // LeftButton triggers TEST1, RightButton triggers TEST2 // (with index TEST1 : 0, TEST2: 1) // dummy2.xml is the other way round dummy2.xml // LeftButton triggers TEST2, RightButton triggers TEST1 // (with index TEST2: 0, TEST1: 1) auto didx = mgr->addListener( Dummy::configureKeyMapping ); mgr->loadConfiguration( "data/dummy1.xml" ); // action index correspond to configuration auto test1Idx = mgr->getActionIndex( Dummy::getContext(), "TEST1" ); auto test2Idx = mgr->getActionIndex( Dummy::getContext(), "TEST2" ); REQUIRE( test1Idx == mgr->getAction( Dummy::getContext(), Qt::LeftButton, Qt::NoModifier, -1 ) ); REQUIRE( test2Idx == mgr->getAction( Dummy::getContext(), Qt::RightButton, Qt::NoModifier, -1 ) ); // and set in Dummy class REQUIRE( Dummy::TEST1 == test1Idx ); REQUIRE( Dummy::TEST2 == test2Idx ); // reload trigger configureKeyMapping and update binding/action index mgr->loadConfiguration( "data/dummy2.xml" ); auto test1Idx2 = mgr->getActionIndex( Dummy::getContext(), "TEST1" ); auto test2Idx2 = mgr->getActionIndex( Dummy::getContext(), "TEST2" ); // action index have been updated in Dummy class (by observation) REQUIRE( Dummy::TEST1 == mgr->getAction( Dummy::getContext(), Qt::RightButton, Qt::NoModifier, -1 ) ); REQUIRE( Dummy::TEST2 == mgr->getAction( Dummy::getContext(), Qt::LeftButton, Qt::NoModifier, -1 ) ); // and do not corresponds to the old one REQUIRE( test1Idx != Dummy::TEST1 ); REQUIRE( test2Idx != Dummy::TEST2 ); // remove listener and relaod do not update action index mgr->removeListener( didx ); mgr->loadConfiguration( "data/dummy1.xml" ); // action index have been reverted REQUIRE( test1Idx == mgr->getAction( Dummy::getContext(), Qt::LeftButton, Qt::NoModifier, -1 ) ); REQUIRE( test2Idx == mgr->getAction( Dummy::getContext(), Qt::RightButton, Qt::NoModifier, -1 ) ); // but not updated in Dummy class REQUIRE( Dummy::TEST1 != test1Idx ); REQUIRE( Dummy::TEST1 == test1Idx2 ); REQUIRE( Dummy::TEST2 != test2Idx ); REQUIRE( Dummy::TEST2 == test2Idx2 ); } } <|endoftext|>
<commit_before>#include "ngraph.h" #include <PCU.h> #include <unordered_set> #include <vector> #include <engpar_support.h> namespace agi { typedef std::unordered_set<GraphVertex*> VertexVector; //TODO: Make a vector by using a "tag" on the edges to detect added or not typedef std::unordered_set<GraphEdge*> EdgeVector; void Ngraph::updateGhostOwners(Migration* plan) { PCU_Comm_Begin(); Migration::iterator itr; for (itr = plan->begin();itr!=plan->end();itr++) { GraphVertex* v = *itr; gid_t gid = globalID(v); part_t toSend = plan->get(v); GraphIterator* gitr = adjacent(v); GraphVertex* other; while ((other=iterate(gitr))) { part_t own = owner(other); if (own!=PCU_Comm_Self()) { PCU_COMM_PACK(own,gid); PCU_COMM_PACK(own,toSend); } } destroy(gitr); } PCU_Comm_Send(); while (PCU_Comm_Receive()) { gid_t gid; part_t own; PCU_COMM_UNPACK(gid); PCU_COMM_UNPACK(own); lid_t lid = vtx_mapping[gid]; if (lid>=num_local_verts) { owners[lid-num_local_verts]=own; } } } /* Finds the vertices and edges that need to be communicated Also stores the local vertices and edges that will be owned on this part after migration */ void getAffected(Ngraph* g, Migration* plan, VertexVector& verts, EdgeVector* edges) { //verts.reserve(plan->size()); Migration::iterator itr; for (itr = plan->begin();itr!=plan->end();itr++) { GraphVertex* v = *itr; part_t toSend = plan->get(v); if (toSend!=PCU_Comm_Self()) { verts.insert(v); } } //For each edge type for (etype t = 0;t<g->numEdgeTypes();t++) { //edges[t].reserve(verts.size()); VertexVector::iterator itr; //loop through the vertices being sent for (itr = verts.begin();itr!=verts.end();itr++) { GraphIterator* gitr =g->adjacent(*itr); GraphEdge* e; GraphEdge* old=NULL; GraphVertex* v; while ((v = g->iterate(gitr))) { e=g->edge(gitr); if (old==NULL||e!=old) edges[t].insert(e); } g->destroy(gitr); } } } void addVertices(Ngraph* g, std::vector<gid_t>& ownedVerts, VertexVector& verts, std::vector<wgt_t>& weights, std::vector<part_t>& originalOwners) { VertexIterator* vitr = g->begin(); GraphVertex* v; while ((v = g->iterate(vitr))) { if (verts.find(v)==verts.end()) { ownedVerts.push_back(g->globalID(v)); weights.push_back(g->weight(v)); originalOwners.push_back(g->originalOwner(v)); } } } void addCoords(Ngraph* g,VertexVector& verts,coord_t* cs,lid_t& size) { VertexIterator* vitr = g->begin(); GraphVertex* v; while ((v = g->iterate(vitr))) { if (verts.find(v)==verts.end()) { const coord_t& c = g->coord(v); for (int i=0;i<3;i++) cs[size][i] = c[i]; size++; } } } void addEdges(Ngraph* g, Migration* plan, std::vector<gid_t>& ownedEdges, std::vector<wgt_t>& edgeWeights, std::vector<lid_t>& degrees,std::vector<gid_t>& pins, std::unordered_map<gid_t,part_t>& ghost_owners, std::unordered_set<gid_t>& addedEdges, etype t) { EdgeIterator* itr = g->begin(t); GraphEdge* e; while ((e = g->iterate(itr))) { agi::PinIterator* pitr = g->pins(e); agi::GraphVertex* end; while ((end=g->iterate(pitr))) if (plan->has(end)) break; g->destroy(pitr); if (!end) { //Add the Edge gid_t gid = g->globalID(e); ownedEdges.push_back(gid); edgeWeights.push_back(g->weight(e)); degrees.push_back(g->degree(e)); addedEdges.insert(gid); pitr=g->pins(e); while ((end=g->iterate(pitr))) { gid_t other_gid = g->globalID(end); pins.push_back(other_gid); part_t owner = g->owner(end); if (owner!=PCU_Comm_Self()) ghost_owners[other_gid] = owner; } g->destroy(pitr); } } g->destroy(itr); } void Ngraph::sendVertex(GraphVertex* vtx, part_t toSend) { gid_t gid = globalID(vtx); wgt_t w = weight(vtx); part_t old_owner = originalOwner(vtx); PCU_COMM_PACK(toSend,gid); PCU_COMM_PACK(toSend,w); PCU_COMM_PACK(toSend,old_owner); } void Ngraph::recvVertex(std::vector<gid_t>& recv, std::vector<wgt_t>& wgts, std::vector<part_t>& old_owners) { gid_t gid; PCU_COMM_UNPACK(gid); wgt_t w; PCU_COMM_UNPACK(w); part_t old_owner; PCU_COMM_UNPACK(old_owner); recv.push_back(gid); wgts.push_back(w); old_owners.push_back(old_owner); } void Ngraph::sendCoord(GraphVertex* vtx, part_t toSend) { const coord_t& c = coord(vtx); PCU_COMM_PACK(toSend,c[0]); PCU_COMM_PACK(toSend,c[1]); PCU_COMM_PACK(toSend,c[2]); } void Ngraph::recvCoord(coord_t* cs,lid_t& size) { PCU_COMM_UNPACK(cs[size][0]); PCU_COMM_UNPACK(cs[size][1]); PCU_COMM_UNPACK(cs[size][2]); size++; } void Ngraph::sendEdges(Migration* plan, EdgeVector& affectedEdges) { EdgeVector::iterator eitr; for (eitr = affectedEdges.begin();eitr!=affectedEdges.end(); eitr++) { GraphEdge* e = *eitr; gid_t* pin; part_t* pin_owners; lid_t deg=0; gid_t id; wgt_t eweight = weight(e); std::unordered_set<part_t> residence; if (isHyperGraph) { id = globalID(e); pin = new gid_t[degree(e)]; pin_owners = new part_t[degree(e)]; agi::PinIterator* pitr = this->pins(e); agi::GraphVertex* vtx; for (lid_t i=0;i<degree(e);i++) { vtx = iterate(pitr); part_t o = owner(vtx); if (plan->has(vtx)) o= plan->get(vtx); pin_owners[deg]=o; pin[deg++] = globalID(vtx); residence.insert(o); } destroy(pitr); } else { id = localID(e); pin = new gid_t[2]; pin_owners = new part_t[2]; GraphVertex* source = u(e); pin_owners[deg] = owner(source); pin[deg++] = globalID(source); GraphVertex* dest = v(e); part_t o = owner(dest); if (plan->has(dest)) o= plan->get(dest); pin_owners[deg] = o; pin[deg++] = globalID(dest); assert(plan->has(source)); pin_owners[0] = plan->get(source); residence.insert(plan->get(source)); } std::unordered_set<part_t>::iterator sitr; for (sitr=residence.begin();sitr!=residence.end();sitr++) { PCU_COMM_PACK(*sitr,id); PCU_COMM_PACK(*sitr,eweight); PCU_COMM_PACK(*sitr,deg); PCU_Comm_Pack(*sitr,pin,deg*sizeof(gid_t)); PCU_Comm_Pack(*sitr,pin_owners,deg*sizeof(part_t)); } delete [] pin; delete [] pin_owners; } } void Ngraph::recvEdges(std::unordered_set<gid_t>& addedEdges, std::vector<gid_t>& ownedEdges, std::vector<wgt_t>& edgeWeights, std::vector<lid_t>& degrees, std::vector<gid_t>& pins, std::unordered_map<gid_t,part_t>& ghost_owners, etype t) { while (PCU_Comm_Receive()) { gid_t id; wgt_t eweight; lid_t deg; PCU_COMM_UNPACK(id); PCU_COMM_UNPACK(eweight); PCU_COMM_UNPACK(deg); gid_t* pin = new gid_t[deg]; part_t* pin_owners = new part_t[deg]; PCU_Comm_Unpack(pin,deg*sizeof(gid_t)); PCU_Comm_Unpack(pin_owners,deg*sizeof(part_t)); if (isHyperGraph) { if (addedEdges.find(id)!=addedEdges.end()) { delete [] pin; delete [] pin_owners; continue; } } addedEdges.insert(id); edge_mapping[t][id]=0; ownedEdges.push_back(id); edgeWeights.push_back(eweight); degrees.push_back(deg); for (lid_t i=0;i<deg;i++) { pins.push_back(pin[i]); if (pin_owners[i]!=PCU_Comm_Self()) ghost_owners[pin[i]]=pin_owners[i]; } delete [] pin; delete [] pin_owners; } } void Ngraph::migrate(Migration* plan) { int nt = num_types; updateGhostOwners(plan); VertexVector affectedVerts; EdgeVector* affectedEdges = new EdgeVector[nt]; std::vector<gid_t> ownedVerts; std::vector<wgt_t> vertWeights; std::vector<part_t> old_owners; std::vector<gid_t>* ownedEdges = new std::vector<gid_t>[nt]; std::vector<wgt_t>* edgeWeights = new std::vector<wgt_t>[nt]; std::vector<lid_t>* degrees = new std::vector<lid_t>[nt]; std::vector<gid_t>* pins = new std::vector<gid_t>[nt]; std::unordered_map<gid_t,part_t> ghost_owners; ownedVerts.reserve(num_local_verts); vertWeights.reserve(num_local_verts); getAffected(this,plan,affectedVerts,affectedEdges); addVertices(this,ownedVerts,affectedVerts,vertWeights,old_owners); std::unordered_set<gid_t>* addedEdges = new std::unordered_set<gid_t>[nt]; for (etype i=0;i<nt;i++) addEdges(this,plan,ownedEdges[i],edgeWeights[i],degrees[i],pins[i], ghost_owners,addedEdges[i],i); //Send and recieve vertices Migration::iterator itr; PCU_Comm_Begin(); for (itr = plan->begin();itr!=plan->end();itr++) { sendVertex(*itr,plan->get(*itr)); } PCU_Comm_Send(); while (PCU_Comm_Receive()) { recvVertex(ownedVerts,vertWeights,old_owners); } //Send and recieve coordinates coord_t* cs=NULL; if (hasCoords()) { lid_t size=0; cs = new coord_t[ownedVerts.size()]; addCoords(this,affectedVerts,cs,size); Migration::iterator itr; PCU_Comm_Begin(); for (itr = plan->begin();itr!=plan->end();itr++) { sendCoord(*itr,plan->get(*itr)); } PCU_Comm_Send(); while (PCU_Comm_Receive()) { recvCoord(cs,size); } assert(size==(lid_t)ownedVerts.size()); } //Send and receive edges of each type for (etype t = 0;t < nt;t++) { PCU_Comm_Begin(); sendEdges(plan,affectedEdges[t]); PCU_Comm_Send(); recvEdges(addedEdges[t],ownedEdges[t],edgeWeights[t],degrees[t], pins[t],ghost_owners,t); } delete [] addedEdges; //Construct the migrated graph constructVerts(isHyperGraph,ownedVerts.size(),&ownedVerts[0],&vertWeights[0]); if (cs) setCoords(cs); for (int i=0;i<nt;i++) { constructEdges(ownedEdges[i].size(),&ownedEdges[i][0], &degrees[i][0],&pins[i][0]); setEdgeWeights(edgeWeights[i],i); } constructGhosts(ghost_owners); setOriginalOwners(old_owners); delete [] affectedEdges; delete [] ownedEdges; delete [] edgeWeights; delete [] degrees; delete [] pins; delete [] cs; delete plan; } PartitionMap* Ngraph::getPartition() { if (EnGPar_Is_Log_Open()) { char message[20]; sprintf(message,"getPartition\n"); EnGPar_Log_Function(message); } PCU_Comm_Begin(); VertexIterator* itr = begin(); GraphVertex* vtx; while ((vtx = iterate(itr))) { gid_t v = globalID(vtx); PCU_COMM_PACK(originalOwner(vtx),v); } PCU_Comm_Send(); PartitionMap* map = new PartitionMap; while (PCU_Comm_Receive()) { gid_t v; PCU_COMM_UNPACK(v); map->insert(std::make_pair(v,PCU_Comm_Sender())); } if (EnGPar_Is_Log_Open()) { EnGPar_End_Function(); } PCU_Barrier(); return map; } } <commit_msg>Add some reserves in migration to potentially speedup by reducing memory reallocation<commit_after>#include "ngraph.h" #include <PCU.h> #include <unordered_set> #include <vector> #include <engpar_support.h> namespace agi { typedef std::unordered_set<GraphVertex*> VertexVector; //TODO: Make a vector by using a "tag" on the edges to detect added or not typedef std::unordered_set<GraphEdge*> EdgeVector; void Ngraph::updateGhostOwners(Migration* plan) { PCU_Comm_Begin(); Migration::iterator itr; for (itr = plan->begin();itr!=plan->end();itr++) { GraphVertex* v = *itr; gid_t gid = globalID(v); part_t toSend = plan->get(v); GraphIterator* gitr = adjacent(v); GraphVertex* other; while ((other=iterate(gitr))) { part_t own = owner(other); if (own!=PCU_Comm_Self()) { PCU_COMM_PACK(own,gid); PCU_COMM_PACK(own,toSend); } } destroy(gitr); } PCU_Comm_Send(); while (PCU_Comm_Receive()) { gid_t gid; part_t own; PCU_COMM_UNPACK(gid); PCU_COMM_UNPACK(own); lid_t lid = vtx_mapping[gid]; if (lid>=num_local_verts) { owners[lid-num_local_verts]=own; } } } /* Finds the vertices and edges that need to be communicated Also stores the local vertices and edges that will be owned on this part after migration */ void getAffected(Ngraph* g, Migration* plan, VertexVector& verts, EdgeVector* edges) { //verts.reserve(plan->size()); Migration::iterator itr; for (itr = plan->begin();itr!=plan->end();itr++) { GraphVertex* v = *itr; part_t toSend = plan->get(v); if (toSend!=PCU_Comm_Self()) { verts.insert(v); } } //For each edge type for (etype t = 0;t<g->numEdgeTypes();t++) { //edges[t].reserve(verts.size()); VertexVector::iterator itr; //loop through the vertices being sent for (itr = verts.begin();itr!=verts.end();itr++) { GraphIterator* gitr =g->adjacent(*itr); GraphEdge* e; GraphEdge* old=NULL; GraphVertex* v; while ((v = g->iterate(gitr))) { e=g->edge(gitr); if (old==NULL||e!=old) edges[t].insert(e); } g->destroy(gitr); } } } void addVertices(Ngraph* g, std::vector<gid_t>& ownedVerts, VertexVector& verts, std::vector<wgt_t>& weights, std::vector<part_t>& originalOwners) { VertexIterator* vitr = g->begin(); GraphVertex* v; while ((v = g->iterate(vitr))) { if (verts.find(v)==verts.end()) { ownedVerts.push_back(g->globalID(v)); weights.push_back(g->weight(v)); originalOwners.push_back(g->originalOwner(v)); } } } void addCoords(Ngraph* g,VertexVector& verts,coord_t* cs,lid_t& size) { VertexIterator* vitr = g->begin(); GraphVertex* v; while ((v = g->iterate(vitr))) { if (verts.find(v)==verts.end()) { const coord_t& c = g->coord(v); for (int i=0;i<3;i++) cs[size][i] = c[i]; size++; } } } void addEdges(Ngraph* g, Migration* plan, std::vector<gid_t>& ownedEdges, std::vector<wgt_t>& edgeWeights, std::vector<lid_t>& degrees,std::vector<gid_t>& pins, std::unordered_map<gid_t,part_t>& ghost_owners, std::unordered_set<gid_t>& addedEdges, etype t) { EdgeIterator* itr = g->begin(t); GraphEdge* e; while ((e = g->iterate(itr))) { agi::PinIterator* pitr = g->pins(e); agi::GraphVertex* end; while ((end=g->iterate(pitr))) if (plan->has(end)) break; g->destroy(pitr); if (!end) { //Add the Edge gid_t gid = g->globalID(e); ownedEdges.push_back(gid); edgeWeights.push_back(g->weight(e)); degrees.push_back(g->degree(e)); addedEdges.insert(gid); pitr=g->pins(e); while ((end=g->iterate(pitr))) { gid_t other_gid = g->globalID(end); pins.push_back(other_gid); part_t owner = g->owner(end); if (owner!=PCU_Comm_Self()) ghost_owners[other_gid] = owner; } g->destroy(pitr); } } g->destroy(itr); } void Ngraph::sendVertex(GraphVertex* vtx, part_t toSend) { gid_t gid = globalID(vtx); wgt_t w = weight(vtx); part_t old_owner = originalOwner(vtx); PCU_COMM_PACK(toSend,gid); PCU_COMM_PACK(toSend,w); PCU_COMM_PACK(toSend,old_owner); } void Ngraph::recvVertex(std::vector<gid_t>& recv, std::vector<wgt_t>& wgts, std::vector<part_t>& old_owners) { gid_t gid; PCU_COMM_UNPACK(gid); wgt_t w; PCU_COMM_UNPACK(w); part_t old_owner; PCU_COMM_UNPACK(old_owner); recv.push_back(gid); wgts.push_back(w); old_owners.push_back(old_owner); } void Ngraph::sendCoord(GraphVertex* vtx, part_t toSend) { const coord_t& c = coord(vtx); PCU_COMM_PACK(toSend,c[0]); PCU_COMM_PACK(toSend,c[1]); PCU_COMM_PACK(toSend,c[2]); } void Ngraph::recvCoord(coord_t* cs,lid_t& size) { PCU_COMM_UNPACK(cs[size][0]); PCU_COMM_UNPACK(cs[size][1]); PCU_COMM_UNPACK(cs[size][2]); size++; } void Ngraph::sendEdges(Migration* plan, EdgeVector& affectedEdges) { EdgeVector::iterator eitr; for (eitr = affectedEdges.begin();eitr!=affectedEdges.end(); eitr++) { GraphEdge* e = *eitr; gid_t* pin; part_t* pin_owners; lid_t deg=0; gid_t id; wgt_t eweight = weight(e); std::unordered_set<part_t> residence; if (isHyperGraph) { id = globalID(e); pin = new gid_t[degree(e)]; pin_owners = new part_t[degree(e)]; agi::PinIterator* pitr = this->pins(e); agi::GraphVertex* vtx; for (lid_t i=0;i<degree(e);i++) { vtx = iterate(pitr); part_t o = owner(vtx); if (plan->has(vtx)) o= plan->get(vtx); pin_owners[deg]=o; pin[deg++] = globalID(vtx); residence.insert(o); } destroy(pitr); } else { id = localID(e); pin = new gid_t[2]; pin_owners = new part_t[2]; GraphVertex* source = u(e); pin_owners[deg] = owner(source); pin[deg++] = globalID(source); GraphVertex* dest = v(e); part_t o = owner(dest); if (plan->has(dest)) o= plan->get(dest); pin_owners[deg] = o; pin[deg++] = globalID(dest); assert(plan->has(source)); pin_owners[0] = plan->get(source); residence.insert(plan->get(source)); } std::unordered_set<part_t>::iterator sitr; for (sitr=residence.begin();sitr!=residence.end();sitr++) { PCU_COMM_PACK(*sitr,id); PCU_COMM_PACK(*sitr,eweight); PCU_COMM_PACK(*sitr,deg); PCU_Comm_Pack(*sitr,pin,deg*sizeof(gid_t)); PCU_Comm_Pack(*sitr,pin_owners,deg*sizeof(part_t)); } delete [] pin; delete [] pin_owners; } } void Ngraph::recvEdges(std::unordered_set<gid_t>& addedEdges, std::vector<gid_t>& ownedEdges, std::vector<wgt_t>& edgeWeights, std::vector<lid_t>& degrees, std::vector<gid_t>& pins, std::unordered_map<gid_t,part_t>& ghost_owners, etype t) { while (PCU_Comm_Receive()) { gid_t id; wgt_t eweight; lid_t deg; PCU_COMM_UNPACK(id); PCU_COMM_UNPACK(eweight); PCU_COMM_UNPACK(deg); gid_t* pin = new gid_t[deg]; part_t* pin_owners = new part_t[deg]; PCU_Comm_Unpack(pin,deg*sizeof(gid_t)); PCU_Comm_Unpack(pin_owners,deg*sizeof(part_t)); if (isHyperGraph) { if (addedEdges.find(id)!=addedEdges.end()) { delete [] pin; delete [] pin_owners; continue; } } addedEdges.insert(id); edge_mapping[t][id]=0; ownedEdges.push_back(id); edgeWeights.push_back(eweight); degrees.push_back(deg); for (lid_t i=0;i<deg;i++) { pins.push_back(pin[i]); if (pin_owners[i]!=PCU_Comm_Self()) ghost_owners[pin[i]]=pin_owners[i]; } delete [] pin; delete [] pin_owners; } } void Ngraph::migrate(Migration* plan) { int nt = num_types; updateGhostOwners(plan); VertexVector affectedVerts; EdgeVector* affectedEdges = new EdgeVector[nt]; //TODO: replace vectors with arrays to improve performance std::vector<gid_t> ownedVerts; std::vector<wgt_t> vertWeights; std::vector<part_t> old_owners; std::vector<gid_t>* ownedEdges = new std::vector<gid_t>[nt]; std::vector<wgt_t>* edgeWeights = new std::vector<wgt_t>[nt]; std::vector<lid_t>* degrees = new std::vector<lid_t>[nt]; std::vector<gid_t>* pins = new std::vector<gid_t>[nt]; std::unordered_map<gid_t,part_t> ghost_owners; //Presize the vectors to reduce the number of reallocations ownedVerts.reserve(num_local_verts); vertWeights.reserve(num_local_verts); old_owners.reserve(num_local_verts); for (int i=0;i<nt;i++) { ownedEdges[i].reserve(num_local_edges[i]); edgeWeights[i].reserve(num_local_edges[i]); degrees[i].reserve(num_local_edges[i]); pins[i].reserve(num_local_pins[i]); } getAffected(this,plan,affectedVerts,affectedEdges); addVertices(this,ownedVerts,affectedVerts,vertWeights,old_owners); std::unordered_set<gid_t>* addedEdges = new std::unordered_set<gid_t>[nt]; for (etype i=0;i<nt;i++) addEdges(this,plan,ownedEdges[i],edgeWeights[i],degrees[i],pins[i], ghost_owners,addedEdges[i],i); //Send and recieve vertices Migration::iterator itr; PCU_Comm_Begin(); for (itr = plan->begin();itr!=plan->end();itr++) { sendVertex(*itr,plan->get(*itr)); } PCU_Comm_Send(); while (PCU_Comm_Receive()) { recvVertex(ownedVerts,vertWeights,old_owners); } //Send and recieve coordinates coord_t* cs=NULL; if (hasCoords()) { lid_t size=0; cs = new coord_t[ownedVerts.size()]; addCoords(this,affectedVerts,cs,size); Migration::iterator itr; PCU_Comm_Begin(); for (itr = plan->begin();itr!=plan->end();itr++) { sendCoord(*itr,plan->get(*itr)); } PCU_Comm_Send(); while (PCU_Comm_Receive()) { recvCoord(cs,size); } assert(size==(lid_t)ownedVerts.size()); } //Send and receive edges of each type for (etype t = 0;t < nt;t++) { PCU_Comm_Begin(); sendEdges(plan,affectedEdges[t]); PCU_Comm_Send(); recvEdges(addedEdges[t],ownedEdges[t],edgeWeights[t],degrees[t], pins[t],ghost_owners,t); } delete [] addedEdges; //Construct the migrated graph constructVerts(isHyperGraph,ownedVerts.size(),&ownedVerts[0],&vertWeights[0]); if (cs) setCoords(cs); for (int i=0;i<nt;i++) { constructEdges(ownedEdges[i].size(),&ownedEdges[i][0], &degrees[i][0],&pins[i][0]); setEdgeWeights(edgeWeights[i],i); } constructGhosts(ghost_owners); setOriginalOwners(old_owners); delete [] affectedEdges; delete [] ownedEdges; delete [] edgeWeights; delete [] degrees; delete [] pins; delete [] cs; delete plan; } PartitionMap* Ngraph::getPartition() { if (EnGPar_Is_Log_Open()) { char message[20]; sprintf(message,"getPartition\n"); EnGPar_Log_Function(message); } PCU_Comm_Begin(); VertexIterator* itr = begin(); GraphVertex* vtx; while ((vtx = iterate(itr))) { gid_t v = globalID(vtx); PCU_COMM_PACK(originalOwner(vtx),v); } PCU_Comm_Send(); PartitionMap* map = new PartitionMap; while (PCU_Comm_Receive()) { gid_t v; PCU_COMM_UNPACK(v); map->insert(std::make_pair(v,PCU_Comm_Sender())); } if (EnGPar_Is_Log_Open()) { EnGPar_End_Function(); } PCU_Barrier(); return map; } } <|endoftext|>
<commit_before>#ifndef AMGCL_MPI_UTIL_HPP #define AMGCL_MPI_UTIL_HPP /* The MIT License Copyright (c) 2012-2018 Denis Demidov <dennis.demidov@gmail.com> Copyright (c) 2014, Riccardo Rossi, CIMNE (International Center for Numerical Methods in Engineering) 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. */ /** * \file amgcl/mpi/util.hpp * \author Denis Demidov <dennis.demidov@gmail.com> * \brief MPI utilities. */ #include <vector> #include <numeric> #include <boost/type_traits.hpp> #include <amgcl/value_type/interface.hpp> #include <mpi.h> namespace amgcl { namespace mpi { /// Converts C type to MPI datatype. template <class T, class Enable = void> struct datatype_impl { static MPI_Datatype get() { static const MPI_Datatype t = create(); return t; } static MPI_Datatype create() { typedef typename math::scalar_of<T>::type S; MPI_Datatype t; int n = sizeof(T) / sizeof(S); MPI_Type_contiguous(n, datatype_impl<S>::get(), &t); MPI_Type_commit(&t); return t; } }; template <> struct datatype_impl<float> { static MPI_Datatype get() { return MPI_FLOAT; } }; template <> struct datatype_impl<double> { static MPI_Datatype get() { return MPI_DOUBLE; } }; template <> struct datatype_impl<long double> { static MPI_Datatype get() { return MPI_LONG_DOUBLE; } }; template <> struct datatype_impl<int> { static MPI_Datatype get() { return MPI_INT; } }; template <> struct datatype_impl<unsigned> { static MPI_Datatype get() { return MPI_UNSIGNED; } }; template <> struct datatype_impl<long long> { static MPI_Datatype get() { return MPI_LONG_LONG_INT; } }; template <> struct datatype_impl<unsigned long long> { static MPI_Datatype get() { return MPI_UNSIGNED_LONG_LONG; } }; template <> struct datatype_impl<ptrdiff_t> : boost::conditional< sizeof(ptrdiff_t) == sizeof(int), datatype_impl<int>, datatype_impl<long long> >::type {}; template <> struct datatype_impl<size_t> : boost::conditional< sizeof(size_t) == sizeof(unsigned), datatype_impl<unsigned>, datatype_impl<unsigned long long> >::type {}; template <> struct datatype_impl<char> { static MPI_Datatype get() { return MPI_CHAR; } }; template <typename T> MPI_Datatype datatype() { return datatype_impl<T>::get(); } /// Convenience wrapper around MPI_Comm. struct communicator { MPI_Comm comm; int rank; int size; communicator() {} communicator(MPI_Comm comm) : comm(comm) { MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); }; operator MPI_Comm() const { return comm; } /// Exclusive sum over mpi communicator template <typename T> std::vector<T> exclusive_sum(T n) const { std::vector<T> v(size + 1); v[0] = 0; MPI_Allgather(&n, 1, datatype<T>(), &v[1], 1, datatype<T>(), comm); std::partial_sum(v.begin(), v.end(), v.begin()); return v; } template <typename T> T reduce(MPI_Op op, const T &lval) const { typedef typename math::scalar_of<T>::type S; const int elems = sizeof(T) / sizeof(S); T gval; MPI_Allreduce(&lval, &gval, elems, datatype<T>(), op, comm); return gval; } /// Communicator-wise condition checking. /** * Checks conditions at each process in the communicator; * * If the condition is false on any of the participating processes, outputs the * provided message together with the ranks of the offending process. * After that each process in the communicator throws. */ template <class Condition, class Message> void check(const Condition &cond, const Message &message) { int lc = static_cast<int>(cond); int gc = reduce(MPI_PROD, lc); if (!gc) { std::vector<int> c(size); MPI_Gather(&lc, 1, MPI_INT, &c[0], size, MPI_INT, 0, comm); if (rank == 0) { std::cerr << "Failed assumption: " << message << std::endl; std::cerr << "Offending processes:"; for (int i = 0; i < size; ++i) if (!c[i]) std::cerr << " " << i; std::cerr << std::endl; } MPI_Barrier(comm); throw std::runtime_error(message); } } }; } // namespace mpi } // namespace amgcl #endif <commit_msg>Const correctness issue on older MPI implementations<commit_after>#ifndef AMGCL_MPI_UTIL_HPP #define AMGCL_MPI_UTIL_HPP /* The MIT License Copyright (c) 2012-2018 Denis Demidov <dennis.demidov@gmail.com> Copyright (c) 2014, Riccardo Rossi, CIMNE (International Center for Numerical Methods in Engineering) 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. */ /** * \file amgcl/mpi/util.hpp * \author Denis Demidov <dennis.demidov@gmail.com> * \brief MPI utilities. */ #include <vector> #include <numeric> #include <boost/type_traits.hpp> #include <amgcl/value_type/interface.hpp> #include <mpi.h> namespace amgcl { namespace mpi { /// Converts C type to MPI datatype. template <class T, class Enable = void> struct datatype_impl { static MPI_Datatype get() { static const MPI_Datatype t = create(); return t; } static MPI_Datatype create() { typedef typename math::scalar_of<T>::type S; MPI_Datatype t; int n = sizeof(T) / sizeof(S); MPI_Type_contiguous(n, datatype_impl<S>::get(), &t); MPI_Type_commit(&t); return t; } }; template <> struct datatype_impl<float> { static MPI_Datatype get() { return MPI_FLOAT; } }; template <> struct datatype_impl<double> { static MPI_Datatype get() { return MPI_DOUBLE; } }; template <> struct datatype_impl<long double> { static MPI_Datatype get() { return MPI_LONG_DOUBLE; } }; template <> struct datatype_impl<int> { static MPI_Datatype get() { return MPI_INT; } }; template <> struct datatype_impl<unsigned> { static MPI_Datatype get() { return MPI_UNSIGNED; } }; template <> struct datatype_impl<long long> { static MPI_Datatype get() { return MPI_LONG_LONG_INT; } }; template <> struct datatype_impl<unsigned long long> { static MPI_Datatype get() { return MPI_UNSIGNED_LONG_LONG; } }; template <> struct datatype_impl<ptrdiff_t> : boost::conditional< sizeof(ptrdiff_t) == sizeof(int), datatype_impl<int>, datatype_impl<long long> >::type {}; template <> struct datatype_impl<size_t> : boost::conditional< sizeof(size_t) == sizeof(unsigned), datatype_impl<unsigned>, datatype_impl<unsigned long long> >::type {}; template <> struct datatype_impl<char> { static MPI_Datatype get() { return MPI_CHAR; } }; template <typename T> MPI_Datatype datatype() { return datatype_impl<T>::get(); } /// Convenience wrapper around MPI_Comm. struct communicator { MPI_Comm comm; int rank; int size; communicator() {} communicator(MPI_Comm comm) : comm(comm) { MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); }; operator MPI_Comm() const { return comm; } /// Exclusive sum over mpi communicator template <typename T> std::vector<T> exclusive_sum(T n) const { std::vector<T> v(size + 1); v[0] = 0; MPI_Allgather(&n, 1, datatype<T>(), &v[1], 1, datatype<T>(), comm); std::partial_sum(v.begin(), v.end(), v.begin()); return v; } template <typename T> T reduce(MPI_Op op, const T &lval) const { typedef typename math::scalar_of<T>::type S; const int elems = sizeof(T) / sizeof(S); T gval; MPI_Allreduce((void*)&lval, &gval, elems, datatype<T>(), op, comm); return gval; } /// Communicator-wise condition checking. /** * Checks conditions at each process in the communicator; * * If the condition is false on any of the participating processes, outputs the * provided message together with the ranks of the offending process. * After that each process in the communicator throws. */ template <class Condition, class Message> void check(const Condition &cond, const Message &message) { int lc = static_cast<int>(cond); int gc = reduce(MPI_PROD, lc); if (!gc) { std::vector<int> c(size); MPI_Gather(&lc, 1, MPI_INT, &c[0], size, MPI_INT, 0, comm); if (rank == 0) { std::cerr << "Failed assumption: " << message << std::endl; std::cerr << "Offending processes:"; for (int i = 0; i < size; ++i) if (!c[i]) std::cerr << " " << i; std::cerr << std::endl; } MPI_Barrier(comm); throw std::runtime_error(message); } } }; } // namespace mpi } // namespace amgcl #endif <|endoftext|>
<commit_before>#ifndef BST_HPP #define BST_HPP #include "BSTNode.hpp" #include "BSTIterator.hpp" #include <utility> // for std::pair template<typename Data> class BST { protected: /** Pointer to the root of this BST, or nullptr if the BST is empty */ BSTNode<Data>* root; /** Number of Data items stored in this BST. */ unsigned int isize; public: /** iterator is an aliased typename for BSTIterator<Data>. */ typedef BSTIterator<Data> iterator; /** Default constructor. Initialize an empty BST. */ BST() : root(nullptr), isize(0) { } /** Default destructor. * It is virtual, to allow appropriate destruction of subclass objects. * Delete every node in this BST. */ // TODO virtual ~BST() { delete BSTNode<Data> (*this)->root; delete (*this)->isize; (*this)->isize = NULL; (*this) = NULL; } /** Insert a Data item in the BST. * Return a pair, with the pair's first member set to an * iterator pointing to either the newly inserted element * or to the equivalent element already in the set. * The pair's second element is set to true * if a new element was inserted or false if an * equivalent element already existed. */ // TODO virtual std::pair<iterator,bool> insert(const Data& item) { bool inserted; ++isize; return std::pair<a,inserted>; } /** Find a Data item in the BST. * Return an iterator pointing to the item, or the end * iterator if the item is not in the BST. */ // TODO iterator find(const Data& item) const { BSTIterator<Data> iter = new BSTIterator<Data>((*this)->root); while (iter->curr != null && iter->curr->value != item){ if (iter->curr->value > item){ iter->curr = iter->curr->left; } if (iter->curr->value < item){ iter->curr = iter->curr->right; } } return iter; /*if (item == iter->curr->data) return iter; else { if (item < iter->curr->data)*/ } /** Return the number of items currently in the BST. */ // TODO unsigned int size() const { return isize; } /** Remove all elements from this BST, and destroy them, * leaving this BST with a size of 0. */ // TODO void clear() { delete BSTNode<Data> (*this)->root; isize = 0; } /** Return true if the BST is empty, else false. */ // TODO bool empty() const { return ( isize == 0 ); } /** Return an iterator pointing to the first item in the BST. */ // TODO iterator begin() const { BSTNode<Data> temp = ( (*this)->root ); while (temp->left) temp = temp->left; return new BSTIterator<Data>(temp); } /** Return an iterator pointing past the last item in the BST. */ iterator end() const { return typename BST<Data>::iterator(nullptr); } }; #endif //BST_HPP <commit_msg>Added insert method, reversed find in BST<commit_after>#ifndef BST_HPP #define BST_HPP #include "BSTNode.hpp" #include "BSTIterator.hpp" #include <utility> // for std::pair template<typename Data> class BST { protected: /** Pointer to the root of this BST, or nullptr if the BST is empty */ BSTNode<Data>* root; /** Number of Data items stored in this BST. */ unsigned int isize; public: /** iterator is an aliased typename for BSTIterator<Data>. */ typedef BSTIterator<Data> iterator; /** Default constructor. Initialize an empty BST. */ BST() : root(nullptr), isize(0) { } /** Default destructor. * It is virtual, to allow appropriate destruction of subclass objects. * Delete every node in this BST. */ // TODO virtual ~BST() { delete BSTNode<Data> (*this)->root; delete (*this)->isize; (*this)->isize = NULL; (*this) = NULL; } /** Insert a Data item in the BST. * Return a pair, with the pair's first member set to an * iterator pointing to either the newly inserted element * or to the equivalent element already in the set. * The pair's second element is set to true * if a new element was inserted or false if an * equivalent element already existed. */ // TODO virtual std::pair<iterator,bool> insert(const Data& item) { bool inserted; if ((*this)->root == NULL){ (*this)->root = new BSTNode(item); BSTITerator<Data> iter = new BSTITerator<Data>((*this)->root); inserted = true; ++isize; return std::pair<iter,inserted>; } BSTIterator<Data> iter = new BSTIterator<Data>((*this)->root); while (iter->curr != null){ if (iter->curr->value > item){ iter->curr = iter->curr->left; } else if (iter->curr->value < item){ iter->curr = iter->curr->right; } else { //iter->curr->value == item inserted = false; ++isize; return std::pair<iter, inserted>; } } iter->curr = new BSTNode(item); inserted = true; ++isize; return std::pair<a,inserted>; } /** Find a Data item in the BST. * Return an iterator pointing to the item, or the end * iterator if the item is not in the BST. */ // TODO iterator find(const Data& item) const { if ((*this)->root == NULL){ (*this)->root = new BSTNode(item); BSTITerator<Data> iter = new BSTITerator<Data>((*this)->root); return iter; } BSTIterator<Data> iter = new BSTIterator<Data>((*this)->root); (iter->curr != null && iter->curr->value != item){ if (iter->curr->value > item){ iter->curr = iter->curr->left; } if (iter->curr->value < item){ iter->curr = iter->curr->right; } } return iter; } /** Return the number of items currently in the BST. */ // TODO unsigned int size() const { return isize; } /** Remove all elements from this BST, and destroy them, * leaving this BST with a size of 0. */ // TODO void clear() { delete BSTNode<Data> (*this)->root; isize = 0; } /** Return true if the BST is empty, else false. */ // TODO bool empty() const { return ( isize == 0 ); } /** Return an iterator pointing to the first item in the BST. */ // TODO iterator begin() const { BSTNode<Data> temp = ( (*this)->root ); while (temp->left) temp = temp->left; return new BSTIterator<Data>(temp); } /** Return an iterator pointing past the last item in the BST. */ iterator end() const { return typename BST<Data>::iterator(nullptr); } }; #endif //BST_HPP <|endoftext|>
<commit_before>/* * This file is part of Poedit (http://poedit.net) * * Copyright (C) 2013-2014 Vaclav Slavik * * 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 "language.h" #include "icuhelpers.h" #include <cctype> #include <algorithm> #include <unordered_map> #include <mutex> #include <memory> #include <unicode/uvernum.h> #include <unicode/locid.h> #include <unicode/coll.h> #include <unicode/utypes.h> #include <wx/filename.h> // GCC's libstdc++ didn't have functional std::regex implementation until 4.9 #if (defined(__GNUC__) && !defined(__clang__) && !wxCHECK_GCC_VERSION(4,9)) #include <boost/regex.hpp> using boost::wregex; using boost::regex_match; #else #include <regex> using std::wregex; using std::regex_match; #endif namespace { // see http://www.gnu.org/software/gettext/manual/html_node/Header-Entry.html // for description of permitted formats const wregex RE_LANG_CODE(L"([a-z]){2,3}(_[A-Z]{2})?(@[a-z]+)?"); // a more permissive variant of the same that TryNormalize() would fix const wregex RE_LANG_CODE_PERMISSIVE(L"([a-zA-Z]){2,3}([_-][a-zA-Z]{2})?(@[a-zA-Z]+)?"); // try some normalizations: s/-/_/, case adjustments void TryNormalize(std::wstring& s) { auto begin = s.begin(); auto end = s.end(); size_t pos = s.rfind('@'); if (pos != std::wstring::npos) { for (auto x = begin + pos; x != end; ++x) *x = std::tolower(*x); end = begin + pos; } bool upper = false; for (auto x = begin; x != end; ++x) { if (*x == '-') *x = '_'; if (*x == '_') upper = true; else if (std::isupper(*x) && !upper) *x = std::tolower(*x); else if (std::islower(*x) && upper) *x = std::toupper(*x); } } bool IsISOLanguage(const std::string& s) { const char *test = s.c_str(); for (const char * const* i = icu::Locale::getISOLanguages(); *i != nullptr; ++i) { if (strcmp(test, *i) == 0) return true; } return false; } bool IsISOCountry(const std::string& s) { const char *test = s.c_str(); for (const char * const* i = icu::Locale::getISOCountries(); *i != nullptr; ++i) { if (strcmp(test, *i) == 0) return true; } return false; } // Mapping of names to their respective ISO codes. struct DisplayNamesData { typedef std::unordered_map<std::wstring, std::string> Map; Map names, namesEng; std::vector<std::wstring> sortedNames; }; std::once_flag of_namesList; const DisplayNamesData& GetDisplayNamesData() { static DisplayNamesData data; std::call_once(of_namesList, [=]{ auto locEng = icu::Locale::getEnglish(); std::vector<icu::UnicodeString> names; int32_t count; const icu::Locale *loc = icu::Locale::getAvailableLocales(count); names.reserve(count); for (int i = 0; i < count; i++, loc++) { // TODO: for now, ignore variants here and in FormatForRoundtrip(), // because translating them between gettext and ICU is nontrivial auto variant = loc->getVariant(); if (variant != nullptr && *variant != '\0') continue; icu::UnicodeString s; loc->getDisplayName(s); names.push_back(s); s.foldCase(); data.names[StdFromIcuStr(s)] = loc->getName(); loc->getDisplayName(locEng, s); s.foldCase(); data.namesEng[StdFromIcuStr(s)] = loc->getName(); } // sort the names alphabetically for data.sortedNames: UErrorCode err = U_ZERO_ERROR; std::unique_ptr<icu::Collator> coll(icu::Collator::createInstance(err)); if (coll) { coll->setStrength(icu::Collator::SECONDARY); // case insensitive std::sort(names.begin(), names.end(), [&coll](const icu::UnicodeString& a, const icu::UnicodeString& b){ UErrorCode e = U_ZERO_ERROR; return coll->compare(a, b, e) == UCOL_LESS; }); } else { std::sort(names.begin(), names.end()); } // convert into std::wstring data.sortedNames.reserve(names.size()); for (auto s: names) data.sortedNames.push_back(StdFromIcuStr(s)); }); return data; } } // anonymous namespace bool Language::IsValidCode(const std::wstring& s) { return regex_match(s, RE_LANG_CODE); } std::string Language::Lang() const { return m_code.substr(0, m_code.find_first_of("_@")); } std::string Language::Country() const { const size_t pos = m_code.find('_'); if (pos == std::string::npos) return std::string(); else return m_code.substr(pos+1, m_code.rfind('@')); } std::string Language::LangAndCountry() const { return m_code.substr(0, m_code.rfind('@')); } std::string Language::Variant() const { const size_t pos = m_code.rfind('@'); if (pos == std::string::npos) return std::string(); else return m_code.substr(0, pos); } Language Language::TryParse(const std::wstring& s) { if (IsValidCode(s)) return Language(s); // Is it a standard language code? if (regex_match(s, RE_LANG_CODE_PERMISSIVE)) { std::wstring s2(s); TryNormalize(s2); if (IsValidCode(s2)) return Language(s2); } // If not, perhaps it's a human-readable name (perhaps coming from the language control)? auto names = GetDisplayNamesData(); icu::UnicodeString s_icu = ToIcuStr(s); s_icu.foldCase(); std::wstring folded = StdFromIcuStr(s_icu); auto i = names.names.find(folded); if (i != names.names.end()) return Language(i->second); // Maybe it was in English? i = names.namesEng.find(folded); if (i != names.namesEng.end()) return Language(i->second); return Language(); // invalid } Language Language::TryParseWithValidation(const std::wstring& s) { Language lang = Language::TryParse(s); if (!lang.IsValid()) return Language(); // invalid if (!IsISOLanguage(lang.Lang())) return Language(); // invalid auto country = lang.Country(); if (!country.empty() && !IsISOCountry(country)) return Language(); // invalid return lang; } Language Language::FromLegacyNames(const std::string& lang, const std::string& country) { if (lang.empty()) return Language(); // invalid #include "language_impl_legacy.h" std::string code; auto i = isoLanguages.find(lang); if ( i != isoLanguages.end() ) code = i->second; else return Language(); // invalid if (!country.empty()) { auto iC = isoCountries.find(country); if ( iC != isoCountries.end() ) code += "_" + iC->second; } return Language(code); } std::string Language::DefaultPluralFormsExpr() const { if (!IsValid()) return std::string(); static const std::unordered_map<std::string, std::string> forms = { #include "language_impl_plurals.h" }; auto i = forms.find(m_code); if ( i != forms.end() ) return i->second; i = forms.find(LangAndCountry()); if ( i != forms.end() ) return i->second; i = forms.find(Lang()); if ( i != forms.end() ) return i->second; return std::string(); } bool Language::IsRTL() const { if (!IsValid()) return false; // fallback #if U_ICU_VERSION_MAJOR_NUM >= 51 auto locale = IcuLocaleName(); UErrorCode err = U_ZERO_ERROR; UScriptCode codes[10]= {USCRIPT_INVALID_CODE}; if (uscript_getCode(locale.c_str(), codes, 10, &err) == 0 || err != U_ZERO_ERROR) return false; // fallback return uscript_isRightToLeft(codes[0]); #else return false; #endif } icu::Locale Language::ToIcu() const { if (!IsValid()) return icu::Locale::getEnglish(); return icu::Locale(IcuLocaleName().c_str()); } wxString Language::DisplayName() const { icu::UnicodeString s; ToIcu().getDisplayName(s); return FromIcuStr(s); } wxString Language::DisplayNameInItself() const { auto loc = ToIcu(); icu::UnicodeString s; loc.getDisplayName(loc, s); return FromIcuStr(s); } wxString Language::FormatForRoundtrip() const { // TODO: Can't show variants nicely yet, not standardized if (!Variant().empty()) return m_code; wxString disp = DisplayName(); // ICU isn't 100% reliable, some of the display names it produces // (e.g. "Chinese (China)" aren't in the list of known locale names // (here because zh-Trans is preferred to zh_CN). So make sure it can // be parsed back first. if (TryParse(disp.ToStdWstring()).IsValid()) return disp; else return m_code; } const std::vector<std::wstring>& Language::AllFormattedNames() { return GetDisplayNamesData().sortedNames; } Language Language::TryGuessFromFilename(const wxString& filename) { wxFileName fn(filename); fn.MakeAbsolute(); // Try matching the filename first: // - entire name // - suffix (foo.cs_CZ.po, wordpressTheme-cs_CZ.po) // - directory name (cs_CZ, cs.lproj, cs/LC_MESSAGES) std::wstring name = fn.GetName().ToStdWstring(); Language lang = Language::TryParseWithValidation(name); if (lang.IsValid()) return lang; size_t pos = name.find_first_of(L".-_"); while (pos != wxString::npos) { auto part = name.substr(pos+1); lang = Language::TryParseWithValidation(part); if (lang.IsValid()) return lang; pos = name.find_first_of(L".-_", pos+1); } auto dirs = fn.GetDirs(); if (!dirs.empty()) { auto d = dirs.rbegin(); if (d->IsSameAs("LC_MESSAGES", /*caseSensitive=*/false)) { if (++d == dirs.rend()) return Language(); // failed to match } wxString rest; if (d->EndsWith(".lproj", &rest)) return Language::TryParseWithValidation(rest.ToStdWstring()); else return Language::TryParseWithValidation(d->ToStdWstring()); } return Language(); // failed to match } <commit_msg>Fix parsing of language names with scripts<commit_after>/* * This file is part of Poedit (http://poedit.net) * * Copyright (C) 2013-2014 Vaclav Slavik * * 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 "language.h" #include "icuhelpers.h" #include <cctype> #include <algorithm> #include <unordered_map> #include <mutex> #include <memory> #include <unicode/uvernum.h> #include <unicode/locid.h> #include <unicode/coll.h> #include <unicode/utypes.h> #include <wx/filename.h> // GCC's libstdc++ didn't have functional std::regex implementation until 4.9 #if (defined(__GNUC__) && !defined(__clang__) && !wxCHECK_GCC_VERSION(4,9)) #include <boost/regex.hpp> using boost::wregex; using boost::regex_match; #else #include <regex> using std::wregex; using std::regex_match; #endif namespace { // see http://www.gnu.org/software/gettext/manual/html_node/Header-Entry.html // for description of permitted formats const wregex RE_LANG_CODE(L"([a-z]){2,3}(_[A-Z]{2})?(@[a-z]+)?"); // a more permissive variant of the same that TryNormalize() would fix const wregex RE_LANG_CODE_PERMISSIVE(L"([a-zA-Z]){2,3}([_-][a-zA-Z]{2})?(@[a-zA-Z]+)?"); // try some normalizations: s/-/_/, case adjustments void TryNormalize(std::wstring& s) { auto begin = s.begin(); auto end = s.end(); size_t pos = s.rfind('@'); if (pos != std::wstring::npos) { for (auto x = begin + pos; x != end; ++x) *x = std::tolower(*x); end = begin + pos; } bool upper = false; for (auto x = begin; x != end; ++x) { if (*x == '-') *x = '_'; if (*x == '_') upper = true; else if (std::isupper(*x) && !upper) *x = std::tolower(*x); else if (std::islower(*x) && upper) *x = std::toupper(*x); } } bool IsISOLanguage(const std::string& s) { const char *test = s.c_str(); for (const char * const* i = icu::Locale::getISOLanguages(); *i != nullptr; ++i) { if (strcmp(test, *i) == 0) return true; } return false; } bool IsISOCountry(const std::string& s) { const char *test = s.c_str(); for (const char * const* i = icu::Locale::getISOCountries(); *i != nullptr; ++i) { if (strcmp(test, *i) == 0) return true; } return false; } // Mapping of names to their respective ISO codes. struct DisplayNamesData { typedef std::unordered_map<std::wstring, std::string> Map; Map names, namesEng; std::vector<std::wstring> sortedNames; }; std::once_flag of_namesList; const DisplayNamesData& GetDisplayNamesData() { static DisplayNamesData data; std::call_once(of_namesList, [=]{ auto locEng = icu::Locale::getEnglish(); std::vector<icu::UnicodeString> names; int32_t count; const icu::Locale *loc = icu::Locale::getAvailableLocales(count); names.reserve(count); for (int i = 0; i < count; i++, loc++) { auto language = loc->getLanguage(); auto script = loc->getScript(); auto country = loc->getCountry(); auto variant = loc->getVariant(); // TODO: for now, ignore variants here and in FormatForRoundtrip(), // because translating them between gettext and ICU is nontrivial if (variant != nullptr && *variant != '\0') continue; // Discard locales for regions (e.g. "English (World)" or "Arabic (World)", // because the base language (en, ar) is enough for our purposes. There are // only a few such locales in ICU: ar_001, en_001, en_150, es_419. if (country && *country >= '0' && *country <= '9') continue; icu::UnicodeString s; loc->getDisplayName(s); names.push_back(s); if (strcmp(language, "zh") == 0 && *country == '\0') { if (strcmp(script, "Hans") == 0) country = "CN"; else if (strcmp(script, "Hant") == 0) country = "TW"; } std::string code(language); if (*country != '\0') { code += '_'; code += country; } if (*script != '\0') { if (strcmp(script, "Latn") == 0) code += "@latin"; } s.foldCase(); data.names[StdFromIcuStr(s)] = code; loc->getDisplayName(locEng, s); s.foldCase(); data.namesEng[StdFromIcuStr(s)] = code; } // sort the names alphabetically for data.sortedNames: UErrorCode err = U_ZERO_ERROR; std::unique_ptr<icu::Collator> coll(icu::Collator::createInstance(err)); if (coll) { coll->setStrength(icu::Collator::SECONDARY); // case insensitive std::sort(names.begin(), names.end(), [&coll](const icu::UnicodeString& a, const icu::UnicodeString& b){ UErrorCode e = U_ZERO_ERROR; return coll->compare(a, b, e) == UCOL_LESS; }); } else { std::sort(names.begin(), names.end()); } // convert into std::wstring data.sortedNames.reserve(names.size()); for (auto s: names) data.sortedNames.push_back(StdFromIcuStr(s)); }); return data; } } // anonymous namespace bool Language::IsValidCode(const std::wstring& s) { return regex_match(s, RE_LANG_CODE); } std::string Language::Lang() const { return m_code.substr(0, m_code.find_first_of("_@")); } std::string Language::Country() const { const size_t pos = m_code.find('_'); if (pos == std::string::npos) return std::string(); else return m_code.substr(pos+1, m_code.rfind('@')); } std::string Language::LangAndCountry() const { return m_code.substr(0, m_code.rfind('@')); } std::string Language::Variant() const { const size_t pos = m_code.rfind('@'); if (pos == std::string::npos) return std::string(); else return m_code.substr(0, pos); } Language Language::TryParse(const std::wstring& s) { if (IsValidCode(s)) return Language(s); // Is it a standard language code? if (regex_match(s, RE_LANG_CODE_PERMISSIVE)) { std::wstring s2(s); TryNormalize(s2); if (IsValidCode(s2)) return Language(s2); } // If not, perhaps it's a human-readable name (perhaps coming from the language control)? auto names = GetDisplayNamesData(); icu::UnicodeString s_icu = ToIcuStr(s); s_icu.foldCase(); std::wstring folded = StdFromIcuStr(s_icu); auto i = names.names.find(folded); if (i != names.names.end()) return Language(i->second); // Maybe it was in English? i = names.namesEng.find(folded); if (i != names.namesEng.end()) return Language(i->second); return Language(); // invalid } Language Language::TryParseWithValidation(const std::wstring& s) { Language lang = Language::TryParse(s); if (!lang.IsValid()) return Language(); // invalid if (!IsISOLanguage(lang.Lang())) return Language(); // invalid auto country = lang.Country(); if (!country.empty() && !IsISOCountry(country)) return Language(); // invalid return lang; } Language Language::FromLegacyNames(const std::string& lang, const std::string& country) { if (lang.empty()) return Language(); // invalid #include "language_impl_legacy.h" std::string code; auto i = isoLanguages.find(lang); if ( i != isoLanguages.end() ) code = i->second; else return Language(); // invalid if (!country.empty()) { auto iC = isoCountries.find(country); if ( iC != isoCountries.end() ) code += "_" + iC->second; } return Language(code); } std::string Language::DefaultPluralFormsExpr() const { if (!IsValid()) return std::string(); static const std::unordered_map<std::string, std::string> forms = { #include "language_impl_plurals.h" }; auto i = forms.find(m_code); if ( i != forms.end() ) return i->second; i = forms.find(LangAndCountry()); if ( i != forms.end() ) return i->second; i = forms.find(Lang()); if ( i != forms.end() ) return i->second; return std::string(); } bool Language::IsRTL() const { if (!IsValid()) return false; // fallback #if U_ICU_VERSION_MAJOR_NUM >= 51 auto locale = IcuLocaleName(); UErrorCode err = U_ZERO_ERROR; UScriptCode codes[10]= {USCRIPT_INVALID_CODE}; if (uscript_getCode(locale.c_str(), codes, 10, &err) == 0 || err != U_ZERO_ERROR) return false; // fallback return uscript_isRightToLeft(codes[0]); #else return false; #endif } icu::Locale Language::ToIcu() const { if (!IsValid()) return icu::Locale::getEnglish(); return icu::Locale(IcuLocaleName().c_str()); } wxString Language::DisplayName() const { icu::UnicodeString s; ToIcu().getDisplayName(s); return FromIcuStr(s); } wxString Language::DisplayNameInItself() const { auto loc = ToIcu(); icu::UnicodeString s; loc.getDisplayName(loc, s); return FromIcuStr(s); } wxString Language::FormatForRoundtrip() const { // TODO: Can't show variants nicely yet, not standardized if (!Variant().empty()) return m_code; wxString disp = DisplayName(); // ICU isn't 100% reliable, some of the display names it produces // (e.g. "Chinese (China)" aren't in the list of known locale names // (here because zh-Trans is preferred to zh_CN). So make sure it can // be parsed back first. if (TryParse(disp.ToStdWstring()).IsValid()) return disp; else return m_code; } const std::vector<std::wstring>& Language::AllFormattedNames() { return GetDisplayNamesData().sortedNames; } Language Language::TryGuessFromFilename(const wxString& filename) { wxFileName fn(filename); fn.MakeAbsolute(); // Try matching the filename first: // - entire name // - suffix (foo.cs_CZ.po, wordpressTheme-cs_CZ.po) // - directory name (cs_CZ, cs.lproj, cs/LC_MESSAGES) std::wstring name = fn.GetName().ToStdWstring(); Language lang = Language::TryParseWithValidation(name); if (lang.IsValid()) return lang; size_t pos = name.find_first_of(L".-_"); while (pos != wxString::npos) { auto part = name.substr(pos+1); lang = Language::TryParseWithValidation(part); if (lang.IsValid()) return lang; pos = name.find_first_of(L".-_", pos+1); } auto dirs = fn.GetDirs(); if (!dirs.empty()) { auto d = dirs.rbegin(); if (d->IsSameAs("LC_MESSAGES", /*caseSensitive=*/false)) { if (++d == dirs.rend()) return Language(); // failed to match } wxString rest; if (d->EndsWith(".lproj", &rest)) return Language::TryParseWithValidation(rest.ToStdWstring()); else return Language::TryParseWithValidation(d->ToStdWstring()); } return Language(); // failed to match } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // stl #include <iostream> // boost #include <boost/optional.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/tokenizer.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> // mapnik #include <mapnik/color.hpp> #include <mapnik/color_factory.hpp> #include <mapnik/filter_factory.hpp> #include <mapnik/layer.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/load_map.hpp> using boost::lexical_cast; using boost::bad_lexical_cast; using boost::tokenizer; namespace mapnik { void load_map(Map & map, std::string const& filename) { using boost::property_tree::ptree; ptree pt; read_xml(filename,pt); boost::optional<std::string> bgcolor = pt.get_optional<std::string>("Map.<xmlattr>.bgcolor"); if (bgcolor) { Color bg = color_factory::from_string(bgcolor->c_str()); map.setBackground(bg); } std::string srs = pt.get<std::string>("Map.<xmlattr>.srs", "+proj=latlong +datum=WGS84"); map.set_srs(srs); ptree::const_iterator itr = pt.get_child("Map").begin(); ptree::const_iterator end = pt.get_child("Map").end(); for (; itr != end; ++itr) { ptree::value_type const& v = *itr; if (v.first == "Style") { std::string name = v.second.get<std::string>("<xmlattr>.name"); feature_type_style style; ptree::const_iterator ruleIter = v.second.begin(); ptree::const_iterator endRule = v.second.end(); for (; ruleIter!=endRule; ++ruleIter) { ptree::value_type const& rule_tag = *ruleIter; if (rule_tag.first == "Rule") { std::string name = rule_tag.second.get<std::string>("<xmlattr>.name",""); std::string title = rule_tag.second.get<std::string>("<xmlattr>.title",""); rule_type rule(name,title); boost::optional<std::string> filter_expr = rule_tag.second.get_optional<std::string>("Filter"); if (filter_expr) { rule.set_filter(create_filter(*filter_expr)); } boost::optional<std::string> else_filter = rule_tag.second.get_optional<std::string>("ElseFilter"); if (else_filter) { rule.set_else(true); } boost::optional<double> min_scale = rule_tag.second.get_optional<double>("MinScaleDenominator"); if (min_scale) { rule.set_min_scale(*min_scale); } boost::optional<double> max_scale = rule_tag.second.get_optional<double>("MaxScaleDenominator"); if (max_scale) { rule.set_max_scale(*max_scale); } ptree::const_iterator symIter = rule_tag.second.begin(); ptree::const_iterator endSym = rule_tag.second.end(); for( ;symIter != endSym; ++symIter) { ptree::value_type const& sym = *symIter; if ( sym.first == "PointSymbolizer") { std::cout << sym.first << "\n"; } else if ( sym.first == "TextSymbolizer") { std::string name = sym.second.get<std::string>("<xmlattr>.name"); std::string face_name = sym.second.get<std::string>("<xmlattr>.face_name"); unsigned size = sym.second.get<unsigned>("<xmlattr>.size",10); std::string color_str = sym.second.get<std::string>("<xmlattr>.fill","black"); Color c = color_factory::from_string(color_str.c_str()); text_symbolizer text_symbol(name,face_name, size,c); std::string placement_str = sym.second.get<std::string>("<xmlattr>.placement","point"); if (placement_str == "line") { text_symbol.set_label_placement(line_placement); } rule.append(text_symbol); } else if ( sym.first == "LineSymbolizer") { stroke strk; ptree::const_iterator cssIter = sym.second.begin(); ptree::const_iterator endCss = sym.second.end(); for(; cssIter != endCss; ++cssIter) { ptree::value_type const& css = * cssIter; std::string css_name = css.second.get<std::string>("<xmlattr>.name"); std::string data = css.second.data(); if (css_name == "stroke") { Color c = color_factory::from_string(css.second.data().c_str()); strk.set_color(c); } else if (css_name == "stroke-width") { try { float width = lexical_cast<float>(data); strk.set_width(width); } catch (bad_lexical_cast & ex) { std::clog << ex.what() << "\n"; } } else if (css_name == "stroke-opacity") { try { float opacity = lexical_cast<float>(data); strk.set_opacity(opacity); } catch (bad_lexical_cast & ex) { std::clog << ex.what() << "\n"; } } else if (css_name == "stroke-linejoin") { if ("miter" == data) { strk.set_line_join(mapnik::MITER_JOIN); } else if ("round" == data) { strk.set_line_join(mapnik::ROUND_JOIN); } else if ("bevel" == data) { strk.set_line_join(mapnik::BEVEL_JOIN); } } else if (css_name == "stroke-linecap") { if ("round" == data) { strk.set_line_cap(mapnik::ROUND_CAP); } else if ("butt" == data) { strk.set_line_cap(mapnik::BUTT_CAP); } else if ("square" == data) { strk.set_line_cap(mapnik::SQUARE_CAP); } } else if (css_name == "stroke-dasharray") { tokenizer<> tok (data); std::vector<float> dash_array; for (tokenizer<>::iterator itr = tok.begin(); itr != tok.end(); ++itr) { try { float f = boost::lexical_cast<float>(*itr); dash_array.push_back(f); } catch ( boost::bad_lexical_cast & ex) { std::clog << ex.what() << "\n"; } } if (dash_array.size()) { size_t size = dash_array.size(); if ( size % 2) { for (size_t i=0; i < size ;++i) { dash_array.push_back(dash_array[i]); } } std::vector<float>::const_iterator pos = dash_array.begin(); while (pos != dash_array.end()) { strk.add_dash(*pos,*(pos + 1)); pos +=2; } } } } rule.append(line_symbolizer(strk)); } else if ( sym.first == "PolygonSymbolizer") { polygon_symbolizer poly_sym; ptree::const_iterator cssIter = sym.second.begin(); ptree::const_iterator endCss = sym.second.end(); for(; cssIter != endCss; ++cssIter) { ptree::value_type const& css = * cssIter; std::string css_name = css.second.get<std::string>("<xmlattr>.name"); std::string data = css.second.data(); if (css_name == "fill") { Color c = color_factory::from_string(css.second.data().c_str()); poly_sym.set_fill(c); } else if (css_name == "fill-opacity") { try { float opacity = lexical_cast<float>(data); poly_sym.set_opacity(opacity); } catch (bad_lexical_cast & ex) { std::clog << ex.what() << "\n"; } } } rule.append(poly_sym); } else if ( sym.first == "TextSymbolizer") { std::cout << sym.first << "\n"; } else if ( sym.first == "RasterSymbolizer") { rule.append(raster_symbolizer()); } } style.add_rule(rule); } } map.insert_style(name, style); } else if (v.first == "Layer") { std::string name = v.second.get<std::string>("<xmlattr>.name","Unnamed"); std::string srs = v.second.get<std::string>("<xmlattr>.srs","+proj=latlong +datum=WGS84"); Layer lyr(name, srs); boost::optional<std::string> status = v.second.get_optional<std::string>("<xmlattr>.status"); if (status && *status == "off") { lyr.setActive(false); } ptree::const_iterator itr2 = v.second.begin(); ptree::const_iterator end2 = v.second.end(); for(; itr2 != end2; ++itr2) { ptree::value_type const& child = *itr2; if (child.first == "StyleName") { lyr.add_style(child.second.data()); } else if (child.first == "Datasource") { parameters params; ptree::const_iterator paramIter = child.second.begin(); ptree::const_iterator endParam = child.second.end(); for (; paramIter != endParam; ++paramIter) { ptree::value_type const& param_tag=*paramIter; if (param_tag.first == "Parameter") { std::string name = param_tag.second.get<std::string>("<xmlattr>.name"); std::string value = param_tag.second.data(); std::clog << "name = " << name << " value = " << value << "\n"; params[name] = value; } } //now we're ready to create datasource boost::shared_ptr<datasource> ds = datasource_cache::instance()->create(params); lyr.set_datasource(ds); } } map.addLayer(lyr); } } } } <commit_msg>support for ShieldSymbolizer and LinePatternSymbolizer tags<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // stl #include <iostream> // boost #include <boost/optional.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/tokenizer.hpp> #include <boost/property_tree/ptree.hpp> // use tinyxml #define BOOST_PROPERTY_TREE_XML_PARSER_TINYXML #include <boost/property_tree/xml_parser.hpp> // mapnik #include <mapnik/color.hpp> #include <mapnik/color_factory.hpp> #include <mapnik/filter_factory.hpp> #include <mapnik/layer.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/load_map.hpp> using boost::lexical_cast; using boost::bad_lexical_cast; using boost::tokenizer; namespace mapnik { void load_map(Map & map, std::string const& filename) { using boost::property_tree::ptree; ptree pt; read_xml(filename,pt); boost::optional<std::string> bgcolor = pt.get_optional<std::string>("Map.<xmlattr>.bgcolor"); if (bgcolor) { Color bg = color_factory::from_string(bgcolor->c_str()); map.setBackground(bg); } std::string srs = pt.get<std::string>("Map.<xmlattr>.srs", "+proj=latlong +datum=WGS84"); map.set_srs(srs); ptree::const_iterator itr = pt.get_child("Map").begin(); ptree::const_iterator end = pt.get_child("Map").end(); for (; itr != end; ++itr) { ptree::value_type const& v = *itr; if (v.first == "Style") { std::string name = v.second.get<std::string>("<xmlattr>.name"); feature_type_style style; ptree::const_iterator ruleIter = v.second.begin(); ptree::const_iterator endRule = v.second.end(); for (; ruleIter!=endRule; ++ruleIter) { ptree::value_type const& rule_tag = *ruleIter; if (rule_tag.first == "Rule") { std::string name = rule_tag.second.get<std::string>("<xmlattr>.name",""); std::string title = rule_tag.second.get<std::string>("<xmlattr>.title",""); rule_type rule(name,title); boost::optional<std::string> filter_expr = rule_tag.second.get_optional<std::string>("Filter"); if (filter_expr) { rule.set_filter(create_filter(*filter_expr)); } boost::optional<std::string> else_filter = rule_tag.second.get_optional<std::string>("ElseFilter"); if (else_filter) { rule.set_else(true); } boost::optional<double> min_scale = rule_tag.second.get_optional<double>("MinScaleDenominator"); if (min_scale) { rule.set_min_scale(*min_scale); } boost::optional<double> max_scale = rule_tag.second.get_optional<double>("MaxScaleDenominator"); if (max_scale) { rule.set_max_scale(*max_scale); } ptree::const_iterator symIter = rule_tag.second.begin(); ptree::const_iterator endSym = rule_tag.second.end(); for( ;symIter != endSym; ++symIter) { ptree::value_type const& sym = *symIter; if ( sym.first == "PointSymbolizer") { std::cout << sym.first << "\n"; } else if ( sym.first == "LinePatternSymbolizer") { std::string file = sym.second.get<std::string>("<xmlattr>.file"); std::string type = sym.second.get<std::string>("<xmlattr>.type"); unsigned width = sym.second.get<unsigned>("<xmlattr>.width"); unsigned height = sym.second.get<unsigned>("<xmlattr>.height"); rule.append(line_pattern_symbolizer(file,type,width,height)); } else if ( sym.first == "TextSymbolizer") { std::string name = sym.second.get<std::string>("<xmlattr>.name"); std::string face_name = sym.second.get<std::string>("<xmlattr>.face_name"); unsigned size = sym.second.get<unsigned>("<xmlattr>.size",10); std::string color_str = sym.second.get<std::string>("<xmlattr>.fill","black"); Color c = color_factory::from_string(color_str.c_str()); text_symbolizer text_symbol(name,face_name, size,c); std::string placement_str = sym.second.get<std::string>("<xmlattr>.placement","point"); if (placement_str == "line") { text_symbol.set_label_placement(line_placement); } rule.append(text_symbol); } else if ( sym.first == "ShieldSymbolizer") { std::string name = sym.second.get<std::string>("<xmlattr>.name"); std::string face_name = sym.second.get<std::string>("<xmlattr>.face_name"); unsigned size = sym.second.get<unsigned>("<xmlattr>.size",10); std::string color_str = sym.second.get<std::string>("<xmlattr>.fill","black"); Color fill = color_factory::from_string(color_str.c_str()); std::string image_file = sym.second.get<std::string>("<xmlattr>.file"); std::string type = sym.second.get<std::string>("<xmlattr>.type"); unsigned width = sym.second.get<unsigned>("<xmlattr>.width"); unsigned height = sym.second.get<unsigned>("<xmlattr>.height"); shield_symbolizer shield_symbol(name,face_name,size,fill, image_file,type,width,height); rule.append(shield_symbol); } else if ( sym.first == "LineSymbolizer") { stroke strk; ptree::const_iterator cssIter = sym.second.begin(); ptree::const_iterator endCss = sym.second.end(); for(; cssIter != endCss; ++cssIter) { ptree::value_type const& css = * cssIter; std::string css_name = css.second.get<std::string>("<xmlattr>.name"); std::string data = css.second.data(); if (css_name == "stroke") { Color c = color_factory::from_string(css.second.data().c_str()); strk.set_color(c); } else if (css_name == "stroke-width") { try { float width = lexical_cast<float>(data); strk.set_width(width); } catch (bad_lexical_cast & ex) { std::clog << ex.what() << "\n"; } } else if (css_name == "stroke-opacity") { try { float opacity = lexical_cast<float>(data); strk.set_opacity(opacity); } catch (bad_lexical_cast & ex) { std::clog << ex.what() << "\n"; } } else if (css_name == "stroke-linejoin") { if ("miter" == data) { strk.set_line_join(mapnik::MITER_JOIN); } else if ("round" == data) { strk.set_line_join(mapnik::ROUND_JOIN); } else if ("bevel" == data) { strk.set_line_join(mapnik::BEVEL_JOIN); } } else if (css_name == "stroke-linecap") { if ("round" == data) { strk.set_line_cap(mapnik::ROUND_CAP); } else if ("butt" == data) { strk.set_line_cap(mapnik::BUTT_CAP); } else if ("square" == data) { strk.set_line_cap(mapnik::SQUARE_CAP); } } else if (css_name == "stroke-dasharray") { tokenizer<> tok (data); std::vector<float> dash_array; for (tokenizer<>::iterator itr = tok.begin(); itr != tok.end(); ++itr) { try { float f = boost::lexical_cast<float>(*itr); dash_array.push_back(f); } catch ( boost::bad_lexical_cast & ex) { std::clog << ex.what() << "\n"; } } if (dash_array.size()) { size_t size = dash_array.size(); if ( size % 2) { for (size_t i=0; i < size ;++i) { dash_array.push_back(dash_array[i]); } } std::vector<float>::const_iterator pos = dash_array.begin(); while (pos != dash_array.end()) { strk.add_dash(*pos,*(pos + 1)); pos +=2; } } } } rule.append(line_symbolizer(strk)); } else if ( sym.first == "PolygonSymbolizer") { polygon_symbolizer poly_sym; ptree::const_iterator cssIter = sym.second.begin(); ptree::const_iterator endCss = sym.second.end(); for(; cssIter != endCss; ++cssIter) { ptree::value_type const& css = * cssIter; std::string css_name = css.second.get<std::string>("<xmlattr>.name"); std::string data = css.second.data(); if (css_name == "fill") { Color c = color_factory::from_string(css.second.data().c_str()); poly_sym.set_fill(c); } else if (css_name == "fill-opacity") { try { float opacity = lexical_cast<float>(data); poly_sym.set_opacity(opacity); } catch (bad_lexical_cast & ex) { std::clog << ex.what() << "\n"; } } } rule.append(poly_sym); } else if ( sym.first == "TextSymbolizer") { std::cout << sym.first << "\n"; } else if ( sym.first == "RasterSymbolizer") { rule.append(raster_symbolizer()); } } style.add_rule(rule); } } map.insert_style(name, style); } else if (v.first == "Layer") { std::string name = v.second.get<std::string>("<xmlattr>.name","Unnamed"); std::string srs = v.second.get<std::string>("<xmlattr>.srs","+proj=latlong +datum=WGS84"); Layer lyr(name, srs); boost::optional<std::string> status = v.second.get_optional<std::string>("<xmlattr>.status"); if (status && *status == "off") { lyr.setActive(false); } ptree::const_iterator itr2 = v.second.begin(); ptree::const_iterator end2 = v.second.end(); for(; itr2 != end2; ++itr2) { ptree::value_type const& child = *itr2; if (child.first == "StyleName") { lyr.add_style(child.second.data()); } else if (child.first == "Datasource") { parameters params; ptree::const_iterator paramIter = child.second.begin(); ptree::const_iterator endParam = child.second.end(); for (; paramIter != endParam; ++paramIter) { ptree::value_type const& param_tag=*paramIter; if (param_tag.first == "Parameter") { std::string name = param_tag.second.get<std::string>("<xmlattr>.name"); std::string value = param_tag.second.data(); std::clog << "name = " << name << " value = " << value << "\n"; params[name] = value; } } //now we're ready to create datasource boost::shared_ptr<datasource> ds = datasource_cache::instance()->create(params); lyr.set_datasource(ds); } } map.addLayer(lyr); } } } } <|endoftext|>
<commit_before>/** \file * Implements the loadplay a bootstrapping tool for libloadplay. */ #include "Options.hpp" #include "errors.hpp" #include "utility.hpp" #include "sys/env.hpp" #include <iostream> /* std::cerr */ #include <unistd.h> /* execvp() */ /** * File local scope. */ namespace { using nih::Parameter; using nih::make_Options; using errors::Exit; using errors::Exception; using errors::fail; using utility::to_value; using namespace utility::literals; /** * An enum for command line parsing. */ enum class OE { USAGE, /**< Print help */ FILE_IN, /**< Set input file instead of stdin */ FILE_OUT, /**< Set output file instead of stdout */ CMD, /**< The command to execute */ OPT_NOOPT = CMD, /**< Obligatory */ OPT_UNKNOWN, /**< Obligatory */ OPT_DASH, /**< Obligatory */ OPT_LDASH, /**< Obligatory */ OPT_DONE /**< Obligatory */ }; /** * The short usage string. */ char const * const USAGE = "[-h] [-i file] [-o file] command [...]"; /** * Definitions of command line parameters. */ Parameter<OE> const PARAMETERS[]{ {OE::USAGE, 'h', "help", "", "Show usage and exit"}, {OE::FILE_IN, 'i', "input", "file", "Input file (load recording)"}, {OE::FILE_OUT, 'o', "output", "file", "Output file (replay stats)"}, {OE::CMD, 0 , "", "command,[...]", "The command to execute"}, }; /** * Performs very rudimentary file name argument checks. * * - Fail on empty path * - Return nullptr on '-' * * @param path * The file path to check * @return * The given path or nullptr if the given path is '-' */ char const * filename(char const * const path) { if (!path || !path[0]) { fail(Exit::EFILE, 0, "empty or missing string for filename"); } if ("-"_s == path) { return nullptr; } return path; } } /* namespace */ /** * Parse command line arguments and execute the given command. * * @param argc,argv * The command line arguments * @return * An exit code * @see Exit */ int main(int argc, char * argv[]) try { auto & env = sys::env::vars; auto getopt = make_Options(argc, argv, USAGE, PARAMETERS); try { while (true) switch (getopt()) { case OE::USAGE: std::cerr << getopt.usage(); throw Exception{Exit::OK, 0, ""}; case OE::FILE_IN: env["LOADPLAY_IN"] = filename(getopt[1]); break; case OE::FILE_OUT: env["LOADPLAY_OUT"] = filename(getopt[1]); break; case OE::CMD: env["LD_PRELOAD"] = "libloadplay.so"; assert(getopt.offset() < argc && "only OPT_DONE may violate this constraint"); /* forward the remainder of the arguments */ execvp(getopt[0], argv + getopt.offset()); /* ^^ must not return */ fail(Exit::EEXEC, errno, "failed to execute %s: %s"_fmt (getopt[0], strerror(errno))); break; case OE::OPT_UNKNOWN: case OE::OPT_DASH: case OE::OPT_LDASH: fail(Exit::ECLARG, 0, "unexpected command line argument: "_s + getopt[0]); break; case OE::OPT_DONE: fail(Exit::ECLARG, 0, "command expected"); break; } } catch (Exception & e) { switch (getopt) { case OE::USAGE: break; case OE::FILE_IN: case OE::FILE_OUT: e.msg += "\n\n"_s += getopt.show(1); break; case OE::CMD: e.msg += "\n\n"_s += getopt.show(0, 0); break; case OE::OPT_UNKNOWN: case OE::OPT_DASH: case OE::OPT_LDASH: case OE::OPT_DONE: e.msg += "\n\n"_s += getopt.show(0) += "\n\n"_s += getopt.usage(); break; } throw; } assert(!"must never be reached"); } catch (Exception & e) { if (e.msg != "") { std::cerr << "loadplay: " << e.msg << '\n'; } return to_value(e.exitcode); } catch (...) { std::cerr << "loadplay: untreated failure\n"; return to_value(Exit::EEXCEPT); } <commit_msg>Move the execvp() call to a wrapper function<commit_after>/** \file * Implements the loadplay a bootstrapping tool for libloadplay. */ #include "Options.hpp" #include "errors.hpp" #include "utility.hpp" #include "sys/env.hpp" #include <iostream> /* std::cerr */ #include <unistd.h> /* execvp() */ /** * File local scope. */ namespace { using nih::Parameter; using nih::make_Options; using errors::Exit; using errors::Exception; using errors::fail; using utility::to_value; using namespace utility::literals; /** * An enum for command line parsing. */ enum class OE { USAGE, /**< Print help */ FILE_IN, /**< Set input file instead of stdin */ FILE_OUT, /**< Set output file instead of stdout */ CMD, /**< The command to execute */ OPT_NOOPT = CMD, /**< Obligatory */ OPT_UNKNOWN, /**< Obligatory */ OPT_DASH, /**< Obligatory */ OPT_LDASH, /**< Obligatory */ OPT_DONE /**< Obligatory */ }; /** * The short usage string. */ char const * const USAGE = "[-h] [-i file] [-o file] command [...]"; /** * Definitions of command line parameters. */ Parameter<OE> const PARAMETERS[]{ {OE::USAGE, 'h', "help", "", "Show usage and exit"}, {OE::FILE_IN, 'i', "input", "file", "Input file (load recording)"}, {OE::FILE_OUT, 'o', "output", "file", "Output file (replay stats)"}, {OE::CMD, 0 , "", "command,[...]", "The command to execute"}, }; /** * Performs very rudimentary file name argument checks. * * - Fail on empty path * - Return nullptr on '-' * * @param path * The file path to check * @return * The given path or nullptr if the given path is '-' */ char const * filename(char const * const path) { if (!path || !path[0]) { fail(Exit::EFILE, 0, "empty or missing string for filename"); } if ("-"_s == path) { return nullptr; } return path; } /** * Executes the given command, substituting this process. * * This function is a wrapper around execvp(3) and does not return. * * @param file * The command to execute, looked up in PATH if no path is provided * @param argv * The command line arguments of the command * @throws errors::Exception{Exit::EEXEC} */ [[noreturn]] void execute(char const * const file, char * const argv[]) { if (!file || !file[0]) { fail(Exit::EEXEC, 0, "failed to execute empty command"); } execvp(file, argv); /* ^^ must not return */ fail(Exit::EEXEC, errno, "failed to execute %s: %s"_fmt(file, strerror(errno))); } } /* namespace */ /** * Parse command line arguments and execute the given command. * * @param argc,argv * The command line arguments * @return * An exit code * @see Exit */ int main(int argc, char * argv[]) try { auto & env = sys::env::vars; auto getopt = make_Options(argc, argv, USAGE, PARAMETERS); try { while (true) switch (getopt()) { case OE::USAGE: std::cerr << getopt.usage(); throw Exception{Exit::OK, 0, ""}; case OE::FILE_IN: env["LOADPLAY_IN"] = filename(getopt[1]); break; case OE::FILE_OUT: env["LOADPLAY_OUT"] = filename(getopt[1]); break; case OE::CMD: env["LD_PRELOAD"] = "libloadplay.so"; assert(getopt.offset() < argc && "only OPT_DONE may violate this constraint"); /* forward the remainder of the arguments */ execute(getopt[0], argv + getopt.offset()); break; case OE::OPT_UNKNOWN: case OE::OPT_DASH: case OE::OPT_LDASH: fail(Exit::ECLARG, 0, "unexpected command line argument: "_s + getopt[0]); break; case OE::OPT_DONE: fail(Exit::ECLARG, 0, "command expected"); break; } } catch (Exception & e) { switch (getopt) { case OE::USAGE: break; case OE::FILE_IN: case OE::FILE_OUT: e.msg += "\n\n"_s += getopt.show(1); break; case OE::CMD: e.msg += "\n\n"_s += getopt.show(0, 0); break; case OE::OPT_UNKNOWN: case OE::OPT_DASH: case OE::OPT_LDASH: case OE::OPT_DONE: e.msg += "\n\n"_s += getopt.show(0) += "\n\n"_s += getopt.usage(); break; } throw; } assert(!"must never be reached"); } catch (Exception & e) { if (e.msg != "") { std::cerr << "loadplay: " << e.msg << '\n'; } return to_value(e.exitcode); } catch (...) { std::cerr << "loadplay: untreated failure\n"; return to_value(Exit::EEXCEPT); } <|endoftext|>
<commit_before>#include "metatype_p.h" #include "metatype.h" #include <ostream> #include <mutex> #include <vector> #include <array> #include <unordered_map> #include <memory> #include <cassert> namespace rtti { namespace { #define DEFINE_STATIC_TYPE_INFO(NAME, TYPEID) \ TypeInfo{#NAME, sizeof(NAME), \ MetaType_ID{TYPEID}, MetaType_ID{TYPEID}, \ pointer_arity<NAME>::value, \ const_bitset<NAME>::value, \ internal::type_flags<NAME>::value, \ internal::type_function_table_for<NAME>() \ }, static std::array<TypeInfo, 38> const fundamentalTypes = {{ TypeInfo{"void", 0, MetaType_ID{0}, MetaType_ID{0}, 0, 0, internal::type_flags<void>::value, nullptr}, FOR_EACH_FUNDAMENTAL_TYPE(DEFINE_STATIC_TYPE_INFO) }}; #undef DEFINE_STATIC_TYPE_INFO class DLL_LOCAL CustomTypes { public: CustomTypes(); CustomTypes(CustomTypes const&) = delete; CustomTypes& operator=(CustomTypes const&) = delete; CustomTypes(CustomTypes &&) = delete; CustomTypes& operator=(CustomTypes &&) = delete; ~CustomTypes(); TypeInfo const* getTypeInfo(MetaType_ID typeId) const; TypeInfo const* getTypeInfo(std::string_view const &name) const; TypeInfo const* addTypeInfo(std::string_view const &name, std::size_t size, MetaType_ID decay, std::uint16_t arity, std::uint16_t const_mask, TypeFlags flags, metatype_manager_t const *manager); private: mutable std::mutex m_lock; std::vector<std::unique_ptr<TypeInfo>> m_items; std::unordered_map<std::string_view, std::size_t> m_names; static bool Destroyed; friend CustomTypes* customTypes(); }; bool CustomTypes::Destroyed = false; #define DEFINE_STATIC_TYPE_MAP(NAME, INDEX) \ {#NAME, INDEX}, CustomTypes::CustomTypes() : m_names { {"void", 0}, FOR_EACH_FUNDAMENTAL_TYPE(DEFINE_STATIC_TYPE_MAP) } {} #undef DEFINE_STATIC_TYPE_MAP CustomTypes::~CustomTypes() { std::lock_guard<std::mutex> lock{m_lock}; m_items.clear(); m_names.clear(); Destroyed = true; } TypeInfo const* CustomTypes::getTypeInfo(MetaType_ID typeId) const { auto type = std::size_t{typeId.value()}; if (type == MetaType::InvalidTypeId) return nullptr; if (type < fundamentalTypes.size()) return &fundamentalTypes[type]; type -= fundamentalTypes.size(); std::lock_guard<std::mutex> lock{m_lock}; if (type < m_items.size()) return m_items[type].get(); return nullptr; } const TypeInfo* CustomTypes::getTypeInfo(std::string_view const &name) const { if (name.empty()) return nullptr; std::lock_guard<std::mutex> lock{m_lock}; if (auto search = m_names.find(name); search != std::end(m_names)) { auto index = search->second; if (index < fundamentalTypes.size()) return &fundamentalTypes[index]; index -= fundamentalTypes.size(); if (index < m_items.size()) return m_items[index].get(); } return nullptr; } inline TypeInfo const* CustomTypes::addTypeInfo(std::string_view const &name, std::size_t size, MetaType_ID decay, uint16_t arity, uint16_t const_mask, TypeFlags flags, metatype_manager_t const *manager) { std::lock_guard<std::mutex> lock{m_lock}; auto type = static_cast<MetaType_ID::type>( fundamentalTypes.size() + m_items.size()); // this means that decay_t<type> = type if (decay.value() == MetaType::InvalidTypeId) decay = MetaType_ID{type}; auto result = new TypeInfo{name, size, MetaType_ID{type}, decay, arity, const_mask, flags, manager}; m_items.emplace_back(result); m_names.emplace(name, type); return result; } inline CustomTypes* customTypes() { if (CustomTypes::Destroyed) return nullptr; static CustomTypes result; return &result; } } // namespace //-------------------------------------------------------------------------------------------------------------------------------- // MetaType //-------------------------------------------------------------------------------------------------------------------------------- MetaType::MetaType(MetaType_ID typeId) noexcept { auto *types = customTypes(); if (types) m_typeInfo = types->getTypeInfo(typeId); } rtti::MetaType::MetaType(std::string_view const &name) noexcept { auto *types = customTypes(); if (types) m_typeInfo = types->getTypeInfo(name.data()); } MetaType_ID MetaType::typeId() const noexcept { if (m_typeInfo) return m_typeInfo->type; return MetaType_ID{}; } MetaType_ID MetaType::decayId() const noexcept { if (m_typeInfo) return m_typeInfo->decay; return MetaType_ID{}; } void MetaType::setTypeId(MetaType_ID typeId) { *this = MetaType{typeId}; } std::string_view MetaType::typeName() const noexcept { if (m_typeInfo) return m_typeInfo->name; return nullptr; } std::size_t MetaType::typeSize() const noexcept { if (m_typeInfo) return m_typeInfo->size; return 0; } TypeFlags MetaType::typeFlags() const noexcept { TypeFlags result = TypeFlags::None; if (m_typeInfo) result = m_typeInfo->flags; return result; } std::uint16_t MetaType::pointerArity() const noexcept { if (m_typeInfo) return m_typeInfo->arity; return 0; } bool MetaType::compatible(MetaType fromType, MetaType toType) noexcept { if (!fromType.valid() || !toType.valid()) return false; if (!fromType.isLvalueReference() && toType.isLvalueReference() && !toType.isConst()) return false; if (fromType.isLvalueReference() && toType.isRvalueReference()) return false; // check array length if (fromType.isArray() && toType.isArray() && (fromType.typeSize() < toType.typeSize())) return false; // decay array to pointer auto arity1 = fromType.m_typeInfo->arity; if (fromType.isArray() && toType.isPointer()) ++arity1; // compare pointer arity if (arity1 != toType.m_typeInfo->arity) return false; // skip top-most const when destination type isn't reference if (!toType.isReference()) { if (!arity1) return true; --arity1; } auto from = TypeInfo::const_bitset_t{fromType.m_typeInfo->const_mask}; auto to = TypeInfo::const_bitset_t{toType.m_typeInfo->const_mask}; // Decay to reference to pointer should be reference to const pointer if (fromType.isArray() && !toType.isArray() && toType.isReference()) from.set(arity1); if (from == to) return true; for (decltype(arity1) i = 0; i <= arity1; ++i) { auto f = from.test(i); auto t = to.test(i); if (f && !t) return false; if (!f & t) { for (decltype(arity1) j = i + 1; j <= arity1; ++j) if (!to.test(j)) return false; break; } } return true; } MetaType_ID MetaType::registerMetaType(char const *name, std::size_t size, MetaType_ID decay, std::uint16_t arity, std::uint16_t const_mask, TypeFlags flags, metatype_manager_t const *manager) { auto *types = customTypes(); if (!types) return MetaType_ID{}; auto result = types->getTypeInfo(name); if (!result) result = types->addTypeInfo(name, size, decay, arity, const_mask, flags, manager); return result->type; } //-------------------------------------------------------------------------------------------------------------------------------- // Low level construction //-------------------------------------------------------------------------------------------------------------------------------- void* MetaType::allocate() const { return m_typeInfo->manager->f_allocate(); } void MetaType::deallocate(void *ptr) const { return m_typeInfo->manager->f_deallocate(ptr); } void MetaType::default_construct(void *where) const { m_typeInfo->manager->f_default_construct(where); } void MetaType::copy_construct(void const *source, void *where) const { m_typeInfo->manager->f_copy_construct(source, where); } void MetaType::move_construct(void *source, void *where) const { m_typeInfo->manager->f_move_construct(source, where); } void MetaType::move_or_copy(void *source, bool movable, void *where) const { m_typeInfo->manager->f_move_or_copy(source, movable, where); } void MetaType::destroy(void *ptr) const noexcept { m_typeInfo->manager->f_destroy(ptr); } //-------------------------------------------------------------------------------------------------------------------------------- // Converter //-------------------------------------------------------------------------------------------------------------------------------- namespace { template<typename F> class MetaTypeFunctionList { public: using key_t = std::pair<MetaType_ID, MetaType_ID>; ~MetaTypeFunctionList() { std::lock_guard<std::mutex> lock{m_lock}; m_items.clear(); Destroyed = true; } bool find(key_t const &key) const { std::lock_guard<std::mutex> lock{m_lock}; return (m_items.find(key) != std::end(m_items)); } bool add(key_t key, F const *func) { if (!func) return false; std::lock_guard<std::mutex> lock{m_lock}; auto search = m_items.find(key); if (search != std::end(m_items)) return false; m_items.emplace(key, func); return true; } F const* get(key_t const &key) const { std::lock_guard<std::mutex> lock{m_lock}; auto search = m_items.find(key); if (search != std::end(m_items)) return search->second; return nullptr; } void remove(key_t const &key) { std::lock_guard<std::mutex> lock{m_lock}; m_items.erase(key); } private: struct hash_key { using result_type = std::size_t; using argument_type = key_t; result_type operator()(argument_type const &key) const { return std::_Hash_impl::__hash_combine(key.first.value(), std::_Hash_impl::hash(key.second.value())); } }; mutable std::mutex m_lock; std::unordered_map<key_t, F const*, hash_key> m_items; static bool Destroyed; friend MetaTypeFunctionList<internal::ConvertFunctionBase>* customConverters(); }; template<typename F> bool MetaTypeFunctionList<F>::Destroyed = false; inline MetaTypeFunctionList<internal::ConvertFunctionBase>* customConverters() { if (MetaTypeFunctionList<internal::ConvertFunctionBase>::Destroyed) return nullptr; static MetaTypeFunctionList<internal::ConvertFunctionBase> result; return &result; } } //namespace bool MetaType::hasConverter(MetaType fromType, MetaType toType) noexcept { if (fromType.valid() && toType.valid()) { auto list = customConverters(); if (list) return list->find({fromType.m_typeInfo->decay, toType.m_typeInfo->decay}); } return false; } bool MetaType::hasConverter(MetaType_ID fromTypeId, MetaType_ID toTypeId) noexcept { auto fromType = MetaType{fromTypeId}; auto toType = MetaType{toTypeId}; return hasConverter(fromType, toType); } bool MetaType::registerConverter(MetaType_ID fromTypeId, MetaType_ID toTypeId, internal::ConvertFunctionBase const &converter) { auto fromType = MetaType{fromTypeId}; auto toType = MetaType{toTypeId}; if (fromType.valid() && toType.valid()) { auto list = customConverters(); if (list) return list->add({fromType.m_typeInfo->decay, toType.m_typeInfo->decay}, &converter); } return false; } bool MetaType::convert(void const *from, MetaType fromType, void *to, MetaType toType) { if (fromType.valid() && toType.valid()) { auto list = customConverters(); if (list) { auto converter = list->get({fromType.m_typeInfo->decay, toType.m_typeInfo->decay}); assert(converter); return converter->invoke(from, to); } } return false; } bool MetaType::convert(void const *from, MetaType_ID fromTypeId, void *to, MetaType_ID toTypeId) { auto fromType = MetaType{fromTypeId}; auto toType = MetaType{toTypeId}; return convert(from, fromType, to, toType); } void MetaType::unregisterConverter(MetaType_ID fromTypeId, MetaType_ID toTypeId) { auto fromType = MetaType{fromTypeId}; auto toType = MetaType{toTypeId}; if (fromType.valid() && toType.valid()) { auto list = customConverters(); if (list) list->remove({fromType.m_typeInfo->decay, toType.m_typeInfo->decay}); } } } //namespace rtti std::ostream& operator<<(std::ostream &stream, rtti::MetaType const &value) { return stream << value.typeId().value() << ":" << value.typeName() << ":" << static_cast<std::underlying_type_t<rtti::TypeFlags>>(value.typeFlags()); } <commit_msg>C++17<commit_after>#include "metatype_p.h" #include "metatype.h" #include <ostream> #include <mutex> #include <vector> #include <array> #include <unordered_map> #include <memory> #include <cassert> namespace rtti { namespace { #define DEFINE_STATIC_TYPE_INFO(NAME, TYPEID) \ TypeInfo{#NAME, sizeof(NAME), \ MetaType_ID{TYPEID}, MetaType_ID{TYPEID}, \ pointer_arity<NAME>::value, \ const_bitset<NAME>::value, \ internal::type_flags<NAME>::value, \ internal::type_function_table_for<NAME>() \ }, static std::array<TypeInfo, 38> const fundamentalTypes = {{ TypeInfo{"void", 0, MetaType_ID{0}, MetaType_ID{0}, 0, 0, internal::type_flags<void>::value, nullptr}, FOR_EACH_FUNDAMENTAL_TYPE(DEFINE_STATIC_TYPE_INFO) }}; #undef DEFINE_STATIC_TYPE_INFO class DLL_LOCAL CustomTypes { public: CustomTypes(); CustomTypes(CustomTypes const&) = delete; CustomTypes& operator=(CustomTypes const&) = delete; CustomTypes(CustomTypes &&) = delete; CustomTypes& operator=(CustomTypes &&) = delete; ~CustomTypes(); TypeInfo const* getTypeInfo(MetaType_ID typeId) const; TypeInfo const* getTypeInfo(std::string_view const &name) const; TypeInfo const* addTypeInfo(std::string_view const &name, std::size_t size, MetaType_ID decay, std::uint16_t arity, std::uint16_t const_mask, TypeFlags flags, metatype_manager_t const *manager); private: mutable std::mutex m_lock; std::vector<std::unique_ptr<TypeInfo>> m_items; std::unordered_map<std::string_view, std::size_t> m_names; static bool Destroyed; friend CustomTypes* customTypes(); }; bool CustomTypes::Destroyed = false; #define DEFINE_STATIC_TYPE_MAP(NAME, INDEX) \ {#NAME, INDEX}, CustomTypes::CustomTypes() : m_names { {"void", 0}, FOR_EACH_FUNDAMENTAL_TYPE(DEFINE_STATIC_TYPE_MAP) } {} #undef DEFINE_STATIC_TYPE_MAP CustomTypes::~CustomTypes() { std::lock_guard<std::mutex> lock{m_lock}; m_items.clear(); m_names.clear(); Destroyed = true; } TypeInfo const* CustomTypes::getTypeInfo(MetaType_ID typeId) const { auto type = std::size_t{typeId.value()}; if (type == MetaType::InvalidTypeId) return nullptr; if (type < fundamentalTypes.size()) return &fundamentalTypes[type]; type -= fundamentalTypes.size(); std::lock_guard<std::mutex> lock{m_lock}; if (type < m_items.size()) return m_items[type].get(); return nullptr; } TypeInfo const* CustomTypes::getTypeInfo(std::string_view const &name) const { if (name.empty()) return nullptr; std::lock_guard<std::mutex> lock{m_lock}; if (auto search = m_names.find(name); search != std::end(m_names)) { auto index = search->second; if (index < fundamentalTypes.size()) return &fundamentalTypes[index]; index -= fundamentalTypes.size(); if (index < m_items.size()) return m_items[index].get(); } return nullptr; } TypeInfo const* CustomTypes::addTypeInfo(std::string_view const &name, std::size_t size, MetaType_ID decay, uint16_t arity, uint16_t const_mask, TypeFlags flags, metatype_manager_t const *manager) { std::lock_guard<std::mutex> lock{m_lock}; auto type = static_cast<MetaType_ID::type>( fundamentalTypes.size() + m_items.size()); // this means that decay_t<type> = type if (decay.value() == MetaType::InvalidTypeId) decay = MetaType_ID{type}; auto result = new TypeInfo{name, size, MetaType_ID{type}, decay, arity, const_mask, flags, manager}; m_items.emplace_back(result); m_names.emplace(name, type); return result; } inline CustomTypes* customTypes() { if (CustomTypes::Destroyed) return nullptr; static CustomTypes result; return &result; } } // namespace //-------------------------------------------------------------------------------------------------------------------------------- // MetaType //-------------------------------------------------------------------------------------------------------------------------------- MetaType::MetaType(MetaType_ID typeId) noexcept { if (auto *types = customTypes(); types) m_typeInfo = types->getTypeInfo(typeId); } rtti::MetaType::MetaType(std::string_view const &name) noexcept { if (auto *types = customTypes(); types) m_typeInfo = types->getTypeInfo(name.data()); } MetaType_ID MetaType::typeId() const noexcept { return m_typeInfo ? m_typeInfo->type : MetaType_ID{}; } MetaType_ID MetaType::decayId() const noexcept { return m_typeInfo ? m_typeInfo->decay : MetaType_ID{}; } void MetaType::setTypeId(MetaType_ID typeId) { *this = MetaType{typeId}; } std::string_view MetaType::typeName() const noexcept { return m_typeInfo ? m_typeInfo->name : nullptr; } std::size_t MetaType::typeSize() const noexcept { return m_typeInfo ? m_typeInfo->size : 0; } TypeFlags MetaType::typeFlags() const noexcept { return m_typeInfo ? m_typeInfo->flags : TypeFlags::None; } std::uint16_t MetaType::pointerArity() const noexcept { return m_typeInfo ? m_typeInfo->arity : 0; } bool MetaType::compatible(MetaType fromType, MetaType toType) noexcept { if (!fromType.valid() || !toType.valid()) return false; if (!fromType.isLvalueReference() && toType.isLvalueReference() && !toType.isConst()) return false; if (fromType.isLvalueReference() && toType.isRvalueReference()) return false; // check array length if (fromType.isArray() && toType.isArray() && (fromType.typeSize() < toType.typeSize())) return false; // decay array to pointer auto arity1 = fromType.m_typeInfo->arity; if (fromType.isArray() && toType.isPointer()) ++arity1; // compare pointer arity if (arity1 != toType.m_typeInfo->arity) return false; // skip top-most const when destination type isn't reference if (!toType.isReference()) { if (!arity1) return true; --arity1; } auto from = TypeInfo::const_bitset_t{fromType.m_typeInfo->const_mask}; auto to = TypeInfo::const_bitset_t{toType.m_typeInfo->const_mask}; // Decay to reference to pointer should be reference to const pointer if (fromType.isArray() && !toType.isArray() && toType.isReference()) from.set(arity1); if (from == to) return true; for (decltype(arity1) i = 0; i <= arity1; ++i) { auto f = from.test(i); auto t = to.test(i); if (f && !t) return false; if (!f & t) { for (decltype(arity1) j = i + 1; j <= arity1; ++j) if (!to.test(j)) return false; break; } } return true; } MetaType_ID MetaType::registerMetaType(char const *name, std::size_t size, MetaType_ID decay, std::uint16_t arity, std::uint16_t const_mask, TypeFlags flags, metatype_manager_t const *manager) { auto *types = customTypes(); if (!types) return MetaType_ID{}; auto result = types->getTypeInfo(name); if (!result) result = types->addTypeInfo(name, size, decay, arity, const_mask, flags, manager); return result->type; } //-------------------------------------------------------------------------------------------------------------------------------- // Low level construction //-------------------------------------------------------------------------------------------------------------------------------- void* MetaType::allocate() const { return m_typeInfo->manager->f_allocate(); } void MetaType::deallocate(void *ptr) const { return m_typeInfo->manager->f_deallocate(ptr); } void MetaType::default_construct(void *where) const { m_typeInfo->manager->f_default_construct(where); } void MetaType::copy_construct(void const *source, void *where) const { m_typeInfo->manager->f_copy_construct(source, where); } void MetaType::move_construct(void *source, void *where) const { m_typeInfo->manager->f_move_construct(source, where); } void MetaType::move_or_copy(void *source, bool movable, void *where) const { m_typeInfo->manager->f_move_or_copy(source, movable, where); } void MetaType::destroy(void *ptr) const noexcept { m_typeInfo->manager->f_destroy(ptr); } //-------------------------------------------------------------------------------------------------------------------------------- // Converter //-------------------------------------------------------------------------------------------------------------------------------- namespace { template<typename F> class MetaTypeFunctionList { public: using key_t = std::pair<MetaType_ID, MetaType_ID>; ~MetaTypeFunctionList() { std::lock_guard<std::mutex> lock{m_lock}; m_items.clear(); Destroyed = true; } bool find(key_t const &key) const { std::lock_guard<std::mutex> lock{m_lock}; return (m_items.find(key) != std::end(m_items)); } bool add(key_t key, F const *func) { if (!func) return false; std::lock_guard<std::mutex> lock{m_lock}; auto search = m_items.find(key); if (search != std::end(m_items)) return false; m_items.emplace(key, func); return true; } F const* get(key_t const &key) const { std::lock_guard<std::mutex> lock{m_lock}; auto search = m_items.find(key); if (search != std::end(m_items)) return search->second; return nullptr; } void remove(key_t const &key) { std::lock_guard<std::mutex> lock{m_lock}; m_items.erase(key); } private: struct hash_key { using result_type = std::size_t; using argument_type = key_t; result_type operator()(argument_type const &key) const { return std::_Hash_impl::__hash_combine(key.first.value(), std::_Hash_impl::hash(key.second.value())); } }; mutable std::mutex m_lock; std::unordered_map<key_t, F const*, hash_key> m_items; static bool Destroyed; friend MetaTypeFunctionList<internal::ConvertFunctionBase>* customConverters(); }; template<typename F> bool MetaTypeFunctionList<F>::Destroyed = false; inline MetaTypeFunctionList<internal::ConvertFunctionBase>* customConverters() { if (MetaTypeFunctionList<internal::ConvertFunctionBase>::Destroyed) return nullptr; static MetaTypeFunctionList<internal::ConvertFunctionBase> result; return &result; } } //namespace bool MetaType::hasConverter(MetaType fromType, MetaType toType) noexcept { if (fromType.valid() && toType.valid()) { auto list = customConverters(); if (list) return list->find({fromType.m_typeInfo->decay, toType.m_typeInfo->decay}); } return false; } bool MetaType::hasConverter(MetaType_ID fromTypeId, MetaType_ID toTypeId) noexcept { auto fromType = MetaType{fromTypeId}; auto toType = MetaType{toTypeId}; return hasConverter(fromType, toType); } bool MetaType::registerConverter(MetaType_ID fromTypeId, MetaType_ID toTypeId, internal::ConvertFunctionBase const &converter) { auto fromType = MetaType{fromTypeId}; auto toType = MetaType{toTypeId}; if (fromType.valid() && toType.valid()) { auto list = customConverters(); if (list) return list->add({fromType.m_typeInfo->decay, toType.m_typeInfo->decay}, &converter); } return false; } bool MetaType::convert(void const *from, MetaType fromType, void *to, MetaType toType) { if (fromType.valid() && toType.valid()) { auto list = customConverters(); if (list) { auto converter = list->get({fromType.m_typeInfo->decay, toType.m_typeInfo->decay}); assert(converter); return converter->invoke(from, to); } } return false; } bool MetaType::convert(void const *from, MetaType_ID fromTypeId, void *to, MetaType_ID toTypeId) { auto fromType = MetaType{fromTypeId}; auto toType = MetaType{toTypeId}; return convert(from, fromType, to, toType); } void MetaType::unregisterConverter(MetaType_ID fromTypeId, MetaType_ID toTypeId) { auto fromType = MetaType{fromTypeId}; auto toType = MetaType{toTypeId}; if (fromType.valid() && toType.valid()) { auto list = customConverters(); if (list) list->remove({fromType.m_typeInfo->decay, toType.m_typeInfo->decay}); } } } //namespace rtti std::ostream& operator<<(std::ostream &stream, rtti::MetaType const &value) { return stream << value.typeId().value() << ":" << value.typeName() << ":" << static_cast<std::underlying_type_t<rtti::TypeFlags>>(value.typeFlags()); } <|endoftext|>
<commit_before>/** * v8cgi - apache module. * Extends v8cgi_App by adding customized initialization and (std)IO routines */ #include <stdlib.h> #include <string.h> #include "httpd.h" #include "http_config.h" #include "http_log.h" #include "http_protocol.h" #include "util_script.h" #include "apr_pools.h" #include "apr_base64.h" #include "apr_strings.h" #include "app.h" #include "path.h" #include "macros.h" typedef struct { const char * config; } v8cgi_config; /** * First module declaration */ extern "C" module AP_MODULE_DECLARE_DATA v8cgi_module; class v8cgi_Module : public v8cgi_App { public: request_rec * request; size_t write(const char * data, size_t size) { return ap_rwrite(data, size, this->request); } void error(const char * data) { ap_log_rerror(__FILE__, __LINE__, APLOG_ERR, 0, this->request, "%s", data); } /** * Remember apache request structure and continue as usually */ void execute(request_rec * request, char ** envp) { this->request = request; this->mainfile = std::string(request->filename); int chdir_result = path_chdir(path_dirname(this->mainfile)); if (chdir_result == -1) { return; } v8cgi_App::execute(envp); } void init(v8cgi_config * cfg) { v8cgi_App::init(); this->cfgfile = cfg->config; } /** * Set a HTTP response header * @param {char *} name * @param {char *} value */ void header(const char * name, const char * value) { if (strcasecmp(name, "content-type") == 0) { char * ct = (char *) apr_palloc(request->pool, strlen(value)+1); strcpy(ct, value); this->request->content_type = ct; } else if (strcasecmp(name, "status") == 0) { char * line = (char *) apr_palloc(request->pool, strlen(value)+1); strcpy(line, value); this->request->status_line = line; this->request->status = atoi(value); } else { char * n = (char *) apr_palloc(request->pool, strlen(name)+1); char * v = (char *) apr_palloc(request->pool, strlen(value)+1); strcpy(n, name); strcpy(v, value); apr_table_addn(this->request->headers_out, n, v); } } protected: void prepare(char ** envp); private: const char * instanceType() { return "module"; } const char * executableName() { return "?"; } }; JS_METHOD(_read) { v8cgi_Module * app = (v8cgi_Module *) APP_PTR; if (args.Length() < 1) { return JS_TYPE_ERROR("Invalid call format. Use 'apache.read(amount)'"); } size_t count = args[0]->IntegerValue(); char * destination = new char[count]; size_t read = 0; long part = 0; do { part = ap_get_client_block(app->request, destination+read, count-read); if (part<0) { break; } read += part; } while (part>0 && read<count); v8::Handle<v8::Value> result = JS_BUFFER(destination, read); delete[] destination; return result; } JS_METHOD(_write) { v8cgi_Module * app = (v8cgi_Module *) APP_PTR; if (args.Length() < 1) { return JS_TYPE_ERROR("Invalid call format. Use 'apache.write(data)'"); } size_t result; if (IS_BUFFER(args[0])) { size_t size = 0; char * data = JS_BUFFER_TO_CHAR(args[0], &size); result = app->write(data, size); } else { v8::String::Utf8Value str(args[0]); result = app->write(*str, str.length()); } return JS_INT(result); } JS_METHOD(_error) { v8cgi_Module * app = (v8cgi_Module *) APP_PTR; v8::String::Utf8Value error(args[0]); app->error(*error); return v8::Undefined(); } JS_METHOD(_header) { v8cgi_Module * app = (v8cgi_Module *) APP_PTR; v8::String::Utf8Value name(args[0]); v8::String::Utf8Value value(args[1]); app->header(*name, *value); return v8::Undefined(); } void v8cgi_Module::prepare(char ** envp) { v8cgi_App::prepare(envp); v8::HandleScope handle_scope; v8::Handle<v8::Object> g = JS_GLOBAL; v8::Handle<v8::Object> apache = v8::Object::New(); g->Set(JS_STR("apache"), apache); apache->Set(JS_STR("header"), v8::FunctionTemplate::New(_header)->GetFunction()); apache->Set(JS_STR("read"), v8::FunctionTemplate::New(_read)->GetFunction()); apache->Set(JS_STR("write"), v8::FunctionTemplate::New(_write)->GetFunction()); apache->Set(JS_STR("error"), v8::FunctionTemplate::New(_error)->GetFunction()); } /** * This is called from Apache every time request arrives */ static int mod_v8cgi_handler(request_rec *r) { const apr_array_header_t *arr; const apr_table_entry_t *elts; if (!r->handler || strcmp(r->handler, "v8cgi-script")) { return DECLINED; } ap_setup_client_block(r, REQUEST_CHUNKED_DECHUNK); ap_add_common_vars(r); ap_add_cgi_vars(r); if (r->headers_in) { const char *auth; auth = apr_table_get(r->headers_in, "Authorization"); if (auth && auth[0] != 0 && strncmp(auth, "Basic ", 6) == 0) { char *user = NULL; char *pass = NULL; int length; user = (char *)apr_palloc(r->pool, apr_base64_decode_len(auth+6) + 1); length = apr_base64_decode(user, auth + 6); /* Null-terminate the string. */ user[length] = '\0'; if (user) { pass = strchr(user, ':'); if (pass) { *pass++ = '\0'; apr_table_setn(r->subprocess_env, "AUTH_USER", user); apr_table_setn(r->subprocess_env, "AUTH_PW", pass); } } } } /* extract the CGI environment */ arr = apr_table_elts(r->subprocess_env); elts = (const apr_table_entry_t*) arr->elts; char ** envp = new char *[arr->nelts + 1]; envp[arr->nelts] = NULL; size_t size = 0; size_t len1 = 0; size_t len2 = 0; for (int i=0;i<arr->nelts;i++) { len1 = strlen(elts[i].key); len2 = strlen(elts[i].val); size = len1 + len2 + 2; envp[i] = new char[size]; envp[i][size-1] = '\0'; envp[i][len1] = '='; strncpy(envp[i], elts[i].key, len1); strncpy(&(envp[i][len1+1]), elts[i].val, len2); } v8cgi_config * cfg = (v8cgi_config *) ap_get_module_config(r->server->module_config, &v8cgi_module); v8cgi_Module app; app.init(cfg); try { app.execute(r, envp); } catch (std::string e) { if (app.show_errors) { app.write(e.c_str(), e.length()); } else { app.error(e.c_str()); } } for (int i=0;i<arr->nelts;i++) { delete[] envp[i]; } delete[] envp; // Ok is safer, because HTTP_INTERNAL_SERVER_ERROR overwrites any content already generated // if (result) { // return HTTP_INTERNAL_SERVER_ERROR; // } else { return OK; // } } /** * Module initialization */ static int mod_v8cgi_init_handler(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) { std::string version; version += "mod_v8cgi/"; version += STRING(VERSION); ap_add_version_component(p, version.c_str()); return OK; } /** * Child initialization * FIXME: what is this for? */ static void mod_v8cgi_child_init(apr_pool_t *p, server_rec *s) { } /** * Register relevant hooks */ static void mod_v8cgi_register_hooks(apr_pool_t *p ) { ap_hook_handler(mod_v8cgi_handler, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_post_config(mod_v8cgi_init_handler, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_child_init(mod_v8cgi_child_init, NULL, NULL, APR_HOOK_MIDDLE); } /** * Create initial configuration values */ static void * mod_v8cgi_create_config(apr_pool_t *p, server_rec *s) { v8cgi_config * newcfg = (v8cgi_config *) apr_pcalloc(p, sizeof(v8cgi_config)); newcfg->config = STRING(CONFIG_PATH); return (void *) newcfg; } /** * Callback executed for every configuration change */ static const char * set_v8cgi_config(cmd_parms * parms, void * mconfig, const char * arg) { v8cgi_config * cfg = (v8cgi_config *) ap_get_module_config(parms->server->module_config, &v8cgi_module); cfg->config = (char *) arg; return NULL; } typedef const char * (* CONFIG_HANDLER) (); /* list of configurations */ static const command_rec mod_v8cgi_cmds[] = { AP_INIT_TAKE1( "v8cgi_Config", (CONFIG_HANDLER) set_v8cgi_config, NULL, RSRC_CONF, "Path to v8cgi configuration file." ), {NULL} }; /** * Module (re-)declaration */ extern "C" { module AP_MODULE_DECLARE_DATA v8cgi_module = { STANDARD20_MODULE_STUFF, NULL, NULL, mod_v8cgi_create_config, NULL, mod_v8cgi_cmds, mod_v8cgi_register_hooks, }; } <commit_msg>patch for apache2.4, thanks to ZenDark<commit_after>/** * v8cgi - apache module. * Extends v8cgi_App by adding customized initialization and (std)IO routines */ #include <stdlib.h> #include <string.h> #include "httpd.h" #include "http_config.h" #include "http_log.h" #include "http_protocol.h" #include "util_script.h" #include "apr_pools.h" #include "apr_base64.h" #include "apr_strings.h" #include "app.h" #include "path.h" #include "macros.h" typedef struct { const char * config; } v8cgi_config; /** * First module declaration */ extern "C" module AP_MODULE_DECLARE_DATA v8cgi_module; #ifdef APLOG_USE_MODULE APLOG_USE_MODULE(v8cgi); #endif class v8cgi_Module : public v8cgi_App { public: request_rec * request; size_t write(const char * data, size_t size) { return ap_rwrite(data, size, this->request); } void error(const char * data) { #ifdef APLOG_USE_MODULE ap_log_rerror(__FILE__, __LINE__, APLOG_MODULE_INDEX, APLOG_ERR, 0, this->request, "%s", data); #else ap_log_rerror(__FILE__, __LINE__, APLOG_ERR, 0, this->request, "%s", data); #endif } /** * Remember apache request structure and continue as usually */ void execute(request_rec * request, char ** envp) { this->request = request; this->mainfile = std::string(request->filename); int chdir_result = path_chdir(path_dirname(this->mainfile)); if (chdir_result == -1) { return; } v8cgi_App::execute(envp); } void init(v8cgi_config * cfg) { v8cgi_App::init(); this->cfgfile = cfg->config; } /** * Set a HTTP response header * @param {char *} name * @param {char *} value */ void header(const char * name, const char * value) { if (strcasecmp(name, "content-type") == 0) { char * ct = (char *) apr_palloc(request->pool, strlen(value)+1); strcpy(ct, value); this->request->content_type = ct; } else if (strcasecmp(name, "status") == 0) { char * line = (char *) apr_palloc(request->pool, strlen(value)+1); strcpy(line, value); this->request->status_line = line; this->request->status = atoi(value); } else { char * n = (char *) apr_palloc(request->pool, strlen(name)+1); char * v = (char *) apr_palloc(request->pool, strlen(value)+1); strcpy(n, name); strcpy(v, value); apr_table_addn(this->request->headers_out, n, v); } } protected: void prepare(char ** envp); private: const char * instanceType() { return "module"; } const char * executableName() { return "?"; } }; JS_METHOD(_read) { v8cgi_Module * app = (v8cgi_Module *) APP_PTR; if (args.Length() < 1) { return JS_TYPE_ERROR("Invalid call format. Use 'apache.read(amount)'"); } size_t count = args[0]->IntegerValue(); char * destination = new char[count]; size_t read = 0; long part = 0; do { part = ap_get_client_block(app->request, destination+read, count-read); if (part<0) { break; } read += part; } while (part>0 && read<count); v8::Handle<v8::Value> result = JS_BUFFER(destination, read); delete[] destination; return result; } JS_METHOD(_write) { v8cgi_Module * app = (v8cgi_Module *) APP_PTR; if (args.Length() < 1) { return JS_TYPE_ERROR("Invalid call format. Use 'apache.write(data)'"); } size_t result; if (IS_BUFFER(args[0])) { size_t size = 0; char * data = JS_BUFFER_TO_CHAR(args[0], &size); result = app->write(data, size); } else { v8::String::Utf8Value str(args[0]); result = app->write(*str, str.length()); } return JS_INT(result); } JS_METHOD(_error) { v8cgi_Module * app = (v8cgi_Module *) APP_PTR; v8::String::Utf8Value error(args[0]); app->error(*error); return v8::Undefined(); } JS_METHOD(_header) { v8cgi_Module * app = (v8cgi_Module *) APP_PTR; v8::String::Utf8Value name(args[0]); v8::String::Utf8Value value(args[1]); app->header(*name, *value); return v8::Undefined(); } void v8cgi_Module::prepare(char ** envp) { v8cgi_App::prepare(envp); v8::HandleScope handle_scope; v8::Handle<v8::Object> g = JS_GLOBAL; v8::Handle<v8::Object> apache = v8::Object::New(); g->Set(JS_STR("apache"), apache); apache->Set(JS_STR("header"), v8::FunctionTemplate::New(_header)->GetFunction()); apache->Set(JS_STR("read"), v8::FunctionTemplate::New(_read)->GetFunction()); apache->Set(JS_STR("write"), v8::FunctionTemplate::New(_write)->GetFunction()); apache->Set(JS_STR("error"), v8::FunctionTemplate::New(_error)->GetFunction()); } /** * This is called from Apache every time request arrives */ static int mod_v8cgi_handler(request_rec *r) { const apr_array_header_t *arr; const apr_table_entry_t *elts; if (!r->handler || strcmp(r->handler, "v8cgi-script")) { return DECLINED; } ap_setup_client_block(r, REQUEST_CHUNKED_DECHUNK); ap_add_common_vars(r); ap_add_cgi_vars(r); if (r->headers_in) { const char *auth; auth = apr_table_get(r->headers_in, "Authorization"); if (auth && auth[0] != 0 && strncmp(auth, "Basic ", 6) == 0) { char *user = NULL; char *pass = NULL; int length; user = (char *)apr_palloc(r->pool, apr_base64_decode_len(auth+6) + 1); length = apr_base64_decode(user, auth + 6); /* Null-terminate the string. */ user[length] = '\0'; if (user) { pass = strchr(user, ':'); if (pass) { *pass++ = '\0'; apr_table_setn(r->subprocess_env, "AUTH_USER", user); apr_table_setn(r->subprocess_env, "AUTH_PW", pass); } } } } /* extract the CGI environment */ arr = apr_table_elts(r->subprocess_env); elts = (const apr_table_entry_t*) arr->elts; char ** envp = new char *[arr->nelts + 1]; envp[arr->nelts] = NULL; size_t size = 0; size_t len1 = 0; size_t len2 = 0; for (int i=0;i<arr->nelts;i++) { len1 = strlen(elts[i].key); len2 = strlen(elts[i].val); size = len1 + len2 + 2; envp[i] = new char[size]; envp[i][size-1] = '\0'; envp[i][len1] = '='; strncpy(envp[i], elts[i].key, len1); strncpy(&(envp[i][len1+1]), elts[i].val, len2); } v8cgi_config * cfg = (v8cgi_config *) ap_get_module_config(r->server->module_config, &v8cgi_module); v8cgi_Module app; app.init(cfg); try { app.execute(r, envp); } catch (std::string e) { if (app.show_errors) { app.write(e.c_str(), e.length()); } else { app.error(e.c_str()); } } for (int i=0;i<arr->nelts;i++) { delete[] envp[i]; } delete[] envp; // Ok is safer, because HTTP_INTERNAL_SERVER_ERROR overwrites any content already generated // if (result) { // return HTTP_INTERNAL_SERVER_ERROR; // } else { return OK; // } } /** * Module initialization */ static int mod_v8cgi_init_handler(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) { std::string version; version += "mod_v8cgi/"; version += STRING(VERSION); ap_add_version_component(p, version.c_str()); return OK; } /** * Child initialization * FIXME: what is this for? */ static void mod_v8cgi_child_init(apr_pool_t *p, server_rec *s) { } /** * Register relevant hooks */ static void mod_v8cgi_register_hooks(apr_pool_t *p ) { ap_hook_handler(mod_v8cgi_handler, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_post_config(mod_v8cgi_init_handler, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_child_init(mod_v8cgi_child_init, NULL, NULL, APR_HOOK_MIDDLE); } /** * Create initial configuration values */ static void * mod_v8cgi_create_config(apr_pool_t *p, server_rec *s) { v8cgi_config * newcfg = (v8cgi_config *) apr_pcalloc(p, sizeof(v8cgi_config)); newcfg->config = STRING(CONFIG_PATH); return (void *) newcfg; } /** * Callback executed for every configuration change */ static const char * set_v8cgi_config(cmd_parms * parms, void * mconfig, const char * arg) { v8cgi_config * cfg = (v8cgi_config *) ap_get_module_config(parms->server->module_config, &v8cgi_module); cfg->config = (char *) arg; return NULL; } typedef const char * (* CONFIG_HANDLER) (); /* list of configurations */ static const command_rec mod_v8cgi_cmds[] = { AP_INIT_TAKE1( "v8cgi_Config", (CONFIG_HANDLER) set_v8cgi_config, NULL, RSRC_CONF, "Path to v8cgi configuration file." ), {NULL} }; /** * Module (re-)declaration */ extern "C" { module AP_MODULE_DECLARE_DATA v8cgi_module = { STANDARD20_MODULE_STUFF, NULL, NULL, mod_v8cgi_create_config, NULL, mod_v8cgi_cmds, mod_v8cgi_register_hooks, }; } <|endoftext|>
<commit_before> #include "include/Shapes.h" double sumOfArea(const std::vector<Shape *> & shapes) { double total =0; for (Shape *shapePoint: shapes) total += shapePoint->area(); return total; } double sumOfPerimeter(const std::vector<Shape *> & shapes){ double total = 0; for (Shape *shapePoint: shapes) total += shapePoint->perimeter(); return total; } Shape* theLargestArea(const std::vector<Shape *> & shapes){ Shape *largestShape = nullptr; double largestArea = 0; for (Shape *shapePoint: shapes) if(shapePoint->area() >= largestArea){ largestArea = shapePoint->area(); largestShape = shapePoint; } return largestShape; } double distanceOfVertexs(const vertex vertex_1, const vertex vertex_2) { double diff_X, diff_Y, distance; diff_X = vertex_1.x - vertex_2.x; diff_Y = vertex_1.y - vertex_2.y; distance = sqrt(((diff_X * diff_X) + (diff_Y * diff_Y))); return distance; } void sortByDecreasingPerimeter(std::vector<Shape *> & shapes) { // use the shakeSort int left = 0; int right = shapes.size()-1; int shift = 0; Shape *temp; while(left < right){ for(int i = left; i < right; i++) { if(shapes[i]->perimeter() < shapes[i+1]->perimeter()){ temp = shapes[i]; shapes[i] = shapes[i+1]; shapes[i+1] = temp; shift = i; } } right = shift; for(int i = right; i > left; i--){ if(shapes[i]->perimeter() > shapes[i-1]->perimeter()){ temp = shapes[i]; shapes[i] = shapes[i-1]; shapes[i-1] = temp; shift = i; } } left = shift; } } <commit_msg>Delete Shapes.cpp<commit_after><|endoftext|>
<commit_before>/* * Copyright (C) 2004-2010 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "Socket.h" #include "Modules.h" #include "User.h" #include "znc.h" unsigned int CSockManager::GetAnonConnectionCount(const CString &sIP) const { const_iterator it; unsigned int ret = 0; for (it = begin(); it != end(); it++) { CZNCSock *pSock = *it; // Logged in CClients have "USR::<username>" as their sockname if (pSock->GetRemoteIP() == sIP && pSock->GetSockName().Left(5) != "USR::") { ret++; } } DEBUG("There are [" << ret << "] clients from [" << sIP << "]"); return ret; } /////////////////// CSocket /////////////////// CSocket::CSocket(CModule* pModule) : CZNCSock() { m_pModule = pModule; m_pModule->AddSocket(this); EnableReadLine(); SetMaxBufferThreshold(10240); } CSocket::CSocket(CModule* pModule, const CString& sHostname, unsigned short uPort, int iTimeout) : CZNCSock(sHostname, uPort, iTimeout) { m_pModule = pModule; m_pModule->AddSocket(this); EnableReadLine(); SetMaxBufferThreshold(10240); } CSocket::~CSocket() { CUser *pUser = m_pModule->GetUser(); m_pModule->UnlinkSocket(this); if (!m_pModule->IsGlobal() && pUser) { pUser->AddBytesWritten(GetBytesWritten()); pUser->AddBytesRead(GetBytesRead()); } else { CZNC::Get().AddBytesWritten(GetBytesWritten()); CZNC::Get().AddBytesRead(GetBytesRead()); } } void CSocket::ReachedMaxBuffer() { DEBUG(GetSockName() << " == ReachedMaxBuffer()"); PutModule("Some socket reached its max buffer limit and was closed!"); Close(); } void CSocket::SockError(int iErrno) { DEBUG(GetSockName() << " == SockError(" << strerror(iErrno) << ")"); if (iErrno == EMFILE) { // We have too many open fds, this can cause a busy loop. Close(); } } bool CSocket::ConnectionFrom(const CString& sHost, unsigned short uPort) { return CZNC::Get().AllowConnectionFrom(sHost); } bool CSocket::Connect(const CString& sHostname, unsigned short uPort, bool bSSL, unsigned int uTimeout) { CUser* pUser = m_pModule->GetUser(); CString sSockName = "MOD::C::" + m_pModule->GetModName(); CString sVHost; if (pUser) { sSockName += "::" + pUser->GetUserName(); sVHost = m_pModule->GetUser()->GetVHost(); } // Don't overwrite the socket name if one is already set if (!GetSockName().empty()) { sSockName = GetSockName(); } return m_pModule->GetManager()->Connect(sHostname, uPort, sSockName, uTimeout, bSSL, sVHost, this); } bool CSocket::Listen(unsigned short uPort, bool bSSL, unsigned int uTimeout) { CUser* pUser = m_pModule->GetUser(); CString sSockName = "MOD::L::" + m_pModule->GetModName(); if (pUser) { sSockName += "::" + pUser->GetUserName(); } // Don't overwrite the socket name if one is already set if (!GetSockName().empty()) { sSockName = GetSockName(); } return m_pModule->GetManager()->ListenAll(uPort, sSockName, bSSL, SOMAXCONN, this); } bool CSocket::PutIRC(const CString& sLine) { return (m_pModule) ? m_pModule->PutIRC(sLine) : false; } bool CSocket::PutUser(const CString& sLine) { return (m_pModule) ? m_pModule->PutUser(sLine) : false; } bool CSocket::PutStatus(const CString& sLine) { return (m_pModule) ? m_pModule->PutStatus(sLine) : false; } bool CSocket::PutModule(const CString& sLine, const CString& sIdent, const CString& sHost) { return (m_pModule) ? m_pModule->PutModule(sLine, sIdent, sHost) : false; } bool CSocket::PutModNotice(const CString& sLine, const CString& sIdent, const CString& sHost) { return (m_pModule) ? m_pModule->PutModNotice(sLine, sIdent, sHost) : false; } void CSocket::SetModule(CModule* p) { m_pModule = p; } CModule* CSocket::GetModule() const { return m_pModule; } /////////////////// !CSocket /////////////////// <commit_msg>Socket.cpp: Add missing #ifdef _MODULES<commit_after>/* * Copyright (C) 2004-2010 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "Socket.h" #include "Modules.h" #include "User.h" #include "znc.h" unsigned int CSockManager::GetAnonConnectionCount(const CString &sIP) const { const_iterator it; unsigned int ret = 0; for (it = begin(); it != end(); it++) { CZNCSock *pSock = *it; // Logged in CClients have "USR::<username>" as their sockname if (pSock->GetRemoteIP() == sIP && pSock->GetSockName().Left(5) != "USR::") { ret++; } } DEBUG("There are [" << ret << "] clients from [" << sIP << "]"); return ret; } #ifdef _MODULES /////////////////// CSocket /////////////////// CSocket::CSocket(CModule* pModule) : CZNCSock() { m_pModule = pModule; m_pModule->AddSocket(this); EnableReadLine(); SetMaxBufferThreshold(10240); } CSocket::CSocket(CModule* pModule, const CString& sHostname, unsigned short uPort, int iTimeout) : CZNCSock(sHostname, uPort, iTimeout) { m_pModule = pModule; m_pModule->AddSocket(this); EnableReadLine(); SetMaxBufferThreshold(10240); } CSocket::~CSocket() { CUser *pUser = m_pModule->GetUser(); m_pModule->UnlinkSocket(this); if (!m_pModule->IsGlobal() && pUser) { pUser->AddBytesWritten(GetBytesWritten()); pUser->AddBytesRead(GetBytesRead()); } else { CZNC::Get().AddBytesWritten(GetBytesWritten()); CZNC::Get().AddBytesRead(GetBytesRead()); } } void CSocket::ReachedMaxBuffer() { DEBUG(GetSockName() << " == ReachedMaxBuffer()"); PutModule("Some socket reached its max buffer limit and was closed!"); Close(); } void CSocket::SockError(int iErrno) { DEBUG(GetSockName() << " == SockError(" << strerror(iErrno) << ")"); if (iErrno == EMFILE) { // We have too many open fds, this can cause a busy loop. Close(); } } bool CSocket::ConnectionFrom(const CString& sHost, unsigned short uPort) { return CZNC::Get().AllowConnectionFrom(sHost); } bool CSocket::Connect(const CString& sHostname, unsigned short uPort, bool bSSL, unsigned int uTimeout) { CUser* pUser = m_pModule->GetUser(); CString sSockName = "MOD::C::" + m_pModule->GetModName(); CString sVHost; if (pUser) { sSockName += "::" + pUser->GetUserName(); sVHost = m_pModule->GetUser()->GetVHost(); } // Don't overwrite the socket name if one is already set if (!GetSockName().empty()) { sSockName = GetSockName(); } return m_pModule->GetManager()->Connect(sHostname, uPort, sSockName, uTimeout, bSSL, sVHost, this); } bool CSocket::Listen(unsigned short uPort, bool bSSL, unsigned int uTimeout) { CUser* pUser = m_pModule->GetUser(); CString sSockName = "MOD::L::" + m_pModule->GetModName(); if (pUser) { sSockName += "::" + pUser->GetUserName(); } // Don't overwrite the socket name if one is already set if (!GetSockName().empty()) { sSockName = GetSockName(); } return m_pModule->GetManager()->ListenAll(uPort, sSockName, bSSL, SOMAXCONN, this); } bool CSocket::PutIRC(const CString& sLine) { return (m_pModule) ? m_pModule->PutIRC(sLine) : false; } bool CSocket::PutUser(const CString& sLine) { return (m_pModule) ? m_pModule->PutUser(sLine) : false; } bool CSocket::PutStatus(const CString& sLine) { return (m_pModule) ? m_pModule->PutStatus(sLine) : false; } bool CSocket::PutModule(const CString& sLine, const CString& sIdent, const CString& sHost) { return (m_pModule) ? m_pModule->PutModule(sLine, sIdent, sHost) : false; } bool CSocket::PutModNotice(const CString& sLine, const CString& sIdent, const CString& sHost) { return (m_pModule) ? m_pModule->PutModNotice(sLine, sIdent, sHost) : false; } void CSocket::SetModule(CModule* p) { m_pModule = p; } CModule* CSocket::GetModule() const { return m_pModule; } /////////////////// !CSocket /////////////////// #endif // _MODULES <|endoftext|>
<commit_before>#include "log.h" #include "SongDb.h" #include "sqlite3/sqlite3.h" #include "utils.h" #include <cstring> using namespace std; using namespace utils; void IncrementalQuery::addLetter(char c) { query.push_back(c); if(query.size() > 2) { search(); } } void IncrementalQuery::removeLast() { if(!query.empty()) { query.pop_back(); if(query.size() > 2) { search(); } } } void IncrementalQuery::clear() { query.resize(0); } const string IncrementalQuery::getString() { return string(&query[0], query.size()); } const vector<string> &IncrementalQuery::getResult() const { return finalResult; } int IncrementalQuery::numHits() const { return finalResult.size(); } void IncrementalQuery::search() { string q = string(&query[0], query.size()); auto parts = split(q, " "); if(oldParts.size() == 0 || oldParts[0] != parts[0]) { sdb->search(parts[0], firstResult, searchLimit); } oldParts = parts; finalResult.resize(0); for(auto &r : firstResult) { string rc = r; makeLower(rc); bool found = true; for(unsigned int i=1; i<parts.size(); i++) { if(parts[i].size() == 0) continue; if(rc.find(parts[i]) == string::npos) { found = false; break; } } if(found) finalResult.push_back(r); } } SongDatabase::SongDatabase(const string &name) { db = nullptr; int rc = sqlite3_open(name.c_str(), &db); if(rc != SQLITE_OK) { THROW(database_exception, name.c_str()); }; } void SongDatabase::addSubStrings(const char *words, unordered_map<string, std::vector<int>> &stringMap, int index) { //auto parts = ansplit(title) const char *ptr = words; char tl[4]; tl[3] = 0; unsigned int sl = strlen(words); if(sl >= 3) { for(unsigned int i=0; i<sl; i++) { char c = words[i]; const char *pc = &words[i]; if(!isalnum(c)) { ptr = &words[i+1]; continue; } if(pc - ptr == 2) { // TODO: 3 letters could be encoded to one unsigned short //string tl = string(ptr, 3); //makeLower(tl); tl[0] = tolower(ptr[0]); tl[1] = tolower(ptr[1]); tl[2] = tolower(ptr[2]); stringMap[tl].push_back(index); ptr++; } } } } /* Logic read all titles and composers into 2 arrays At the same time create 2 3L-maps referring those arrays */ string IncrementalQuery::getFull(int pos) { string r = finalResult[pos]; auto parts = split(r, "\t"); int id = atoi(parts[2].c_str()); LOGD("ID %d", id); id++; sqlite3_stmt *s; const char *tail; int rc = sqlite3_prepare_v2(db, "SELECT title, composer, path, metadata FROM songs WHERE _id == ?", -1, &s, &tail); LOGD("Result '%d'\n", rc); if(rc != SQLITE_OK) THROW(database_exception, "Select failed"); sqlite3_bind_int(s, 1, id); int ok = sqlite3_step(s); if(ok == SQLITE_ROW) { const char *title = (const char *)sqlite3_column_text(s, 0); const char *composer = (const char *)sqlite3_column_text(s, 1); const char *path = (const char *)sqlite3_column_text(s, 2); const char *metadata = (const char *)sqlite3_column_text(s, 3); return format("%s\t%s\t%s\t%s", title, composer, path, metadata); } else { throw not_found_exception(); } return ""; } void SongDatabase::generateIndex() { sqlite3_stmt *s; const char *tail; char oldComposer[256] = ""; int rc = sqlite3_prepare_v2(db, "SELECT title, composer FROM songs;", -1, &s, &tail); LOGD("Result '%d'\n", rc); if(rc != SQLITE_OK) THROW(database_exception, "Select failed"); int count = 0; //int maxTotal = 3; int cindex = 0; while(count < 100000) { count++; int ok = sqlite3_step(s); if(ok == SQLITE_ROW) { const char *title = (const char *)sqlite3_column_text(s, 0); const char *composer = (const char *)sqlite3_column_text(s, 1); int tindex = titles.size(); if(strcmp(composer, oldComposer) != 0) { composers.push_back(make_pair(composer, tindex)); cindex = composers.size()-1; strcpy(oldComposer, composer); addSubStrings(composer, composerMap, cindex); } titles.push_back(make_pair(title, cindex)); addSubStrings(title, titleMap, tindex); } else if(ok == SQLITE_DONE) { break; } } LOGD("%d titles by %d composer generated %d + %d 3 letter indexes\n", titles.size(), composers.size(), titleMap.size(), composerMap.size()); } void SongDatabase::search(const string &query, vector<string> &result, unsigned int searchLimit) { result.resize(0); if(query.size() < 3) return; string t = string(query, 0, 3); makeLower(t); LOGD("Checking '%s/%s' among %d+%d sub strings", query, t, titleMap.size(), composerMap.size()); const auto &tv = titleMap[t]; const auto &cv = composerMap[t]; LOGD("Searching %d candidates", tv.size()); for(int index : tv) { string title = titles[index].first; makeLower(title); if(title.find(query) != string::npos) { result.push_back(format("%s\t%s\t%d", titles[index].first, composers[titles[index].second].first, index)); //LOGD("%s / %s", titles[index].first, composers[titles[index].second].first); } if(result.size() >= searchLimit) break; } LOGD("Searching %d candidates", cv.size()); for(int index : cv) { string composer = composers[index].first; makeLower(composer); if(composer.find(query) != string::npos) { int title_index = composers[index].second; while(true) { auto title = titles[title_index]; if(title.second != index) break; //LOGD("%s / %s", title.first, composers[index].first); result.push_back(format("%s\t%s\t%d", title.first, composers[index].first, title_index)); title_index++; if(result.size() >= searchLimit) break; } } } } void SongDatabase::search(const char *query) { } <commit_msg>Simplified search<commit_after>#include "log.h" #include "SongDb.h" #include "sqlite3/sqlite3.h" #include "utils.h" #include <cstring> using namespace std; using namespace utils; void IncrementalQuery::addLetter(char c) { query.push_back(c); if(query.size() > 2) { search(); } } void IncrementalQuery::removeLast() { if(!query.empty()) { query.pop_back(); if(query.size() > 2) { search(); } } } void IncrementalQuery::clear() { query.resize(0); } const string IncrementalQuery::getString() { return string(&query[0], query.size()); } const vector<string> &IncrementalQuery::getResult() const { return finalResult; } int IncrementalQuery::numHits() const { return finalResult.size(); } void IncrementalQuery::search() { string q = string(&query[0], query.size()); auto parts = split(q, " "); if(oldParts.size() == 0 || string(oldParts[0], 0, 3) != string(parts[0], 0, 3)) { sdb->search(string(parts[0], 0, 3), firstResult, searchLimit); } oldParts = parts; finalResult.resize(0); for(auto &r : firstResult) { string rc = r; makeLower(rc); bool found = true; for(unsigned int i=1; i<parts.size(); i++) { if(parts[i].size() == 0) continue; if(rc.find(parts[i]) == string::npos) { found = false; break; } } if(found) finalResult.push_back(r); } } SongDatabase::SongDatabase(const string &name) { db = nullptr; int rc = sqlite3_open(name.c_str(), &db); if(rc != SQLITE_OK) { THROW(database_exception, name.c_str()); }; } void SongDatabase::addSubStrings(const char *words, unordered_map<string, std::vector<int>> &stringMap, int index) { //auto parts = ansplit(title) const char *ptr = words; char tl[4]; tl[3] = 0; unsigned int sl = strlen(words); if(sl >= 3) { for(unsigned int i=0; i<sl; i++) { char c = words[i]; const char *pc = &words[i]; if(!isalnum(c)) { ptr = &words[i+1]; continue; } if(pc - ptr == 2) { // TODO: 3 letters could be encoded to one unsigned short //string tl = string(ptr, 3); //makeLower(tl); tl[0] = tolower(ptr[0]); tl[1] = tolower(ptr[1]); tl[2] = tolower(ptr[2]); stringMap[tl].push_back(index); ptr++; } } } } /* Logic read all titles and composers into 2 arrays At the same time create 2 3L-maps referring those arrays */ string IncrementalQuery::getFull(int pos) { string r = finalResult[pos]; auto parts = split(r, "\t"); int id = atoi(parts[2].c_str()); LOGD("ID %d", id); id++; sqlite3_stmt *s; const char *tail; int rc = sqlite3_prepare_v2(db, "SELECT title, composer, path, metadata FROM songs WHERE _id == ?", -1, &s, &tail); LOGD("Result '%d'\n", rc); if(rc != SQLITE_OK) THROW(database_exception, "Select failed"); sqlite3_bind_int(s, 1, id); int ok = sqlite3_step(s); if(ok == SQLITE_ROW) { const char *title = (const char *)sqlite3_column_text(s, 0); const char *composer = (const char *)sqlite3_column_text(s, 1); const char *path = (const char *)sqlite3_column_text(s, 2); const char *metadata = (const char *)sqlite3_column_text(s, 3); return format("%s\t%s\t%s\t%s", title, composer, path, metadata); } else { throw not_found_exception(); } return ""; } void SongDatabase::generateIndex() { sqlite3_stmt *s; const char *tail; char oldComposer[256] = ""; int rc = sqlite3_prepare_v2(db, "SELECT title, composer FROM songs;", -1, &s, &tail); LOGD("Result '%d'\n", rc); if(rc != SQLITE_OK) THROW(database_exception, "Select failed"); int count = 0; //int maxTotal = 3; int cindex = 0; while(count < 100000) { count++; int ok = sqlite3_step(s); if(ok == SQLITE_ROW) { const char *title = (const char *)sqlite3_column_text(s, 0); const char *composer = (const char *)sqlite3_column_text(s, 1); int tindex = titles.size(); if(strcmp(composer, oldComposer) != 0) { composers.push_back(make_pair(composer, tindex)); cindex = composers.size()-1; strcpy(oldComposer, composer); addSubStrings(composer, composerMap, cindex); } titles.push_back(make_pair(title, cindex)); addSubStrings(title, titleMap, tindex); } else if(ok == SQLITE_DONE) { break; } } LOGD("%d titles by %d composer generated %d + %d 3 letter indexes\n", titles.size(), composers.size(), titleMap.size(), composerMap.size()); } void SongDatabase::search(const string &query, vector<string> &result, unsigned int searchLimit) { result.resize(0); //if(query.size() < 3) // return; //string t = string(query, 0, 3); //makeLower(t); LOGD("Checking '%s' among %d+%d sub strings", query, titleMap.size(), composerMap.size()); const auto &tv = titleMap[query]; const auto &cv = composerMap[query]; LOGD("Searching %d candidates", tv.size()); for(int index : tv) { result.push_back(format("%s\t%s\t%d", titles[index].first, composers[titles[index].second].first, index)); if(result.size() >= searchLimit) break; } LOGD("Searching %d candidates", cv.size()); for(int index : cv) { int title_index = composers[index].second; while(true) { auto title = titles[title_index]; if(title.second != index) break; //LOGD("%s / %s", title.first, composers[index].first); result.push_back(format("%s\t%s\t%d", title.first, composers[index].first, title_index)); title_index++; if(result.size() >= searchLimit) break; } } } void SongDatabase::search(const char *query) { } <|endoftext|>
<commit_before>#pragma once #ifndef PI # define PI 3.14159265359f #endif #include "ISystem.hpp" #include "EntityManager.hpp" #pragma warning(disable : 4250) namespace kengine { template<typename CRTP, typename ...DataPackets> class System : public ISystem, public putils::Module<CRTP, DataPackets...> { public: System(EntityManager & em) : Module(&em) { detail::components = &em.__getComponentMap(); } System() = delete; public: pmeta::type_index getType() const noexcept final { static_assert(std::is_base_of<System, CRTP>::value, "System's first template parameter should be inheriting class"); return pmeta::type<CRTP>::index; } }; }<commit_msg>rename PI into KENGINE_PI<commit_after>#pragma once #ifndef KENGINE_PI # define KENGINE_PI 3.14159265359f #endif #include "ISystem.hpp" #include "EntityManager.hpp" #pragma warning(disable : 4250) namespace kengine { template<typename CRTP, typename ...DataPackets> class System : public ISystem, public putils::Module<CRTP, DataPackets...> { public: System(EntityManager & em) : Module(&em) { detail::components = &em.__getComponentMap(); } System() = delete; public: pmeta::type_index getType() const noexcept final { static_assert(std::is_base_of<System, CRTP>::value, "System's first template parameter should be inheriting class"); return pmeta::type<CRTP>::index; } }; }<|endoftext|>
<commit_before>// SA:MP Profiler plugin // // Copyright (c) 2011 Zeex // // 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 <fstream> #include <iomanip> #include <iostream> #include <string> #include "printers.h" #include "profile.h" namespace samp_profiler { LogPrinter::LogPrinter(const std::string script_name) : script_name_(script_name) { } void LogPrinter::Print(const std::vector<Profile> &profiles) { } HtmlPrinter::HtmlPrinter(const std::string &out_file, const std::string &title) : out_file_(out_file) , title_(title) { } void HtmlPrinter::Print(const std::vector<Profile> &profiles) { std::ofstream stream(out_file_.c_str()); if (!stream.is_open()) return; stream << "<html>\n\n" "<head>\n" ; if (!title_.empty()) { stream << " <title>" << title_ << "</title>\n" ; } stream << " <script type=\"text/javascript\"\n" " src=\"http://code.jquery.com/jquery-latest.min.js\"></script>\n" " <script type=\"text/javascript\"\n" " src=\"http://autobahn.tablesorter.com/jquery.tablesorter.min.js\"></script>\n" " <script type=\"text/javascript\">\n" " $(document).ready(function() {\n" " $(\"#stats\").tablesorter();\n" " });\n" " </script>\n" "</head>\n\n" ; stream << "<body>" " <h1>" << title_ << "</h1>\n" " <table id=\"stats\" class=\"tablesorter\" border=\"1\" width=\"100%\">\n" " <thead>\n" " <tr>\n" " <th>Function Type</th>\n" " <th>Function Name</th>\n" " <th>Calls</th>\n" " <th>Time per call, &#181;s</th>\n" " <th>Overall time, &#181;s</th>\n" " <th>Overall time, &#037;</th>\n" " </tr>\n" " </thead>\n" " <tbody>\n" ; int64_t total_time = 0; for (std::vector<Profile>::const_iterator it = profiles.begin(); it != profiles.end(); ++it) { total_time += it->GetCounter().GetTotalTime(); } for (std::vector<Profile>::const_iterator it = profiles.begin(); it != profiles.end(); ++it) { const PerformanceCounter &counter = it->GetCounter(); stream << " <tr>\n" << " <td>" << it->GetFunctionType() << "</td>\n" << " <td>" << it->GetFunctionName() << "</td>\n" << " <td>" << counter.GetNumberOfCalls() << "</td>\n" << " <td>" << counter.GetTotalTime() / counter.GetNumberOfCalls() << "</td>\n" << " <td>" << counter.GetTotalTime() << "</td>\n" << " <td>" << std::fixed << std::setprecision(2) << static_cast<double>(counter.GetTotalTime() * 100) / total_time << "</td>\n" << " </tr>\n"; } stream << " </tbody>\n" " </table>\n\n" ; stream << "</body>\n" "</html>\n" ; } } // namespace samp_profiler<commit_msg>HtmlPrinter: Move JS code from head for body<commit_after>// SA:MP Profiler plugin // // Copyright (c) 2011 Zeex // // 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 <fstream> #include <iomanip> #include <iostream> #include <string> #include "printers.h" #include "profile.h" namespace samp_profiler { LogPrinter::LogPrinter(const std::string script_name) : script_name_(script_name) { } void LogPrinter::Print(const std::vector<Profile> &profiles) { } HtmlPrinter::HtmlPrinter(const std::string &out_file, const std::string &title) : out_file_(out_file) , title_(title) { } void HtmlPrinter::Print(const std::vector<Profile> &profiles) { std::ofstream stream(out_file_.c_str()); if (!stream.is_open()) return; stream << "<html>\n" "<head>\n" ; if (!title_.empty()) { stream << " <title>" << title_ << "</title>\n" ; } stream << "</head>\n\n" "<body>" ; if (!title_.empty()) { stream << " <h1>" << title_ << "</h1>\n" ; } stream << " <table id=\"stats\" class=\"tablesorter\" border=\"1\" width=\"100%\">\n" " <thead>\n" " <tr>\n" " <th>Function Type</th>\n" " <th>Function Name</th>\n" " <th>Calls</th>\n" " <th>Time per call, &#181;s</th>\n" " <th>Overall time, &#181;s</th>\n" " <th>Overall time, &#037;</th>\n" " </tr>\n" " </thead>\n" " <tbody>\n" ; int64_t total_time = 0; for (std::vector<Profile>::const_iterator it = profiles.begin(); it != profiles.end(); ++it) { total_time += it->GetCounter().GetTotalTime(); } for (std::vector<Profile>::const_iterator it = profiles.begin(); it != profiles.end(); ++it) { const PerformanceCounter &counter = it->GetCounter(); stream << " <tr>\n" << " <td>" << it->GetFunctionType() << "</td>\n" << " <td>" << it->GetFunctionName() << "</td>\n" << " <td>" << counter.GetNumberOfCalls() << "</td>\n" << " <td>" << counter.GetTotalTime() / counter.GetNumberOfCalls() << "</td>\n" << " <td>" << counter.GetTotalTime() << "</td>\n" << " <td>" << std::fixed << std::setprecision(2) << static_cast<double>(counter.GetTotalTime() * 100) / total_time << "</td>\n" << " </tr>\n"; } stream << " </tbody>\n" " </table>\n" ; stream << " <script type=\"text/javascript\"\n" " src=\"http://code.jquery.com/jquery-latest.min.js\"></script>\n" " <script type=\"text/javascript\"\n" " src=\"http://autobahn.tablesorter.com/jquery.tablesorter.min.js\"></script>\n" " <script type=\"text/javascript\">\n" " $(document).ready(function() {\n" " $(\"#stats\").tablesorter();\n" " });\n" " </script>\n" "</body>\n" "</html>\n" ; } } // namespace samp_profiler <|endoftext|>
<commit_before>// SA:MP Profiler plugin // // Copyright (c) 2011 Zeex // // 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 <algorithm> #include <cstdio> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <list> #include <numeric> #include <string> #include <vector> #include "amxnamefinder.h" #include "jump.h" #include "plugincommon.h" #include "profiler.h" std::map<AMX*, AmxProfiler*> AmxProfiler::instances_; AmxProfiler::AmxProfiler() {} static void GetNatives(AMX *amx, std::vector<std::string> &names) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); AMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->natives); int numNatives = (hdr->libraries - hdr->natives) / hdr->defsize; for (int i = 0; i < numNatives; i++) { names.push_back(reinterpret_cast<char*>(amx->base + natives[i].nameofs)); } } AmxProfiler::AmxProfiler(AMX *amx, AMX_DBG amxdbg) : amx_(amx), amxdbg_(amxdbg), debug_(amx->debug), callback_(amx->callback), active_(false), frame_(amx->stp) { // Since PrintStats is done in AmxUnload and amx->base is already freed before // AmxUnload gets called, the native table is not accessible there, thus natives' // names must be stored manually in another global place. GetNatives(amx, nativeNames_); } void AmxProfiler::Attach(AMX *amx, AMX_DBG amxdbg) { AmxProfiler *prof = new AmxProfiler(amx, amxdbg); instances_[amx] = prof; prof->Activate(); } void AmxProfiler::Detach(AMX *amx) { AmxProfiler *prof = AmxProfiler::Get(amx); if (prof != 0) { prof->Deactivate(); delete prof; } instances_.erase(amx); } AmxProfiler *AmxProfiler::Get(AMX *amx) { std::map<AMX*, AmxProfiler*>::iterator it = instances_.find(amx); if (it != instances_.end()) { return it->second; } return 0; } static int AMXAPI Debug(AMX *amx) { return AmxProfiler::Get(amx)->Debug(); } static int AMXAPI Callback(AMX *amx, cell index, cell *result, cell *params) { return AmxProfiler::Get(amx)->Callback(index, result, params); } void AmxProfiler::Activate() { if (!active_) { active_ = true; amx_SetDebugHook(amx_, ::Debug); amx_SetCallback(amx_, ::Callback); } } bool AmxProfiler::IsActive() const { return active_; } void AmxProfiler::Deactivate() { if (active_) { active_ = false; amx_SetDebugHook(amx_, debug_); amx_SetCallback(amx_, callback_); } } void AmxProfiler::ResetStats() { counters_.clear(); } static bool ByCalls(const std::pair<cell, AmxPerformanceCounter> &op1, const std::pair<cell, AmxPerformanceCounter> &op2) { return op1.second.GetCalls() > op2.second.GetCalls(); } static bool ByTime(const std::pair<cell, AmxPerformanceCounter> &op1, const std::pair<cell, AmxPerformanceCounter> &op2) { return op1.second.GetTime() > op2.second.GetTime(); } static bool ByTimePerCall(const std::pair<cell, AmxPerformanceCounter> &op1, const std::pair<cell, AmxPerformanceCounter> &op2) { return static_cast<double>(op1.second.GetTime()) / static_cast<double>(op1.second.GetCalls()) > static_cast<double>(op2.second.GetTime()) / static_cast<double>(op2.second.GetCalls()); } bool AmxProfiler::PrintStats(const std::string &filename, StatsPrintOrder order) { std::ofstream stream(filename.c_str()); if (stream.is_open()) { std::vector<std::pair<cell, AmxPerformanceCounter> > stats(counters_.begin(), counters_.end()); switch (order) { case ORDER_BY_CALLS: std::sort(stats.begin(), stats.end(), ByCalls); break; case ORDER_BY_TIME: std::sort(stats.begin(), stats.end(), ByTime); break; case ORDER_BY_TIME_PER_CALL: std::sort(stats.begin(), stats.end(), ByTimePerCall); break; default: // leave as is break; } stream << "<table>\n" << "\t<tr>\n" << "\t\t<td>Function</td>\n" << "\t\t<td>Calls</td>\n" << "\t\t<td>Time per call, &#181;s</td>\n" << "\t\t<td>Overall time, &#181;s</td>\n" << "\t\t<td>Overall time, &#037;</td>\n" << "\t</tr>\n"; platformstl::int64_t totalTime = 0; for (std::vector<std::pair<cell, AmxPerformanceCounter> >::iterator it = stats.begin(); it != stats.end(); ++it) { totalTime += it->second.GetTime(); } for (std::vector<std::pair<cell, AmxPerformanceCounter> >::iterator it = stats.begin(); it != stats.end(); ++it) { stream << "\t<tr>\n"; if (it->first <= 0) { stream << "\t\t<td>" << nativeNames_[-it->first] << "</td>\n"; } else { const char *name; if (dbg_LookupFunction(&amxdbg_, it->first, &name) == AMX_ERR_NONE) { //stream << "\t\t<td>" << name << "@" << std::hex << it->first << std::dec << "</td>\n"; stream << "\t\t<td>" << name << "</td>\n"; } else { stream << "\t\t<td>" << std::hex << it->first << std::dec << "</td>\n"; } } stream << "\t\t<td>" << it->second.GetCalls() << "</td>\n" << "\t\t<td>" << std::fixed << std::setprecision(0) << static_cast<double>(it->second.GetTime()) / static_cast<double>(it->second.GetCalls()) << "</td>\n" << "\t\t<td>" << it->second.GetTime() << "</td>\n" << "\t\t<td>" << std::setprecision(2) << static_cast<double>(it->second.GetTime() * 100) / static_cast<double>(totalTime) << "</td>\n"; stream << "\t</tr>\n"; } stream << "</table>\n"; return true; } return false; } int AmxProfiler::Debug() { if (amx_->frm != frame_ && frame_ > amx_->hea) { if (amx_->frm < frame_) { // Probably entered a function body (first BREAK after PROC) cell address = amx_->cip - 2*sizeof(cell); // Check if we have a PROC opcode behind us AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx_->base); cell op = *reinterpret_cast<cell*>(hdr->cod + amx_->base + address); if (op == 46) { callStack_.push(address); if (active_) { counters_[address].Start(); } } } else { // Left a function cell address = callStack_.top(); if (active_) { counters_[address].Stop(); } callStack_.pop(); if (callStack_.empty()) { frame_ = amx_->stp; } } frame_ = amx_->frm; } if (debug_ != 0) { // Others could set their own debug hooks return debug_(amx_); } return AMX_ERR_NONE; } int AmxProfiler::Callback(cell index, cell *result, cell *params) { // The default AMX callback (amx_Callback) can replace SYSREQ.C opcodes // with SYSREQ.D for better performance. amx_->sysreq_d = 0; if (active_) { counters_[-index].Start();; // Notice negative index } // Call any previously set AMX callback (must not be null so we don't check) int error = callback_(amx_, index, result, params); if (active_) { counters_[-index].Stop(); } return error; } static uint32_t amx_Exec_addr; static unsigned char amx_Exec_code[5]; static int AMXAPI Exec(AMX *amx, cell *retval, int index) { memcpy(reinterpret_cast<void*>(::amx_Exec_addr), ::amx_Exec_code, 5); int error; // Check if this script has a profiler attached to it AmxProfiler *prof = AmxProfiler::Get(amx); if (prof != 0 && prof->IsActive()) { error = prof->Exec(retval, index); } else { error = amx_Exec(amx, retval, index); } SetJump(reinterpret_cast<void*>(::amx_Exec_addr), (void*)::Exec, ::amx_Exec_code); return error; } int AmxProfiler::Exec(cell *retval, int index) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx_->base); AMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx_->base + hdr->publics); cell address = publics[index].address; callStack_.push(address); // Set frame_ to the value which amx_->frm will be set to // during amx_Exec. If we do this Debug() will think that // the frame stays the same and won't profile this call. frame_ = amx_->stk - 3*sizeof(cell); counters_[address].Start(); int error = amx_Exec(amx_, retval, index); counters_[address].Stop(); if (!callStack_.empty()) { callStack_.pop(); } else { frame_ = amx_->stp; } return error; } PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } extern void *pAMXFunctions; // Both x86 and x86-64 are Little Endian... static void *AMXAPI DummyAmxAlign(void *v) { return v; } static std::list<std::string> profiledScripts; PLUGIN_EXPORT bool PLUGIN_CALL Load(void **pluginData) { pAMXFunctions = pluginData[PLUGIN_DATA_AMX_EXPORTS]; // The server does not export amx_Align16 and amx_Align32 for some reason ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)DummyAmxAlign; ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)DummyAmxAlign; // Hook amx_Exec ::amx_Exec_addr = reinterpret_cast<uint32_t>((static_cast<void**>(pAMXFunctions))[PLUGIN_AMX_EXPORT_Exec]); SetJump(reinterpret_cast<void*>(::amx_Exec_addr), (void*)::Exec, ::amx_Exec_code); // Get the names of scripts to be profiled std::copy(std::istream_iterator<std::string>(std::ifstream("plugins/profiler.cfg")), std::istream_iterator<std::string>(), std::back_inserter(::profiledScripts)); // Add SA:MP default directories to the .amx finder sarch path AmxNameFinder *nameFinder = AmxNameFinder::GetInstance(); nameFinder->AddSearchDir("gamemodes"); nameFinder->AddSearchDir("filterscripts"); nameFinder->UpdateCache(); return true; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { return; } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { AmxNameFinder *nameFinder = AmxNameFinder::GetInstance(); nameFinder->UpdateCache(); // If the name is established, load symbolic info std::string filename = nameFinder->GetAmxName(amx); if (!filename.empty()) { std::replace(filename.begin(), filename.end(), '\\', '/'); if (std::find(::profiledScripts.begin(), ::profiledScripts.end(), filename) != ::profiledScripts.end()) { FILE *fp = fopen(filename.c_str(), "rb"); if (fp != 0) { AMX_DBG amxdbg; int error = dbg_LoadInfo(&amxdbg, fp); if (error == AMX_ERR_NONE) { AmxProfiler::Attach(amx, amxdbg); } else { // An error occured, no profiler attached return error; } fclose(fp); } } } return AMX_ERR_NONE; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { // Get an instance of AmxProfiler attached to the unloading AMX AmxProfiler *prof = AmxProfiler::Get(amx); // Detach profiler if (prof != 0) { // Before doing that, print stats to <amx_file_path>.prof std::string name = AmxNameFinder::GetInstance()->GetAmxName(amx); if (!name.empty()) { prof->PrintStats(name + std::string(".prof")); } AmxProfiler::Detach(amx); } return AMX_ERR_NONE; } <commit_msg>Fix missing #include <cstring> and <iterator><commit_after>// SA:MP Profiler plugin // // Copyright (c) 2011 Zeex // // 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 <algorithm> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iomanip> #include <iostream> #include <iterator> #include <list> #include <numeric> #include <string> #include <vector> #include "amxnamefinder.h" #include "jump.h" #include "plugincommon.h" #include "profiler.h" std::map<AMX*, AmxProfiler*> AmxProfiler::instances_; AmxProfiler::AmxProfiler() {} static void GetNatives(AMX *amx, std::vector<std::string> &names) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); AMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->natives); int numNatives = (hdr->libraries - hdr->natives) / hdr->defsize; for (int i = 0; i < numNatives; i++) { names.push_back(reinterpret_cast<char*>(amx->base + natives[i].nameofs)); } } AmxProfiler::AmxProfiler(AMX *amx, AMX_DBG amxdbg) : amx_(amx), amxdbg_(amxdbg), debug_(amx->debug), callback_(amx->callback), active_(false), frame_(amx->stp) { // Since PrintStats is done in AmxUnload and amx->base is already freed before // AmxUnload gets called, the native table is not accessible there, thus natives' // names must be stored manually in another global place. GetNatives(amx, nativeNames_); } void AmxProfiler::Attach(AMX *amx, AMX_DBG amxdbg) { AmxProfiler *prof = new AmxProfiler(amx, amxdbg); instances_[amx] = prof; prof->Activate(); } void AmxProfiler::Detach(AMX *amx) { AmxProfiler *prof = AmxProfiler::Get(amx); if (prof != 0) { prof->Deactivate(); delete prof; } instances_.erase(amx); } AmxProfiler *AmxProfiler::Get(AMX *amx) { std::map<AMX*, AmxProfiler*>::iterator it = instances_.find(amx); if (it != instances_.end()) { return it->second; } return 0; } static int AMXAPI Debug(AMX *amx) { return AmxProfiler::Get(amx)->Debug(); } static int AMXAPI Callback(AMX *amx, cell index, cell *result, cell *params) { return AmxProfiler::Get(amx)->Callback(index, result, params); } void AmxProfiler::Activate() { if (!active_) { active_ = true; amx_SetDebugHook(amx_, ::Debug); amx_SetCallback(amx_, ::Callback); } } bool AmxProfiler::IsActive() const { return active_; } void AmxProfiler::Deactivate() { if (active_) { active_ = false; amx_SetDebugHook(amx_, debug_); amx_SetCallback(amx_, callback_); } } void AmxProfiler::ResetStats() { counters_.clear(); } static bool ByCalls(const std::pair<cell, AmxPerformanceCounter> &op1, const std::pair<cell, AmxPerformanceCounter> &op2) { return op1.second.GetCalls() > op2.second.GetCalls(); } static bool ByTime(const std::pair<cell, AmxPerformanceCounter> &op1, const std::pair<cell, AmxPerformanceCounter> &op2) { return op1.second.GetTime() > op2.second.GetTime(); } static bool ByTimePerCall(const std::pair<cell, AmxPerformanceCounter> &op1, const std::pair<cell, AmxPerformanceCounter> &op2) { return static_cast<double>(op1.second.GetTime()) / static_cast<double>(op1.second.GetCalls()) > static_cast<double>(op2.second.GetTime()) / static_cast<double>(op2.second.GetCalls()); } bool AmxProfiler::PrintStats(const std::string &filename, StatsPrintOrder order) { std::ofstream stream(filename.c_str()); if (stream.is_open()) { std::vector<std::pair<cell, AmxPerformanceCounter> > stats(counters_.begin(), counters_.end()); switch (order) { case ORDER_BY_CALLS: std::sort(stats.begin(), stats.end(), ByCalls); break; case ORDER_BY_TIME: std::sort(stats.begin(), stats.end(), ByTime); break; case ORDER_BY_TIME_PER_CALL: std::sort(stats.begin(), stats.end(), ByTimePerCall); break; default: // leave as is break; } stream << "<table>\n" << "\t<tr>\n" << "\t\t<td>Function</td>\n" << "\t\t<td>Calls</td>\n" << "\t\t<td>Time per call, &#181;s</td>\n" << "\t\t<td>Overall time, &#181;s</td>\n" << "\t\t<td>Overall time, &#037;</td>\n" << "\t</tr>\n"; platformstl::int64_t totalTime = 0; for (std::vector<std::pair<cell, AmxPerformanceCounter> >::iterator it = stats.begin(); it != stats.end(); ++it) { totalTime += it->second.GetTime(); } for (std::vector<std::pair<cell, AmxPerformanceCounter> >::iterator it = stats.begin(); it != stats.end(); ++it) { stream << "\t<tr>\n"; if (it->first <= 0) { stream << "\t\t<td>" << nativeNames_[-it->first] << "</td>\n"; } else { const char *name; if (dbg_LookupFunction(&amxdbg_, it->first, &name) == AMX_ERR_NONE) { //stream << "\t\t<td>" << name << "@" << std::hex << it->first << std::dec << "</td>\n"; stream << "\t\t<td>" << name << "</td>\n"; } else { stream << "\t\t<td>" << std::hex << it->first << std::dec << "</td>\n"; } } stream << "\t\t<td>" << it->second.GetCalls() << "</td>\n" << "\t\t<td>" << std::fixed << std::setprecision(0) << static_cast<double>(it->second.GetTime()) / static_cast<double>(it->second.GetCalls()) << "</td>\n" << "\t\t<td>" << it->second.GetTime() << "</td>\n" << "\t\t<td>" << std::setprecision(2) << static_cast<double>(it->second.GetTime() * 100) / static_cast<double>(totalTime) << "</td>\n"; stream << "\t</tr>\n"; } stream << "</table>\n"; return true; } return false; } int AmxProfiler::Debug() { if (amx_->frm != frame_ && frame_ > amx_->hea) { if (amx_->frm < frame_) { // Probably entered a function body (first BREAK after PROC) cell address = amx_->cip - 2*sizeof(cell); // Check if we have a PROC opcode behind us AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx_->base); cell op = *reinterpret_cast<cell*>(hdr->cod + amx_->base + address); if (op == 46) { callStack_.push(address); if (active_) { counters_[address].Start(); } } } else { // Left a function cell address = callStack_.top(); if (active_) { counters_[address].Stop(); } callStack_.pop(); if (callStack_.empty()) { frame_ = amx_->stp; } } frame_ = amx_->frm; } if (debug_ != 0) { // Others could set their own debug hooks return debug_(amx_); } return AMX_ERR_NONE; } int AmxProfiler::Callback(cell index, cell *result, cell *params) { // The default AMX callback (amx_Callback) can replace SYSREQ.C opcodes // with SYSREQ.D for better performance. amx_->sysreq_d = 0; if (active_) { counters_[-index].Start();; // Notice negative index } // Call any previously set AMX callback (must not be null so we don't check) int error = callback_(amx_, index, result, params); if (active_) { counters_[-index].Stop(); } return error; } static uint32_t amx_Exec_addr; static unsigned char amx_Exec_code[5]; static int AMXAPI Exec(AMX *amx, cell *retval, int index) { memcpy(reinterpret_cast<void*>(::amx_Exec_addr), ::amx_Exec_code, 5); int error; // Check if this script has a profiler attached to it AmxProfiler *prof = AmxProfiler::Get(amx); if (prof != 0 && prof->IsActive()) { error = prof->Exec(retval, index); } else { error = amx_Exec(amx, retval, index); } SetJump(reinterpret_cast<void*>(::amx_Exec_addr), (void*)::Exec, ::amx_Exec_code); return error; } int AmxProfiler::Exec(cell *retval, int index) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx_->base); AMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx_->base + hdr->publics); cell address = publics[index].address; callStack_.push(address); // Set frame_ to the value which amx_->frm will be set to // during amx_Exec. If we do this Debug() will think that // the frame stays the same and won't profile this call. frame_ = amx_->stk - 3*sizeof(cell); counters_[address].Start(); int error = amx_Exec(amx_, retval, index); counters_[address].Stop(); if (!callStack_.empty()) { callStack_.pop(); } else { frame_ = amx_->stp; } return error; } PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } extern void *pAMXFunctions; // Both x86 and x86-64 are Little Endian... static void *AMXAPI DummyAmxAlign(void *v) { return v; } static std::list<std::string> profiledScripts; PLUGIN_EXPORT bool PLUGIN_CALL Load(void **pluginData) { pAMXFunctions = pluginData[PLUGIN_DATA_AMX_EXPORTS]; // The server does not export amx_Align16 and amx_Align32 for some reason ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)DummyAmxAlign; ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)DummyAmxAlign; // Hook amx_Exec ::amx_Exec_addr = reinterpret_cast<uint32_t>((static_cast<void**>(pAMXFunctions))[PLUGIN_AMX_EXPORT_Exec]); SetJump(reinterpret_cast<void*>(::amx_Exec_addr), (void*)::Exec, ::amx_Exec_code); // Get the names of scripts to be profiled std::copy(std::istream_iterator<std::string>(std::ifstream("plugins/profiler.cfg")), std::istream_iterator<std::string>(), std::back_inserter(::profiledScripts)); // Add SA:MP default directories to the .amx finder sarch path AmxNameFinder *nameFinder = AmxNameFinder::GetInstance(); nameFinder->AddSearchDir("gamemodes"); nameFinder->AddSearchDir("filterscripts"); nameFinder->UpdateCache(); return true; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { return; } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { AmxNameFinder *nameFinder = AmxNameFinder::GetInstance(); nameFinder->UpdateCache(); // If the name is established, load symbolic info std::string filename = nameFinder->GetAmxName(amx); if (!filename.empty()) { std::replace(filename.begin(), filename.end(), '\\', '/'); if (std::find(::profiledScripts.begin(), ::profiledScripts.end(), filename) != ::profiledScripts.end()) { FILE *fp = fopen(filename.c_str(), "rb"); if (fp != 0) { AMX_DBG amxdbg; int error = dbg_LoadInfo(&amxdbg, fp); if (error == AMX_ERR_NONE) { AmxProfiler::Attach(amx, amxdbg); } else { // An error occured, no profiler attached return error; } fclose(fp); } } } return AMX_ERR_NONE; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { // Get an instance of AmxProfiler attached to the unloading AMX AmxProfiler *prof = AmxProfiler::Get(amx); // Detach profiler if (prof != 0) { // Before doing that, print stats to <amx_file_path>.prof std::string name = AmxNameFinder::GetInstance()->GetAmxName(amx); if (!name.empty()) { prof->PrintStats(name + std::string(".prof")); } AmxProfiler::Detach(amx); } return AMX_ERR_NONE; } <|endoftext|>
<commit_before>#include "code_it_pr2/robot_api.h" #include <string> #include <vector> #include "boost/shared_ptr.hpp" #include "code_it_msgs/ArmId.h" #include "code_it_msgs/AskMultipleChoice.h" #include "code_it_msgs/DisplayMessage.h" #include "code_it_msgs/GripperId.h" #include "code_it_msgs/LookAt.h" #include "code_it_msgs/Pick.h" #include "code_it_msgs/Place.h" #include "code_it_msgs/Say.h" #include "code_it_msgs/SetGripper.h" #include "code_it_msgs/TuckArms.h" #include "geometry_msgs/PoseStamped.h" #include "geometry_msgs/Vector3.h" #include "rapid_perception/pr2.h" #include "rapid_perception/rgbd.hpp" #include "rapid_perception/scene.h" #include "rapid_pr2/pr2.h" #include "ros/ros.h" #include "sensor_msgs/PointCloud2.h" #include "std_msgs/Bool.h" #include "std_msgs/String.h" #include "tf/transform_listener.h" namespace rpe = rapid::perception; using boost::shared_ptr; using std::string; namespace code_it_pr2 { RobotApi::RobotApi(rapid::pr2::Pr2* robot, const ros::Publisher& error_pub) : robot_(robot), error_pub_(error_pub), tf_listener_(), scene_(), scene_has_parsed_(false) {} bool RobotApi::AskMultipleChoice(code_it_msgs::AskMultipleChoiceRequest& req, code_it_msgs::AskMultipleChoiceResponse& res) { string choice; bool success = robot_->display()->AskMultipleChoice(req.question, req.choices, &choice); res.choice = choice; if (!success) { PublishError(errors::ASK_MC_QUESTION); } return success; } bool RobotApi::DisplayMessage(code_it_msgs::DisplayMessageRequest& req, code_it_msgs::DisplayMessageResponse& res) { return robot_->display()->ShowMessage(req.h1_text, req.h2_text); } bool RobotApi::FindObjects(code_it_msgs::FindObjectsRequest& req, code_it_msgs::FindObjectsResponse& res) { bool success = rpe::pr2::GetManipulationScene(tf_listener_, &scene_); if (!success) { PublishError(errors::GET_SCENE); return false; } scene_has_parsed_ = true; boost::shared_ptr<rpe::Tabletop> tt = scene_.GetPrimarySurface(); const std::vector<rpe::Object>* objects = tt->objects(); for (size_t i = 0; i < objects->size(); ++i) { const rpe::Object& obj = (*objects)[i]; code_it_msgs::Object msg; msg.name = obj.name(); msg.pose = obj.pose(); msg.scale = obj.scale(); res.objects.push_back(msg); } return true; } bool RobotApi::LookAt(code_it_msgs::LookAtRequest& req, code_it_msgs::LookAtResponse& res) { return robot_->head()->LookAt(req.target); } bool RobotApi::Pick(code_it_msgs::PickRequest& req, code_it_msgs::PickResponse& res) { if (!scene_has_parsed_) { PublishError(errors::PICK_SCENE_NOT_PARSED); return false; } bool has_left_object = robot_->left_gripper()->is_holding_object(); bool has_right_object = robot_->right_gripper()->is_holding_object(); // Check if both hands are full if (has_left_object && has_right_object) { PublishError(errors::PICK_ARMS_FULL); return false; } // If using the default arm, use whichever arm is free, or the right arm if // both arms are free. int8_t arm_id = req.arm.arm_id; if (arm_id == code_it_msgs::ArmId::DEFAULT) { if (has_left_object && !has_right_object) { arm_id = code_it_msgs::ArmId::RIGHT; } else if (!has_left_object && has_right_object) { arm_id = code_it_msgs::ArmId::LEFT; } else { arm_id = code_it_msgs::ArmId::RIGHT; } } geometry_msgs::PoseStamped ps = req.object.pose; geometry_msgs::Vector3 scale = req.object.scale; rapid::perception::ScenePrimitive primitive(ps, scale, "object"); rapid::perception::Object object; if (!scene_.GetObject(req.object.name, &object)) { PublishError(errors::PICK_OBJECT_NOT_FOUND); return false; } bool success = false; if (arm_id == code_it_msgs::ArmId::LEFT) { if (has_left_object) { PublishError(errors::PICK_LEFT_FULL); return false; } success = robot_->left_picker()->Pick(object); if (success) { robot_->left_gripper()->set_held_object(primitive); } } else { if (has_right_object) { PublishError(errors::PICK_RIGHT_FULL); return false; } success = robot_->right_picker()->Pick(object); if (success) { robot_->right_gripper()->set_held_object(primitive); } } if (!success) { PublishError(errors::PICK_OBJECT); return false; } return true; } bool RobotApi::Place(code_it_msgs::PlaceRequest& req, code_it_msgs::PlaceResponse& res) { bool has_left_object = robot_->left_gripper()->is_holding_object(); bool has_right_object = robot_->right_gripper()->is_holding_object(); // Check if both hands are empty if (!has_left_object && !has_right_object) { PublishError(errors::PLACE_NO_OBJECTS); return false; } // If using default arm, default to whichever arm has an object, or the right // arm if both arms have objects. int8_t arm_id = req.arm.arm_id; if (arm_id == code_it_msgs::ArmId::DEFAULT) { if (has_left_object && !has_right_object) { arm_id = code_it_msgs::ArmId::LEFT; } else { arm_id = code_it_msgs::ArmId::RIGHT; } } if (arm_id == code_it_msgs::ArmId::LEFT && !has_left_object) { PublishError(errors::PLACE_NO_LEFT_OBJECT); return false; } if (arm_id == code_it_msgs::ArmId::RIGHT && !has_right_object) { PublishError(errors::PLACE_NO_RIGHT_OBJECT); return false; } // Get the tabletop. rpe::Scene scene; bool success = rpe::pr2::GetManipulationScene(tf_listener_, &scene); if (!success) { PublishError(errors::GET_SCENE); return false; } boost::shared_ptr<rpe::Tabletop> tt = scene.GetPrimarySurface(); if (arm_id == code_it_msgs::ArmId::LEFT) { rpe::ScenePrimitive obj; robot_->left_gripper()->HeldObject(&obj); success = robot_->left_placer()->Place(obj, *tt); if (success) { robot_->left_gripper()->set_is_holding_object(false); } } else { rpe::ScenePrimitive obj; robot_->right_gripper()->HeldObject(&obj); success = robot_->right_placer()->Place(obj, *tt); if (success) { robot_->right_gripper()->set_is_holding_object(false); } } if (!success) { PublishError(errors::PLACE_OBJECT); return false; } return true; } bool RobotApi::Say(code_it_msgs::SayRequest& req, code_it_msgs::SayResponse& res) { robot_->sound()->Say(req.text); return true; } bool RobotApi::SetGripper(code_it_msgs::SetGripperRequest& req, code_it_msgs::SetGripperResponse& res) { if (req.gripper.id == code_it_msgs::GripperId::LEFT) { if (req.action == code_it_msgs::SetGripperRequest::OPEN) { robot_->left_gripper()->Open(req.max_effort); } else if (req.action == code_it_msgs::SetGripperRequest::CLOSE) { robot_->left_gripper()->Close(req.max_effort); } } else { if (req.action == code_it_msgs::SetGripperRequest::OPEN) { robot_->right_gripper()->Open(req.max_effort); } else if (req.action == code_it_msgs::SetGripperRequest::CLOSE) { robot_->right_gripper()->Close(req.max_effort); } } return true; } bool RobotApi::TuckArms(code_it_msgs::TuckArmsRequest& req, code_it_msgs::TuckArmsResponse& res) { bool success = false; if (req.tuck_left && req.tuck_right) { success = robot_->tuck_arms()->TuckArms(); } else if (req.tuck_left && !req.tuck_right) { success = robot_->tuck_arms()->DeployRight(); } else if (!req.tuck_left && req.tuck_right) { success = robot_->tuck_arms()->DeployLeft(); } else { success = robot_->tuck_arms()->DeployArms(); } if (!success) { PublishError(errors::TUCK_DEPLOY); return false; } return true; } void RobotApi::HandleProgramStopped(const std_msgs::Bool& msg) { if (msg.data) { return; // Program is running, nothing to do. } bool success = robot_->display()->ShowDefault(); if (!success) { PublishError(errors::RESET_SCREEN_ON_STOP); } } void RobotApi::PublishError(const string& error) { std_msgs::String error_msg; error_msg.data = error; error_pub_.publish(error_msg); ROS_ERROR("%s", error.c_str()); } } // namespace code_it_pr2 <commit_msg>Updated to work with rapid_perception refactoring.<commit_after>#include "code_it_pr2/robot_api.h" #include <string> #include <vector> #include "boost/shared_ptr.hpp" #include "code_it_msgs/ArmId.h" #include "code_it_msgs/AskMultipleChoice.h" #include "code_it_msgs/DisplayMessage.h" #include "code_it_msgs/GripperId.h" #include "code_it_msgs/LookAt.h" #include "code_it_msgs/Pick.h" #include "code_it_msgs/Place.h" #include "code_it_msgs/Say.h" #include "code_it_msgs/SetGripper.h" #include "code_it_msgs/TuckArms.h" #include "geometry_msgs/PoseStamped.h" #include "geometry_msgs/Vector3.h" #include "rapid_perception/pr2.h" #include "rapid_perception/rgbd.hpp" #include "rapid_perception/scene.h" #include "rapid_pr2/pr2.h" #include "ros/ros.h" #include "sensor_msgs/PointCloud2.h" #include "std_msgs/Bool.h" #include "std_msgs/String.h" #include "tf/transform_listener.h" namespace rpe = rapid::perception; using boost::shared_ptr; using std::string; namespace code_it_pr2 { RobotApi::RobotApi(rapid::pr2::Pr2* robot, const ros::Publisher& error_pub) : robot_(robot), error_pub_(error_pub), tf_listener_(), scene_(), scene_has_parsed_(false) {} bool RobotApi::AskMultipleChoice(code_it_msgs::AskMultipleChoiceRequest& req, code_it_msgs::AskMultipleChoiceResponse& res) { string choice; bool success = robot_->display()->AskMultipleChoice(req.question, req.choices, &choice); res.choice = choice; if (!success) { PublishError(errors::ASK_MC_QUESTION); } return success; } bool RobotApi::DisplayMessage(code_it_msgs::DisplayMessageRequest& req, code_it_msgs::DisplayMessageResponse& res) { return robot_->display()->ShowMessage(req.h1_text, req.h2_text); } bool RobotApi::FindObjects(code_it_msgs::FindObjectsRequest& req, code_it_msgs::FindObjectsResponse& res) { bool success = rpe::pr2::GetManipulationScene(tf_listener_, &scene_); if (!success) { PublishError(errors::GET_SCENE); return false; } scene_has_parsed_ = true; rpe::HSurface tt = scene_.primary_surface(); const std::vector<rpe::Object>& objects = tt.objects(); for (size_t i = 0; i < objects.size(); ++i) { const rpe::Object& obj = objects[i]; code_it_msgs::Object msg; msg.name = obj.name(); msg.pose = obj.pose(); msg.scale = obj.scale(); res.objects.push_back(msg); } return true; } bool RobotApi::LookAt(code_it_msgs::LookAtRequest& req, code_it_msgs::LookAtResponse& res) { return robot_->head()->LookAt(req.target); } bool RobotApi::Pick(code_it_msgs::PickRequest& req, code_it_msgs::PickResponse& res) { if (!scene_has_parsed_) { PublishError(errors::PICK_SCENE_NOT_PARSED); return false; } bool has_left_object = robot_->left_gripper()->is_holding_object(); bool has_right_object = robot_->right_gripper()->is_holding_object(); // Check if both hands are full if (has_left_object && has_right_object) { PublishError(errors::PICK_ARMS_FULL); return false; } // If using the default arm, use whichever arm is free, or the right arm if // both arms are free. int8_t arm_id = req.arm.arm_id; if (arm_id == code_it_msgs::ArmId::DEFAULT) { if (has_left_object && !has_right_object) { arm_id = code_it_msgs::ArmId::RIGHT; } else if (!has_left_object && has_right_object) { arm_id = code_it_msgs::ArmId::LEFT; } else { arm_id = code_it_msgs::ArmId::RIGHT; } } rapid::perception::Object object; if (!scene_.GetObject(req.object.name, &object)) { PublishError(errors::PICK_OBJECT_NOT_FOUND); return false; } bool success = false; if (arm_id == code_it_msgs::ArmId::LEFT) { if (has_left_object) { PublishError(errors::PICK_LEFT_FULL); return false; } success = robot_->left_picker()->Pick(object); } else { if (has_right_object) { PublishError(errors::PICK_RIGHT_FULL); return false; } success = robot_->right_picker()->Pick(object); } if (!success) { PublishError(errors::PICK_OBJECT); return false; } return true; } bool RobotApi::Place(code_it_msgs::PlaceRequest& req, code_it_msgs::PlaceResponse& res) { bool has_left_object = robot_->left_gripper()->is_holding_object(); bool has_right_object = robot_->right_gripper()->is_holding_object(); // Check if both hands are empty if (!has_left_object && !has_right_object) { PublishError(errors::PLACE_NO_OBJECTS); return false; } // If using default arm, default to whichever arm has an object, or the right // arm if both arms have objects. int8_t arm_id = req.arm.arm_id; if (arm_id == code_it_msgs::ArmId::DEFAULT) { if (has_left_object && !has_right_object) { arm_id = code_it_msgs::ArmId::LEFT; } else { arm_id = code_it_msgs::ArmId::RIGHT; } } if (arm_id == code_it_msgs::ArmId::LEFT && !has_left_object) { PublishError(errors::PLACE_NO_LEFT_OBJECT); return false; } if (arm_id == code_it_msgs::ArmId::RIGHT && !has_right_object) { PublishError(errors::PLACE_NO_RIGHT_OBJECT); return false; } // Get the tabletop. rpe::Scene scene; bool success = rpe::pr2::GetManipulationScene(tf_listener_, &scene); if (!success) { PublishError(errors::GET_SCENE); return false; } const rpe::HSurface& tt = scene.primary_surface(); if (arm_id == code_it_msgs::ArmId::LEFT) { rpe::Object obj; robot_->left_gripper()->HeldObject(&obj); success = robot_->left_placer()->Place(obj, tt); } else { rpe::Object obj; robot_->right_gripper()->HeldObject(&obj); success = robot_->right_placer()->Place(obj, tt); } if (!success) { PublishError(errors::PLACE_OBJECT); return false; } return true; } bool RobotApi::Say(code_it_msgs::SayRequest& req, code_it_msgs::SayResponse& res) { robot_->sound()->Say(req.text); return true; } bool RobotApi::SetGripper(code_it_msgs::SetGripperRequest& req, code_it_msgs::SetGripperResponse& res) { if (req.gripper.id == code_it_msgs::GripperId::LEFT) { if (req.action == code_it_msgs::SetGripperRequest::OPEN) { robot_->left_gripper()->Open(req.max_effort); } else if (req.action == code_it_msgs::SetGripperRequest::CLOSE) { robot_->left_gripper()->Close(req.max_effort); } } else { if (req.action == code_it_msgs::SetGripperRequest::OPEN) { robot_->right_gripper()->Open(req.max_effort); } else if (req.action == code_it_msgs::SetGripperRequest::CLOSE) { robot_->right_gripper()->Close(req.max_effort); } } return true; } bool RobotApi::TuckArms(code_it_msgs::TuckArmsRequest& req, code_it_msgs::TuckArmsResponse& res) { bool success = false; if (req.tuck_left && req.tuck_right) { success = robot_->tuck_arms()->TuckArms(); } else if (req.tuck_left && !req.tuck_right) { success = robot_->tuck_arms()->DeployRight(); } else if (!req.tuck_left && req.tuck_right) { success = robot_->tuck_arms()->DeployLeft(); } else { success = robot_->tuck_arms()->DeployArms(); } if (!success) { PublishError(errors::TUCK_DEPLOY); return false; } return true; } void RobotApi::HandleProgramStopped(const std_msgs::Bool& msg) { if (msg.data) { return; // Program is running, nothing to do. } bool success = robot_->display()->ShowDefault(); if (!success) { PublishError(errors::RESET_SCREEN_ON_STOP); } } void RobotApi::PublishError(const string& error) { std_msgs::String error_msg; error_msg.data = error; error_pub_.publish(error_msg); ROS_ERROR("%s", error.c_str()); } } // namespace code_it_pr2 <|endoftext|>
<commit_before>#include "selectors.hh" #include "string.hh" #include <algorithm> #include <boost/optional.hpp> namespace Kakoune { Selection select_line(const Buffer& buffer, const Selection& selection) { Utf8Iterator first = buffer.iterator_at(selection.cursor()); if (*first == '\n' and first + 1 != buffer.end()) ++first; while (first != buffer.begin() and *(first - 1) != '\n') --first; Utf8Iterator last = first; while (last + 1 != buffer.end() and *last != '\n') ++last; return utf8_range(first, last); } Selection select_matching(const Buffer& buffer, const Selection& selection) { std::vector<Codepoint> matching_pairs = { '(', ')', '{', '}', '[', ']', '<', '>' }; Utf8Iterator it = buffer.iterator_at(selection.cursor()); std::vector<Codepoint>::iterator match = matching_pairs.end(); while (not is_eol(*it)) { match = std::find(matching_pairs.begin(), matching_pairs.end(), *it); if (match != matching_pairs.end()) break; ++it; } if (match == matching_pairs.end()) return selection; Utf8Iterator begin = it; if (((match - matching_pairs.begin()) % 2) == 0) { int level = 0; const Codepoint opening = *match; const Codepoint closing = *(match+1); while (it != buffer.end()) { if (*it == opening) ++level; else if (*it == closing and --level == 0) return utf8_range(begin, it); ++it; } } else { int level = 0; const Codepoint opening = *(match-1); const Codepoint closing = *match; while (true) { if (*it == closing) ++level; else if (*it == opening and --level == 0) return utf8_range(begin, it); if (it == buffer.begin()) break; --it; } } return selection; } // c++14 will add std::optional, so we use boost::optional until then using boost::optional; static optional<Selection> find_surrounding(const Buffer& buffer, BufferCoord coord, CodepointPair matching, ObjectFlags flags, int init_level) { const bool to_begin = flags & ObjectFlags::ToBegin; const bool to_end = flags & ObjectFlags::ToEnd; const bool nestable = matching.first != matching.second; auto pos = buffer.iterator_at(coord); Utf8Iterator first = pos; if (to_begin) { int level = nestable ? init_level : 0; while (first != buffer.begin()) { if (nestable and first != pos and *first == matching.second) ++level; else if (*first == matching.first) { if (level == 0) break; else --level; } --first; } if (level != 0 or *first != matching.first) return optional<Selection>{}; } Utf8Iterator last = pos; if (to_end) { int level = nestable ? init_level : 0; while (last != buffer.end()) { if (nestable and last != pos and *last == matching.first) ++level; else if (*last == matching.second) { if (level == 0) break; else --level; } ++last; } if (level != 0 or last == buffer.end()) return optional<Selection>{}; } if (flags & ObjectFlags::Inner) { if (to_begin and first != last) ++first; if (to_end and first != last) --last; } return to_end ? utf8_range(first, last) : utf8_range(last, first); } Selection select_surrounding(const Buffer& buffer, const Selection& selection, CodepointPair matching, int level, ObjectFlags flags) { const bool nestable = matching.first != matching.second; auto pos = selection.cursor(); if (not nestable or flags & ObjectFlags::Inner) { if (auto res = find_surrounding(buffer, pos, matching, flags, level)) return *res; return selection; } auto c = buffer.byte_at(pos); if ((flags == ObjectFlags::ToBegin and c == matching.first) or (flags == ObjectFlags::ToEnd and c == matching.second)) ++level; auto res = find_surrounding(buffer, pos, matching, flags, level); if (not res) return selection; if (flags == (ObjectFlags::ToBegin | ObjectFlags::ToEnd) and res->min() == selection.min() and res->max() == selection.max()) { if (auto res_parent = find_surrounding(buffer, pos, matching, flags, level+1)) return Selection{*res_parent}; } return *res; } Selection select_to(const Buffer& buffer, const Selection& selection, Codepoint c, int count, bool inclusive) { Utf8Iterator begin = buffer.iterator_at(selection.cursor()); Utf8Iterator end = begin; do { ++end; skip_while(end, buffer.end(), [c](Codepoint cur) { return cur != c; }); if (end == buffer.end()) return selection; } while (--count > 0); return utf8_range(begin, inclusive ? end : end-1); } Selection select_to_reverse(const Buffer& buffer, const Selection& selection, Codepoint c, int count, bool inclusive) { Utf8Iterator begin = buffer.iterator_at(selection.cursor()); Utf8Iterator end = begin; do { --end; skip_while_reverse(end, buffer.begin(), [c](Codepoint cur) { return cur != c; }); if (end == buffer.begin()) return selection; } while (--count > 0); return utf8_range(begin, inclusive ? end : end+1); } Selection select_to_eol(const Buffer& buffer, const Selection& selection) { Utf8Iterator begin = buffer.iterator_at(selection.cursor()); Utf8Iterator end = begin; skip_while(end, buffer.end(), [](Codepoint cur) { return not is_eol(cur); }); return utf8_range(begin, end != begin ? end-1 : end); } Selection select_to_eol_reverse(const Buffer& buffer, const Selection& selection) { Utf8Iterator begin = buffer.iterator_at(selection.cursor()); Utf8Iterator end = begin - 1; skip_while_reverse(end, buffer.begin(), [](Codepoint cur) { return not is_eol(cur); }); return utf8_range(begin, end == buffer.begin() ? end : end+1); } static bool is_end_of_sentence(char c) { return c == '.' or c == ';' or c == '!' or c == '?'; } Selection select_whole_sentence(const Buffer& buffer, const Selection& selection, ObjectFlags flags) { BufferIterator first = buffer.iterator_at(selection.cursor()); BufferIterator last = first; if (flags & ObjectFlags::ToBegin) { bool saw_non_blank = false; while (first != buffer.begin()) { char cur = *first; char prev = *(first-1); if (not is_blank(cur)) saw_non_blank = true; if (is_eol(prev) and is_eol(cur)) { ++first; break; } else if (is_end_of_sentence(prev)) { if (saw_non_blank) break; else if (flags & ObjectFlags::ToEnd) last = first-1; } --first; } skip_while(first, buffer.end(), is_blank); } if (flags & ObjectFlags::ToEnd) { while (last != buffer.end()) { char cur = *last; if (is_end_of_sentence(cur) or (is_eol(cur) and (last+1 == buffer.end() or is_eol(*(last+1))))) break; ++last; } if (not (flags & ObjectFlags::Inner) and last != buffer.end()) { ++last; skip_while(last, buffer.end(), is_blank); --last; } } return (flags & ObjectFlags::ToEnd) ? Selection{first.coord(), last.coord()} : Selection{last.coord(), first.coord()}; } Selection select_whole_paragraph(const Buffer& buffer, const Selection& selection, ObjectFlags flags) { BufferIterator first = buffer.iterator_at(selection.cursor()); BufferIterator last = first; if (flags & ObjectFlags::ToBegin and first != buffer.begin()) { skip_while_reverse(first, buffer.begin(), is_eol); if (flags & ObjectFlags::ToEnd) last = first; while (first != buffer.begin()) { char cur = *first; char prev = *(first-1); if (is_eol(prev) and is_eol(cur)) { ++first; break; } --first; } } if (flags & ObjectFlags::ToEnd) { while (last != buffer.end()) { char cur = *last; char prev = *(last-1); if (is_eol(cur) and is_eol(prev)) { if (not (flags & ObjectFlags::Inner)) skip_while(last, buffer.end(), is_eol); break; } ++last; } --last; } return (flags & ObjectFlags::ToEnd) ? Selection{first.coord(), last.coord()} : Selection{last.coord(), first.coord()}; } static CharCount get_indent(const String& str, int tabstop) { CharCount indent = 0; for (auto& c : str) { if (c == ' ') ++indent; else if (c =='\t') indent = (indent / tabstop + 1) * tabstop; else break; } return indent; } Selection select_whole_indent(const Buffer& buffer, const Selection& selection, ObjectFlags flags) { int tabstop = buffer.options()["tabstop"].get<int>(); LineCount line = selection.cursor().line; auto indent = get_indent(buffer[line], tabstop); LineCount begin_line = line - 1; if (flags & ObjectFlags::ToBegin) { while (begin_line >= 0 and (buffer[begin_line] == "\n" or get_indent(buffer[begin_line], tabstop) >= indent)) --begin_line; } ++begin_line; LineCount end_line = line + 1; if (flags & ObjectFlags::ToEnd) { LineCount end = buffer.line_count(); while (end_line < end and (buffer[end_line] == "\n" or get_indent(buffer[end_line], tabstop) >= indent)) ++end_line; } --end_line; BufferCoord first = begin_line; // keep the first line indent in inner mode if (flags & ObjectFlags::Inner) { CharCount i = 0; for (; i < indent; ++first.column) { auto c = buffer.byte_at(first); if (c == ' ') ++i; if (c == '\t') i = (i / tabstop + 1) * tabstop; } } return Selection{first, {end_line, buffer[end_line].length() - 1}}; } Selection select_whole_lines(const Buffer& buffer, const Selection& selection) { // no need to be utf8 aware for is_eol as we only use \n as line seperator BufferIterator first = buffer.iterator_at(selection.anchor()); BufferIterator last = buffer.iterator_at(selection.cursor()); BufferIterator& to_line_start = first <= last ? first : last; BufferIterator& to_line_end = first <= last ? last : first; --to_line_start; skip_while_reverse(to_line_start, buffer.begin(), [](char cur) { return not is_eol(cur); }); if (is_eol(*to_line_start)) ++to_line_start; skip_while(to_line_end, buffer.end(), [](char cur) { return not is_eol(cur); }); if (to_line_end == buffer.end()) --to_line_end; return Selection(first.coord(), last.coord()); } Selection trim_partial_lines(const Buffer& buffer, const Selection& selection) { // same as select_whole_lines BufferIterator first = buffer.iterator_at(selection.anchor()); BufferIterator last = buffer.iterator_at(selection.cursor()); BufferIterator& to_line_start = first <= last ? first : last; BufferIterator& to_line_end = first <= last ? last : first; while (to_line_start != buffer.begin() and *(to_line_start-1) != '\n') ++to_line_start; while (*(to_line_end+1) != '\n' and to_line_end != to_line_start) --to_line_end; return Selection(first.coord(), last.coord()); } void select_whole_buffer(const Buffer& buffer, SelectionList& selections) { selections = SelectionList{ Selection({0,0}, buffer.back_coord()) }; } void select_all_matches(const Buffer& buffer, SelectionList& selections, const Regex& regex) { SelectionList result; for (auto& sel : selections) { auto sel_end = utf8::next(buffer.iterator_at(sel.max())); RegexIterator re_it(buffer.iterator_at(sel.min()), sel_end, regex); RegexIterator re_end; for (; re_it != re_end; ++re_it) { auto& begin = (*re_it)[0].first; auto& end = (*re_it)[0].second; if (begin == sel_end) continue; CaptureList captures; for (auto& match : *re_it) captures.emplace_back(match.first, match.second); result.emplace_back(begin.coord(), (begin == end ? end : utf8::previous(end)).coord(), std::move(captures)); } } if (result.empty()) throw runtime_error("nothing selected"); result.set_main_index(result.size() - 1); selections = std::move(result); } void split_selections(const Buffer& buffer, SelectionList& selections, const Regex& regex) { SelectionList result; for (auto& sel : selections) { auto begin = buffer.iterator_at(sel.min()); auto sel_end = utf8::next(buffer.iterator_at(sel.max())); RegexIterator re_it(begin, sel_end, regex, boost::regex_constants::match_nosubs); RegexIterator re_end; for (; re_it != re_end; ++re_it) { BufferIterator end = (*re_it)[0].first; result.emplace_back(begin.coord(), (begin == end) ? end.coord() : utf8::previous(end).coord()); begin = (*re_it)[0].second; } if (begin.coord() <= sel.max()) result.emplace_back(begin.coord(), sel.max()); } result.set_main_index(result.size() - 1); selections = std::move(result); } } <commit_msg>When selecting forward paragraph and we are on an end of line, select the next one.<commit_after>#include "selectors.hh" #include "string.hh" #include <algorithm> #include <boost/optional.hpp> namespace Kakoune { Selection select_line(const Buffer& buffer, const Selection& selection) { Utf8Iterator first = buffer.iterator_at(selection.cursor()); if (*first == '\n' and first + 1 != buffer.end()) ++first; while (first != buffer.begin() and *(first - 1) != '\n') --first; Utf8Iterator last = first; while (last + 1 != buffer.end() and *last != '\n') ++last; return utf8_range(first, last); } Selection select_matching(const Buffer& buffer, const Selection& selection) { std::vector<Codepoint> matching_pairs = { '(', ')', '{', '}', '[', ']', '<', '>' }; Utf8Iterator it = buffer.iterator_at(selection.cursor()); std::vector<Codepoint>::iterator match = matching_pairs.end(); while (not is_eol(*it)) { match = std::find(matching_pairs.begin(), matching_pairs.end(), *it); if (match != matching_pairs.end()) break; ++it; } if (match == matching_pairs.end()) return selection; Utf8Iterator begin = it; if (((match - matching_pairs.begin()) % 2) == 0) { int level = 0; const Codepoint opening = *match; const Codepoint closing = *(match+1); while (it != buffer.end()) { if (*it == opening) ++level; else if (*it == closing and --level == 0) return utf8_range(begin, it); ++it; } } else { int level = 0; const Codepoint opening = *(match-1); const Codepoint closing = *match; while (true) { if (*it == closing) ++level; else if (*it == opening and --level == 0) return utf8_range(begin, it); if (it == buffer.begin()) break; --it; } } return selection; } // c++14 will add std::optional, so we use boost::optional until then using boost::optional; static optional<Selection> find_surrounding(const Buffer& buffer, BufferCoord coord, CodepointPair matching, ObjectFlags flags, int init_level) { const bool to_begin = flags & ObjectFlags::ToBegin; const bool to_end = flags & ObjectFlags::ToEnd; const bool nestable = matching.first != matching.second; auto pos = buffer.iterator_at(coord); Utf8Iterator first = pos; if (to_begin) { int level = nestable ? init_level : 0; while (first != buffer.begin()) { if (nestable and first != pos and *first == matching.second) ++level; else if (*first == matching.first) { if (level == 0) break; else --level; } --first; } if (level != 0 or *first != matching.first) return optional<Selection>{}; } Utf8Iterator last = pos; if (to_end) { int level = nestable ? init_level : 0; while (last != buffer.end()) { if (nestable and last != pos and *last == matching.first) ++level; else if (*last == matching.second) { if (level == 0) break; else --level; } ++last; } if (level != 0 or last == buffer.end()) return optional<Selection>{}; } if (flags & ObjectFlags::Inner) { if (to_begin and first != last) ++first; if (to_end and first != last) --last; } return to_end ? utf8_range(first, last) : utf8_range(last, first); } Selection select_surrounding(const Buffer& buffer, const Selection& selection, CodepointPair matching, int level, ObjectFlags flags) { const bool nestable = matching.first != matching.second; auto pos = selection.cursor(); if (not nestable or flags & ObjectFlags::Inner) { if (auto res = find_surrounding(buffer, pos, matching, flags, level)) return *res; return selection; } auto c = buffer.byte_at(pos); if ((flags == ObjectFlags::ToBegin and c == matching.first) or (flags == ObjectFlags::ToEnd and c == matching.second)) ++level; auto res = find_surrounding(buffer, pos, matching, flags, level); if (not res) return selection; if (flags == (ObjectFlags::ToBegin | ObjectFlags::ToEnd) and res->min() == selection.min() and res->max() == selection.max()) { if (auto res_parent = find_surrounding(buffer, pos, matching, flags, level+1)) return Selection{*res_parent}; } return *res; } Selection select_to(const Buffer& buffer, const Selection& selection, Codepoint c, int count, bool inclusive) { Utf8Iterator begin = buffer.iterator_at(selection.cursor()); Utf8Iterator end = begin; do { ++end; skip_while(end, buffer.end(), [c](Codepoint cur) { return cur != c; }); if (end == buffer.end()) return selection; } while (--count > 0); return utf8_range(begin, inclusive ? end : end-1); } Selection select_to_reverse(const Buffer& buffer, const Selection& selection, Codepoint c, int count, bool inclusive) { Utf8Iterator begin = buffer.iterator_at(selection.cursor()); Utf8Iterator end = begin; do { --end; skip_while_reverse(end, buffer.begin(), [c](Codepoint cur) { return cur != c; }); if (end == buffer.begin()) return selection; } while (--count > 0); return utf8_range(begin, inclusive ? end : end+1); } Selection select_to_eol(const Buffer& buffer, const Selection& selection) { Utf8Iterator begin = buffer.iterator_at(selection.cursor()); Utf8Iterator end = begin; skip_while(end, buffer.end(), [](Codepoint cur) { return not is_eol(cur); }); return utf8_range(begin, end != begin ? end-1 : end); } Selection select_to_eol_reverse(const Buffer& buffer, const Selection& selection) { Utf8Iterator begin = buffer.iterator_at(selection.cursor()); Utf8Iterator end = begin - 1; skip_while_reverse(end, buffer.begin(), [](Codepoint cur) { return not is_eol(cur); }); return utf8_range(begin, end == buffer.begin() ? end : end+1); } static bool is_end_of_sentence(char c) { return c == '.' or c == ';' or c == '!' or c == '?'; } Selection select_whole_sentence(const Buffer& buffer, const Selection& selection, ObjectFlags flags) { BufferIterator first = buffer.iterator_at(selection.cursor()); BufferIterator last = first; if (flags & ObjectFlags::ToBegin) { bool saw_non_blank = false; while (first != buffer.begin()) { char cur = *first; char prev = *(first-1); if (not is_blank(cur)) saw_non_blank = true; if (is_eol(prev) and is_eol(cur)) { ++first; break; } else if (is_end_of_sentence(prev)) { if (saw_non_blank) break; else if (flags & ObjectFlags::ToEnd) last = first-1; } --first; } skip_while(first, buffer.end(), is_blank); } if (flags & ObjectFlags::ToEnd) { while (last != buffer.end()) { char cur = *last; if (is_end_of_sentence(cur) or (is_eol(cur) and (last+1 == buffer.end() or is_eol(*(last+1))))) break; ++last; } if (not (flags & ObjectFlags::Inner) and last != buffer.end()) { ++last; skip_while(last, buffer.end(), is_blank); --last; } } return (flags & ObjectFlags::ToEnd) ? Selection{first.coord(), last.coord()} : Selection{last.coord(), first.coord()}; } Selection select_whole_paragraph(const Buffer& buffer, const Selection& selection, ObjectFlags flags) { BufferIterator first = buffer.iterator_at(selection.cursor()); BufferIterator last = first; if (flags & ObjectFlags::ToBegin and first != buffer.begin()) { skip_while_reverse(first, buffer.begin(), is_eol); if (flags & ObjectFlags::ToEnd) last = first; while (first != buffer.begin()) { char cur = *first; char prev = *(first-1); if (is_eol(prev) and is_eol(cur)) { ++first; break; } --first; } } if (flags & ObjectFlags::ToEnd) { if (last != buffer.end() && is_eol(*last)) ++last; while (last != buffer.end()) { char cur = *last; char prev = *(last-1); if (is_eol(cur) and is_eol(prev)) { if (not (flags & ObjectFlags::Inner)) skip_while(last, buffer.end(), is_eol); break; } ++last; } --last; } return (flags & ObjectFlags::ToEnd) ? Selection{first.coord(), last.coord()} : Selection{last.coord(), first.coord()}; } static CharCount get_indent(const String& str, int tabstop) { CharCount indent = 0; for (auto& c : str) { if (c == ' ') ++indent; else if (c =='\t') indent = (indent / tabstop + 1) * tabstop; else break; } return indent; } Selection select_whole_indent(const Buffer& buffer, const Selection& selection, ObjectFlags flags) { int tabstop = buffer.options()["tabstop"].get<int>(); LineCount line = selection.cursor().line; auto indent = get_indent(buffer[line], tabstop); LineCount begin_line = line - 1; if (flags & ObjectFlags::ToBegin) { while (begin_line >= 0 and (buffer[begin_line] == "\n" or get_indent(buffer[begin_line], tabstop) >= indent)) --begin_line; } ++begin_line; LineCount end_line = line + 1; if (flags & ObjectFlags::ToEnd) { LineCount end = buffer.line_count(); while (end_line < end and (buffer[end_line] == "\n" or get_indent(buffer[end_line], tabstop) >= indent)) ++end_line; } --end_line; BufferCoord first = begin_line; // keep the first line indent in inner mode if (flags & ObjectFlags::Inner) { CharCount i = 0; for (; i < indent; ++first.column) { auto c = buffer.byte_at(first); if (c == ' ') ++i; if (c == '\t') i = (i / tabstop + 1) * tabstop; } } return Selection{first, {end_line, buffer[end_line].length() - 1}}; } Selection select_whole_lines(const Buffer& buffer, const Selection& selection) { // no need to be utf8 aware for is_eol as we only use \n as line seperator BufferIterator first = buffer.iterator_at(selection.anchor()); BufferIterator last = buffer.iterator_at(selection.cursor()); BufferIterator& to_line_start = first <= last ? first : last; BufferIterator& to_line_end = first <= last ? last : first; --to_line_start; skip_while_reverse(to_line_start, buffer.begin(), [](char cur) { return not is_eol(cur); }); if (is_eol(*to_line_start)) ++to_line_start; skip_while(to_line_end, buffer.end(), [](char cur) { return not is_eol(cur); }); if (to_line_end == buffer.end()) --to_line_end; return Selection(first.coord(), last.coord()); } Selection trim_partial_lines(const Buffer& buffer, const Selection& selection) { // same as select_whole_lines BufferIterator first = buffer.iterator_at(selection.anchor()); BufferIterator last = buffer.iterator_at(selection.cursor()); BufferIterator& to_line_start = first <= last ? first : last; BufferIterator& to_line_end = first <= last ? last : first; while (to_line_start != buffer.begin() and *(to_line_start-1) != '\n') ++to_line_start; while (*(to_line_end+1) != '\n' and to_line_end != to_line_start) --to_line_end; return Selection(first.coord(), last.coord()); } void select_whole_buffer(const Buffer& buffer, SelectionList& selections) { selections = SelectionList{ Selection({0,0}, buffer.back_coord()) }; } void select_all_matches(const Buffer& buffer, SelectionList& selections, const Regex& regex) { SelectionList result; for (auto& sel : selections) { auto sel_end = utf8::next(buffer.iterator_at(sel.max())); RegexIterator re_it(buffer.iterator_at(sel.min()), sel_end, regex); RegexIterator re_end; for (; re_it != re_end; ++re_it) { auto& begin = (*re_it)[0].first; auto& end = (*re_it)[0].second; if (begin == sel_end) continue; CaptureList captures; for (auto& match : *re_it) captures.emplace_back(match.first, match.second); result.emplace_back(begin.coord(), (begin == end ? end : utf8::previous(end)).coord(), std::move(captures)); } } if (result.empty()) throw runtime_error("nothing selected"); result.set_main_index(result.size() - 1); selections = std::move(result); } void split_selections(const Buffer& buffer, SelectionList& selections, const Regex& regex) { SelectionList result; for (auto& sel : selections) { auto begin = buffer.iterator_at(sel.min()); auto sel_end = utf8::next(buffer.iterator_at(sel.max())); RegexIterator re_it(begin, sel_end, regex, boost::regex_constants::match_nosubs); RegexIterator re_end; for (; re_it != re_end; ++re_it) { BufferIterator end = (*re_it)[0].first; result.emplace_back(begin.coord(), (begin == end) ? end.coord() : utf8::previous(end).coord()); begin = (*re_it)[0].second; } if (begin.coord() <= sel.max()) result.emplace_back(begin.coord(), sel.max()); } result.set_main_index(result.size() - 1); selections = std::move(result); } } <|endoftext|>
<commit_before> #include "stdexcept.h" namespace std { exception::exception() throw() { } exception::exception(const exception&) throw() { } exception& exception::operator=(const exception&) throw() { return *this; } exception::~exception() { } const char* exception::what() const throw() { return 0; } bad_alloc::bad_alloc() throw() { } bad_alloc::bad_alloc(const bad_alloc&) throw() { } bad_alloc& bad_alloc::operator=(const bad_alloc&) throw() { return *this; } bad_alloc::~bad_alloc() { } const char* bad_alloc::what() const throw() { return "cxxrt::bad_alloc"; } bad_cast::bad_cast() throw() { } bad_cast::bad_cast(const bad_cast&) throw() { } bad_cast& bad_cast::operator=(const bad_cast&) throw() { return *this; } bad_cast::~bad_cast() { } const char* bad_cast::what() const throw() { return "std::bad_cast"; } bad_typeid::bad_typeid() throw() { } bad_typeid::bad_typeid(const bad_typeid &__rhs) throw() { } bad_typeid::~bad_typeid() { } bad_typeid& bad_typeid::operator=(const bad_typeid &__rhs) throw() { return *this; } const char* bad_typeid::what() const throw() { return "std::bad_typeid"; } } <commit_msg>fix for COMPILER-8891: std::exception::what() should not return NULL<commit_after> #include "stdexcept.h" namespace std { exception::exception() throw() { } exception::exception(const exception&) throw() { } exception& exception::operator=(const exception&) throw() { return *this; } exception::~exception() { } const char* exception::what() const throw() { return "std::exception"; } bad_alloc::bad_alloc() throw() { } bad_alloc::bad_alloc(const bad_alloc&) throw() { } bad_alloc& bad_alloc::operator=(const bad_alloc&) throw() { return *this; } bad_alloc::~bad_alloc() { } const char* bad_alloc::what() const throw() { return "cxxrt::bad_alloc"; } bad_cast::bad_cast() throw() { } bad_cast::bad_cast(const bad_cast&) throw() { } bad_cast& bad_cast::operator=(const bad_cast&) throw() { return *this; } bad_cast::~bad_cast() { } const char* bad_cast::what() const throw() { return "std::bad_cast"; } bad_typeid::bad_typeid() throw() { } bad_typeid::bad_typeid(const bad_typeid &__rhs) throw() { } bad_typeid::~bad_typeid() { } bad_typeid& bad_typeid::operator=(const bad_typeid &__rhs) throw() { return *this; } const char* bad_typeid::what() const throw() { return "std::bad_typeid"; } } <|endoftext|>
<commit_before>#include "HTTP.hpp" #include <iostream> #include <sstream> using namespace boost; using namespace boost::asio::ip; // to get 'tcp::' void testGet(asio::io_service& io_service, tcp::resolver& resolver, bool is_ssl, asio::yield_context yield) { RESTClient::HTTP server("httpbin.org", io_service, resolver, yield, is_ssl); RESTClient::HTTPResponse response = server.get("/get"); assert(response.body.empty()); } void testChunkedGet(asio::io_service &io_service, tcp::resolver &resolver, bool is_ssl, asio::yield_context yield) { RESTClient::HTTP server("httpbin.org", io_service, resolver, yield, is_ssl); const int size = 1024; const int chunk_size = 80; std::stringstream path; path << "/range/" << size << "?duration=1&chunk_size=" << chunk_size; RESTClient::HTTPResponse response = server.get(path.str()); // Make up the expected string const std::string block = "abcdefghijklmnopqrstuvwxyz"; std::stringstream expected; int i = 0; size_t block_size = block.size(); while (i < size) { int toWrite = size - i; if (toWrite >= block.size()) { expected << block; i += block_size; } else { std::copy_n(block.begin(), toWrite, std::ostream_iterator<char>(expected)); i += toWrite; } } if (expected.str() != response.body) { std::stringstream msg; using std::endl; msg << "Received body not the same as the expected body. " << "Expected Length: " << size << endl << "Actual Length: " << response.body.size() << endl << endl << "=== Expected data begin === " << endl << expected.str() << endl << "=== Expected data end ===" << endl << "=== Actual data begin === " << endl << response.body << endl << "=== Actual data end ===" << endl; throw std::runtime_error(msg.str()); } } int main(int argc, char *argv[]) { asio::io_service io_service; tcp::resolver resolver(io_service); using namespace std::placeholders; auto runTests = [&](bool is_ssl) { // HTTP get //asio::spawn(io_service, std::bind(testGet, std::ref(io_service), std::ref(resolver), is_ssl, _1)); // HTTPS chunked get asio::spawn(io_service, std::bind(testChunkedGet, std::ref(io_service), std::ref(resolver), is_ssl, _1)); }; // HTTP tests runTests(false); // HTTPS tests //runTests(false); io_service.run(); return 0; } <commit_msg>uncommented tests that were commented out<commit_after>#include "HTTP.hpp" #include <iostream> #include <sstream> #include <boost/algorithm/string/predicate.hpp> using namespace boost; using namespace boost::asio::ip; // to get 'tcp::' void testGet(asio::io_service& io_service, tcp::resolver& resolver, bool is_ssl, asio::yield_context yield) { RESTClient::HTTP server("httpbin.org", io_service, resolver, yield, is_ssl); RESTClient::HTTPResponse response = server.get("/get"); std::string shouldContain("httpbin.org/get"); assert(boost::algorithm::contains(response.body, shouldContain)); } void testChunkedGet(asio::io_service &io_service, tcp::resolver &resolver, bool is_ssl, asio::yield_context yield) { RESTClient::HTTP server("httpbin.org", io_service, resolver, yield, is_ssl); const int size = 1024; const int chunk_size = 80; std::stringstream path; path << "/range/" << size << "?duration=1&chunk_size=" << chunk_size; RESTClient::HTTPResponse response = server.get(path.str()); // Make up the expected string const std::string block = "abcdefghijklmnopqrstuvwxyz"; std::stringstream expected; int i = 0; size_t block_size = block.size(); while (i < size) { int toWrite = size - i; if (toWrite >= block.size()) { expected << block; i += block_size; } else { std::copy_n(block.begin(), toWrite, std::ostream_iterator<char>(expected)); i += toWrite; } } if (expected.str() != response.body) { std::stringstream msg; using std::endl; msg << "Received body not the same as the expected body. " << "Expected Length: " << size << endl << "Actual Length: " << response.body.size() << endl << endl << "=== Expected data begin === " << endl << expected.str() << endl << "=== Expected data end ===" << endl << "=== Actual data begin === " << endl << response.body << endl << "=== Actual data end ===" << endl; throw std::runtime_error(msg.str()); } } int main(int argc, char *argv[]) { asio::io_service io_service; tcp::resolver resolver(io_service); using namespace std::placeholders; auto runTests = [&](bool is_ssl) { // HTTP get asio::spawn(io_service, std::bind(testGet, std::ref(io_service), std::ref(resolver), is_ssl, _1)); // HTTPS chunked get asio::spawn(io_service, std::bind(testChunkedGet, std::ref(io_service), std::ref(resolver), is_ssl, _1)); }; // HTTP tests runTests(false); // HTTPS tests runTests(false); io_service.run(); return 0; } <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2011 Razor team * Authors: * Christian Surlykke <christian@surlykke.dk> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "trayicon.h" #include "razorqt/razorsettings.h" #include "../config/constants.h" #include <math.h> #include <QtCore/QDebug> #include <QtSvg/QSvgRenderer> #include <QtGui/QPainter> TrayIcon::TrayIcon(Battery* battery, QObject *parent) : QSystemTrayIcon(parent), mBattery(battery), mSettings("razor-autosuspend") { connect(mBattery, SIGNAL(batteryChanged()), this, SLOT(update())); connect(RazorSettings::globalSettings(), SIGNAL(iconThemeChanged()), this, SLOT(iconThemeChanged())); connect(&mSettings, SIGNAL(settingsChanged()), this, SLOT(settingsChanged())); connect(this, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(showStatus(QSystemTrayIcon::ActivationReason))); checkThemeStatusIcons(); update(); setVisible(mSettings.value(SHOWTRAYICON_KEY, true).toBool()); } TrayIcon::~TrayIcon() { } void TrayIcon::update() { updateStatusIcon(); updateToolTip(); mBatteryInfo.updateInfo(mBattery); } void TrayIcon::updateStatusIcon() { static double chargeLevel = -1; static bool discharging = false; if (fabs(mBattery->chargeLevel() - chargeLevel) < 0.1 && (mBattery->discharging() == discharging)) { qDebug() << "No significant change - not updating icon"; return; } chargeLevel = mBattery->chargeLevel(); discharging = mBattery->discharging(); if (mSettings.value(USETHEMEICONS_KEY, true).toBool() && mThemeHasStatusIcons) { QString iconName; if (QIcon::themeName() == "oxygen") { if (chargeLevel < 20) iconName = discharging ? "battery-low" : "battery-charging-low"; else if (chargeLevel < 40) iconName = discharging ? "battery-caution" : "battery-charging-caution"; else if (chargeLevel < 60) iconName = discharging ? "battery-040" : "battery-charging-040"; else if (chargeLevel < 80) iconName = discharging ? "battery-060" : "battery-charging-060"; else if (chargeLevel < 99.5) iconName = discharging ? "battery-080" : "battery-charging-080"; else iconName = discharging ? "battery-100" : "battery-charging"; } else // For all themes but 'oxygen' we follow freedesktop's battery status icon name standard // (http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html) _with_ the changes proposed in // https://bugs.freedesktop.org/show_bug.cgi?id=41458 (we assume that this patch will be accepted) { if (chargeLevel < 1 && discharging) iconName = "battery-empty" ; else if (chargeLevel < 20) iconName = discharging ? "battery-caution" : "battery-caution-discharging"; else if (chargeLevel < 40) iconName = discharging ? "battery-low" : "battery-low-discharging"; else if (chargeLevel < 60) iconName = discharging ? "battery-good" : "battery-good-discharging"; else iconName = discharging ? "battery-full" : "battery-full-discharging"; } qDebug() << "ChargeLevel" << chargeLevel << "- getting icon:" << iconName << "from" << QIcon::themeName() << "theme"; setIcon(QIcon::fromTheme(iconName)); } else { setIcon(getBuiltInIcon(chargeLevel, discharging)); } } void TrayIcon::updateToolTip() { QString toolTip = mBattery->stateAsString(); if (mBattery->state() == 1 || mBattery->state() == 2) { toolTip = toolTip + QString(" - %1 %").arg(mBattery->chargeLevel(), 0, 'f', 1); } setToolTip(toolTip); } void TrayIcon::checkThemeStatusIcons() { mThemeHasStatusIcons = true; if ("oxygen" != QIcon::themeName()) { // We know what icons the oxygen theme contains, so with oxygen we're good // but we don't know that all icon themes have those that the freedesktop // standard prescribes. If the current theme doesn't, we will fall back to // the built in status icons. static QStringList statusIconNames = QStringList() << "battery-empty" << "battery-caution" << "battery-low" << "battery-good" << "battery-full" << "battery-caution-charging" << "battery-low-charging" << "battery-good-charging" << "battery-full-charging"; foreach (QString statusIconName, statusIconNames) { if (! QIcon::hasThemeIcon(statusIconName)) { mThemeHasStatusIcons = false; break; } } } } void TrayIcon::iconThemeChanged() { checkThemeStatusIcons(); updateStatusIcon(); } void TrayIcon::settingsChanged() { updateStatusIcon(); setVisible(mSettings.value(SHOWTRAYICON_KEY, true).toBool()); } QIcon TrayIcon::getBuiltInIcon(double chargeLevel, bool discharging) { // See http://www.w3.org/TR/SVG/Overview.html // and regarding circle-arch in particular: // http://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands static const QString svgTemplate = "<?xml version='1.0' standalone='no'?>\n" "<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n" "<svg xmlns='http://www.w3.org/2000/svg' version='1.1' viewBox='0 0 200 200'>\n" " %1\n" " <circle cx='100' cy='100' r='55' fill='white'/>\n" " %2\n" "</svg>\n"; // We show charge with a segment of a circle. // We start at the top of the circle // The starting point of the circle segment is at the top (12 o'clock or (0,1) or pi/2 // and it moves counter-clockwise as the charge increases // First we calculate in floating point numbers, using a circle with center // in (0,0) and a radius of 1 double angle = 2*M_PI*chargeLevel/100 + M_PI_2; double segment_endpoint_x = cos(angle); double segment_endpoint_y = sin(angle); int large_arch = (angle > M_PI + M_PI_2 ? 1 : 0); // 1 if the arch is more than half a circle, 0 otherwise // svg uses an coordinate system with (0,0) at the topmost left corner, // y increasing downwards and x increasing left-to-right. // We draw the circle with center at (100,100) and radius 100 so that it // fits inside a viewBox of (0 0 200 200). int x_start = 100; int y_start = 0; int x_end = round(100 + 100*segment_endpoint_x); int y_end = round(100 - 100*segment_endpoint_y); int x_rel = x_end - x_start; int y_rel = y_end - y_start; // We color the arch red when charge level < 30% and discharging, green otherwise static const QString warningcolor = "rgb(200, 40, 40)"; static const QString green = "rgb(40, 200, 40)"; bool warn_level = chargeLevel < 30 && discharging; QString chargeArch = QString("<path d='M100,100 v -100 a100,100 0 %1,0 %2,%3 z' fill='%4' stroke-width='0'/>") .arg(large_arch) .arg(x_rel) .arg(y_rel) .arg(warn_level ? warningcolor : green); //qDebug() << "chargeArch:" << chargeArch; // We color the minus sign red when chargelevel below 30%, black otherwise QString minus = QString("<path d='M 60,100 h 80' stroke='%1' stroke-width='20'/>") .arg(warn_level ? warningcolor : "black"); static QString plus = "<path d='M 60,100 h 80 M 100,60 v 80' stroke='black' stroke-width='20'/>"; QString svg = svgTemplate.arg(chargeArch).arg(discharging ? minus : plus); qDebug() << svg; // Paint the svg on a pixmap and create an icon from that. QSvgRenderer render(svg.toAscii()); QPixmap pixmap(render.defaultSize()); pixmap.fill(QColor(0,0,0,0)); QPainter painter(&pixmap); render.render(&painter); return QIcon(pixmap); } void TrayIcon::showStatus(ActivationReason reason) { if (reason == QSystemTrayIcon::Trigger) { if (mBatteryInfo.isVisible()) { mBatteryInfo.close(); } else { mBatteryInfo.open(); } } } <commit_msg>Fixes to razor-autosuspend trayicon drawing<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2011 Razor team * Authors: * Christian Surlykke <christian@surlykke.dk> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "trayicon.h" #include "razorqt/razorsettings.h" #include "../config/constants.h" #include <math.h> #include <QtCore/QDebug> #include <QtSvg/QSvgRenderer> #include <QtGui/QPainter> TrayIcon::TrayIcon(Battery* battery, QObject *parent) : QSystemTrayIcon(parent), mBattery(battery), mSettings("razor-autosuspend") { connect(mBattery, SIGNAL(batteryChanged()), this, SLOT(update())); connect(RazorSettings::globalSettings(), SIGNAL(iconThemeChanged()), this, SLOT(iconThemeChanged())); connect(&mSettings, SIGNAL(settingsChanged()), this, SLOT(settingsChanged())); connect(this, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(showStatus(QSystemTrayIcon::ActivationReason))); checkThemeStatusIcons(); update(); setVisible(mSettings.value(SHOWTRAYICON_KEY, true).toBool()); } TrayIcon::~TrayIcon() { } void TrayIcon::update() { updateStatusIcon(); updateToolTip(); mBatteryInfo.updateInfo(mBattery); } void TrayIcon::updateStatusIcon() { static double chargeLevel = -1; static bool discharging = false; if (fabs(mBattery->chargeLevel() - chargeLevel) < 0.1 && (mBattery->discharging() == discharging)) { qDebug() << "No significant change - not updating icon"; return; } chargeLevel = mBattery->chargeLevel(); discharging = mBattery->discharging(); if (mSettings.value(USETHEMEICONS_KEY, true).toBool() && mThemeHasStatusIcons) { QString iconName; if (QIcon::themeName() == "oxygen") { if (chargeLevel < 20) iconName = discharging ? "battery-low" : "battery-charging-low"; else if (chargeLevel < 40) iconName = discharging ? "battery-caution" : "battery-charging-caution"; else if (chargeLevel < 60) iconName = discharging ? "battery-040" : "battery-charging-040"; else if (chargeLevel < 80) iconName = discharging ? "battery-060" : "battery-charging-060"; else if (chargeLevel < 99.5) iconName = discharging ? "battery-080" : "battery-charging-080"; else iconName = discharging ? "battery-100" : "battery-charging"; } else // For all themes but 'oxygen' we follow freedesktop's battery status icon name standard // (http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html) _with_ the changes proposed in // https://bugs.freedesktop.org/show_bug.cgi?id=41458 (we assume that this patch will be accepted) { if (chargeLevel < 1 && discharging) iconName = "battery-empty" ; else if (chargeLevel < 20) iconName = discharging ? "battery-caution" : "battery-caution-discharging"; else if (chargeLevel < 40) iconName = discharging ? "battery-low" : "battery-low-discharging"; else if (chargeLevel < 60) iconName = discharging ? "battery-good" : "battery-good-discharging"; else iconName = discharging ? "battery-full" : "battery-full-discharging"; } qDebug() << "ChargeLevel" << chargeLevel << "- getting icon:" << iconName << "from" << QIcon::themeName() << "theme"; setIcon(QIcon::fromTheme(iconName)); } else { setIcon(getBuiltInIcon(chargeLevel, discharging)); } } void TrayIcon::updateToolTip() { QString toolTip = mBattery->stateAsString(); if (mBattery->state() == 1 || mBattery->state() == 2) { toolTip = toolTip + QString(" - %1 %").arg(mBattery->chargeLevel(), 0, 'f', 1); } setToolTip(toolTip); } void TrayIcon::checkThemeStatusIcons() { mThemeHasStatusIcons = true; if ("oxygen" != QIcon::themeName()) { // We know what icons the oxygen theme contains, so with oxygen we're good // but we don't know that all icon themes have those that the freedesktop // standard prescribes. If the current theme doesn't, we will fall back to // the built in status icons. static QStringList statusIconNames = QStringList() << "battery-empty" << "battery-caution" << "battery-low" << "battery-good" << "battery-full" << "battery-caution-charging" << "battery-low-charging" << "battery-good-charging" << "battery-full-charging"; foreach (QString statusIconName, statusIconNames) { if (! QIcon::hasThemeIcon(statusIconName)) { mThemeHasStatusIcons = false; break; } } } } void TrayIcon::iconThemeChanged() { checkThemeStatusIcons(); updateStatusIcon(); } void TrayIcon::settingsChanged() { updateStatusIcon(); setVisible(mSettings.value(SHOWTRAYICON_KEY, true).toBool()); } QIcon TrayIcon::getBuiltInIcon(double chargeLevel, bool discharging) { // See http://www.w3.org/TR/SVG/Overview.html // and regarding circle-arch in particular: // http://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands // We show charge with a segment of a circle. // We start at the top of the circle // The starting point of the circle segment is at the top (12 o'clock or (0,1) or pi/2 // and it moves counter-clockwise as the charge increases // First we calculate in floating point numbers, using a circle with center // in (0,0) and a radius of 1 double angle = 2*M_PI*chargeLevel/100 + M_PI_2; qDebug() << "Angle:" << angle; double segment_endpoint_x = cos(angle); double segment_endpoint_y = sin(angle); // svg uses an coordinate system with (0,0) at the topmost left corner, // y increasing downwards and x increasing left-to-right. // We draw the circle segments with center at (100,100) and radius 100 for the // outer and radius 60 for the inner. The segments will (unless fully charged, // where they go full circle) be radially connected at the endpoints. QString chargeGraphics; if (chargeLevel < 0.5) { chargeGraphics = ""; } else if (chargeLevel > 99.5) { chargeGraphics = "<path d='M 100,0 A 100,100 0 1,0 101,0 z M 100,40 A 60,60 0 1,0 101,40 z' stroke-width='0'/>"; } else { chargeGraphics = QString("<path d='M 100,0 A 100,100 0 %1,0 %2,%3 L %4,%5 A 60,60 0 %1,1 100,40 z'/>") .arg(angle > M_PI + M_PI_2 ? 1 : 0) // %1 .arg(round(100*(1 + segment_endpoint_x))) // %2 .arg(round(100*(1 - segment_endpoint_y))) // %3 .arg(round(100*(1 + 0.6*segment_endpoint_x))) // %4 .arg(round(100*(1 - 0.6*segment_endpoint_y))); // %5 } QString chargeColor; int lowLevel = mSettings.value(POWERLOWLEVEL_KEY, 5).toInt(); if (discharging && chargeLevel <= lowLevel + 10) { chargeColor = "rgb(200,40,40)"; } else if (discharging && chargeLevel <= lowLevel + 30) { int fac = chargeLevel - lowLevel - 10; chargeColor = QString("rgb(%1,%2,40)").arg(40 + 200 - fac*8).arg(40 + fac*8); } else chargeColor = "rgb(40,200,40)"; QString sign = discharging ? QString("<path d='M 60,100 h 80' stroke='black' stroke-width='20' />"): // Minus QString("<path d='M 60,100 h 80 M 100,60 v 80' stroke='black' stroke-width='20' />"); // Plus QString svg = QString("<?xml version='1.0' standalone='no'?>\n" "<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n" "<svg xmlns='http://www.w3.org/2000/svg' version='1.1' viewBox='0 0 210 210'>\n" " <circle cx='100' cy='100' r='100' fill='rgb(210,210,210)' stroke-width='0'/>\n" " <circle cx='100' cy='100' r='55' fill='rgb(255,255,255)' stroke-width='0'/>\n" " <g fill-rule='evenodd' fill='%2' stroke-width='0'>\n" " %1\n" " </g>\n" " %3\n" "</svg>\n").arg(chargeGraphics).arg(chargeColor).arg(sign); qDebug() << svg; // Paint the svg on a pixmap and create an icon from that. QSvgRenderer render(svg.toAscii()); QPixmap pixmap(render.defaultSize()); pixmap.fill(QColor(0,0,0,0)); QPainter painter(&pixmap); render.render(&painter); return QIcon(pixmap); } /*QIcon TrayIcon::getBuiltInIcon(double chargeLevel, bool discharging) { // See http://www.w3.org/TR/SVG/Overview.html // and regarding circle-arch in particular: // http://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands static const QString svgTemplate = "<?xml version='1.0' standalone='no'?>\n" "<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n" "<svg xmlns='http://www.w3.org/2000/svg' version='1.1' viewBox='0 0 200 200'>\n" " %1\n" " <circle cx='100' cy='100' r='55' fill='white'/>\n" " %2\n" "</svg>\n"; // We show charge with a segment of a circle. // We start at the top of the circle // The starting point of the circle segment is at the top (12 o'clock or (0,1) or pi/2 // and it moves counter-clockwise as the charge increases // First we calculate in floating point numbers, using a circle with center // in (0,0) and a radius of 1 double angle = 2*M_PI*chargeLevel/100 + M_PI_2; double segment_endpoint_x = cos(angle); double segment_endpoint_y = sin(angle); int large_arch = (angle > M_PI + M_PI_2 ? 1 : 0); // 1 if the arch is more than half a circle, 0 otherwise // svg uses an coordinate system with (0,0) at the topmost left corner, // y increasing downwards and x increasing left-to-right. // We draw the circle with center at (100,100) and radius 100 so that it // fits inside a viewBox of (0 0 200 200). int x_start = 100; int y_start = 0; int x_end = round(100 + 100*segment_endpoint_x); int y_end = round(100 - 100*segment_endpoint_y); int x_rel = x_end - x_start; int y_rel = y_end - y_start; // We color the arch red when charge level < 30% and discharging, green otherwise static const QString warningcolor = "rgb(200, 40, 40)"; static const QString green = "rgb(40, 200, 40)"; bool warn_level = chargeLevel < 30 && discharging; QString chargeArch = QString("<path d='M100,100 v -100 a100,100 0 %1,0 %2,%3 z' fill='%4' stroke-width='0'/>") .arg(large_arch) .arg(x_rel) .arg(y_rel) .arg(warn_level ? warningcolor : green); //qDebug() << "chargeArch:" << chargeArch; // We color the minus sign red when chargelevel below 30%, black otherwise QString minus = QString("<path d='M 60,100 h 80' stroke='%1' stroke-width='20'/>") .arg(warn_level ? warningcolor : "black"); static QString plus = "<path d='M 60,100 h 80 M 100,60 v 80' stroke='black' stroke-width='20'/>"; QString svg = svgTemplate.arg(chargeArch).arg(discharging ? minus : plus); qDebug() << svg; // Paint the svg on a pixmap and create an icon from that. QSvgRenderer render(svg.toAscii()); QPixmap pixmap(render.defaultSize()); pixmap.fill(QColor(0,0,0,0)); QPainter painter(&pixmap); render.render(&painter); return QIcon(pixmap); }*/ void TrayIcon::showStatus(ActivationReason reason) { if (reason == QSystemTrayIcon::Trigger) { if (mBatteryInfo.isVisible()) { mBatteryInfo.close(); } else { mBatteryInfo.open(); } } } <|endoftext|>
<commit_before>#include "TrayMenu.h" #include <QAction> #include <QWidgetAction> #include "Light.h" #include <QDir> #include "ColorPickerController.h" #include <QWidget> #include <QSlider> #include <QLabel> #include <QHBoxLayout> #include <QPluginLoader> TrayMenu::TrayMenu(std::shared_ptr<ILight> light, QWidget* parent) : QMenu(parent), quitAction(new QAction("Quit", this)), activeController(-1), light(light) { //FIXME this should not be connected to qApp.quit(). Instead it should //invoke a local slot which cleans up before quitting. connect(quitAction, SIGNAL(triggered()),qApp,SLOT(quit())); //load all light controllers loadPlugins(); //populate the controller selection submenu controllerSelection = new QMenu("Select Mode", this); this->addMenu(controllerSelection); for(int i = 0; i < controllers.size(); ++i) { QAction* act = new QAction(this); act->setCheckable(true); act->setChecked(false); act->setData(QVariant(i)); act->setText(controllers[i]->getName()); controllerSelection->addAction(act); } connect(controllerSelection, SIGNAL(triggered(QAction*)), this, SLOT(controllerSelected(QAction*))); this->addSeparator(); //set brightness action QSlider* brightnessSlider = new QSlider(nullptr); brightnessSlider->setOrientation(Qt::Horizontal); brightnessSlider->setMinimum(0); brightnessSlider->setMaximum(255); brightnessSlider->setValue(255); QLabel* brightnesslabel = new QLabel("Brightness", nullptr); QHBoxLayout* brightnessLayout = new QHBoxLayout(nullptr); brightnessLayout->addWidget(brightnesslabel); brightnessLayout->addWidget(brightnessSlider); QWidget* brightnessWidget = new QWidget(nullptr); brightnessWidget->setLayout(brightnessLayout); QWidgetAction* brigthnessAction = new QWidgetAction(nullptr); brigthnessAction->setDefaultWidget(brightnessWidget); connect(brightnessSlider, SIGNAL(valueChanged(int)), this, SLOT(brightnessChanged(int))); this->addAction(brigthnessAction); this->addSeparator(); this->addAction(quitAction); if(controllers.size() > 0) { activateController(0);//FIXME should be loaded from settings?! controllerSelection->actions()[0]->setChecked(true);//mark the first controller as active } else { qWarning() << "No controllers found!"; } } void TrayMenu::activateController(const int controllerIndex) { Q_ASSERT(controllerIndex >= 0); Q_ASSERT(controllerIndex < controllers.size()); if(activeController != -1)//is -1 if there has never been an active controller { controllers[activeController]->deactivate(); this->removeAction(this->actions()[0]);//0 is the topmost action, i.e. the action of the old controller //TODO remove old action } activeController = controllerIndex; controllers[controllerIndex]->activate(light); Q_ASSERT(this->actions().size() > 0); this->insertAction( this->actions()[0], controllers[controllerIndex]->getMenuWidget()); } void TrayMenu::brightnessChanged(int newBrightness) { Q_ASSERT(newBrightness >= 0); Q_ASSERT(newBrightness <= 255); if(activeController != -1)//if there is an active controller { controllers[activeController]->setBrightness(newBrightness); } } void TrayMenu::controllerSelected(QAction *action) { const int controllerId = action->data().toInt(); Q_ASSERT(controllerId >= 0); Q_ASSERT(controllerId < controllers.size()); if(controllerId != activeController) { //uncheck all actions for(QAction* action : controllerSelection->actions()) { action->setChecked(false); } activateController(controllerId); } controllerSelection->actions()[controllerId]->setChecked(true); } void TrayMenu::loadPlugins() { QDir pluginsDir = QDir(qApp->applicationDirPath()); pluginsDir.cd("plugins"); qDebug() << "Searching for plugins in: " << pluginsDir.absolutePath(); for(QString fileName : pluginsDir.entryList(QDir::Files)) { qDebug() << "Loading plugin: " << fileName; QPluginLoader loader(pluginsDir.absoluteFilePath(fileName)); QObject *plugin = loader.instance(); if (plugin) { LightController* controller = qobject_cast<LightController*>(plugin); if(controller) { // std::unique_ptr<LightController> pCtrl(controller); controllers.emplace_back(controller); } else { qWarning() << "unable to load plugin " << fileName; } } else { qWarning() << "unable to load plugin " << fileName << "Error: " << loader.errorString(); } } } <commit_msg>Fix includes in menu<commit_after>#include "TrayMenu.h" #include <QAction> #include <QWidgetAction> #include "Light.h" #include <QDir> #include <QWidget> #include <QSlider> #include <QLabel> #include <QHBoxLayout> #include <QPluginLoader> #include "LightController.h" TrayMenu::TrayMenu(std::shared_ptr<ILight> light, QWidget* parent) : QMenu(parent), quitAction(new QAction("Quit", this)), activeController(-1), light(light) { //FIXME this should not be connected to qApp.quit(). Instead it should //invoke a local slot which cleans up before quitting. connect(quitAction, SIGNAL(triggered()),qApp,SLOT(quit())); //load all light controllers loadPlugins(); //populate the controller selection submenu controllerSelection = new QMenu("Select Mode", this); this->addMenu(controllerSelection); for(int i = 0; i < controllers.size(); ++i) { QAction* act = new QAction(this); act->setCheckable(true); act->setChecked(false); act->setData(QVariant(i)); act->setText(controllers[i]->getName()); controllerSelection->addAction(act); } connect(controllerSelection, SIGNAL(triggered(QAction*)), this, SLOT(controllerSelected(QAction*))); this->addSeparator(); //set brightness action QSlider* brightnessSlider = new QSlider(nullptr); brightnessSlider->setOrientation(Qt::Horizontal); brightnessSlider->setMinimum(0); brightnessSlider->setMaximum(255); brightnessSlider->setValue(255); QLabel* brightnesslabel = new QLabel("Brightness", nullptr); QHBoxLayout* brightnessLayout = new QHBoxLayout(nullptr); brightnessLayout->addWidget(brightnesslabel); brightnessLayout->addWidget(brightnessSlider); QWidget* brightnessWidget = new QWidget(nullptr); brightnessWidget->setLayout(brightnessLayout); QWidgetAction* brigthnessAction = new QWidgetAction(nullptr); brigthnessAction->setDefaultWidget(brightnessWidget); connect(brightnessSlider, SIGNAL(valueChanged(int)), this, SLOT(brightnessChanged(int))); this->addAction(brigthnessAction); this->addSeparator(); this->addAction(quitAction); if(controllers.size() > 0) { activateController(0);//FIXME should be loaded from settings?! controllerSelection->actions()[0]->setChecked(true);//mark the first controller as active } else { qWarning() << "No controllers found!"; } } void TrayMenu::activateController(const int controllerIndex) { Q_ASSERT(controllerIndex >= 0); Q_ASSERT(controllerIndex < controllers.size()); if(activeController != -1)//is -1 if there has never been an active controller { controllers[activeController]->deactivate(); this->removeAction(this->actions()[0]);//0 is the topmost action, i.e. the action of the old controller //TODO remove old action } activeController = controllerIndex; controllers[controllerIndex]->activate(light); Q_ASSERT(this->actions().size() > 0); this->insertAction( this->actions()[0], controllers[controllerIndex]->getMenuWidget()); } void TrayMenu::brightnessChanged(int newBrightness) { Q_ASSERT(newBrightness >= 0); Q_ASSERT(newBrightness <= 255); if(activeController != -1)//if there is an active controller { controllers[activeController]->setBrightness(newBrightness); } } void TrayMenu::controllerSelected(QAction *action) { const int controllerId = action->data().toInt(); Q_ASSERT(controllerId >= 0); Q_ASSERT(controllerId < controllers.size()); if(controllerId != activeController) { //uncheck all actions for(QAction* action : controllerSelection->actions()) { action->setChecked(false); } activateController(controllerId); } controllerSelection->actions()[controllerId]->setChecked(true); } void TrayMenu::loadPlugins() { QDir pluginsDir = QDir(qApp->applicationDirPath()); pluginsDir.cd("plugins"); qDebug() << "Searching for plugins in: " << pluginsDir.absolutePath(); for(QString fileName : pluginsDir.entryList(QDir::Files)) { qDebug() << "Loading plugin: " << fileName; QPluginLoader loader(pluginsDir.absoluteFilePath(fileName)); QObject *plugin = loader.instance(); if (plugin) { LightController* controller = qobject_cast<LightController*>(plugin); if(controller) { // std::unique_ptr<LightController> pCtrl(controller); controllers.emplace_back(controller); } else { qWarning() << "unable to load plugin " << fileName; } } else { qWarning() << "unable to load plugin " << fileName << "Error: " << loader.errorString(); } } } <|endoftext|>
<commit_before>// Copyright (c) 2016, Joseph Mirabel // Authors: Joseph Mirabel (joseph.mirabel@laas.fr) // // This file is part of hpp-pinocchio. // hpp-pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-pinocchio. If not, see <http://www.gnu.org/licenses/>. #include <hpp/pinocchio/urdf/util.hh> #include <urdf_parser/urdf_parser.h> #include <hpp/fcl/mesh_loader/loader.h> #include <pinocchio/parsers/utils.hpp> #include <pinocchio/parsers/urdf.hpp> #include <pinocchio/multibody/geometry.hpp> #include <pinocchio/algorithm/geometry.hpp> #include <pinocchio/algorithm/model.hpp> #include <pinocchio/parsers/srdf.hpp> #include <hpp/util/debug.hh> #include <hpp/pinocchio/joint.hh> #include <hpp/pinocchio/joint-collection.hh> #include <hpp/pinocchio/device.hh> #include <hpp/pinocchio/humanoid-robot.hh> namespace hpp { namespace pinocchio { namespace urdf { namespace { #ifdef HPP_DEBUG const bool verbose = true; #else const bool verbose = false; #endif JointPtr_t findSpecialJoint (const HumanoidRobotPtr_t& robot, const std::string& linkName) { return robot->getJointByBodyName (linkName); } void setSpecialJoints (const HumanoidRobotPtr_t& robot, std::string prefix) { if (!prefix.empty() && *prefix.rbegin() != '/') prefix += "/"; try { robot->waist (robot->getJointByName(prefix + "root_joint")); } catch (const std::exception&) { hppDout (notice, "No waist joint found"); } try { robot->chest (findSpecialJoint (robot, prefix + "chest")); } catch (const std::exception&) { hppDout (notice, "No chest joint found"); } try { robot->leftWrist (findSpecialJoint (robot, prefix + "l_wrist")); } catch (const std::exception&) { hppDout (notice, "No left wrist joint found"); } try { robot->rightWrist (findSpecialJoint (robot, prefix + "r_wrist")); } catch (const std::exception&) { hppDout (notice, "No right wrist joint found"); } try { robot->leftAnkle (findSpecialJoint (robot, prefix + "l_ankle")); } catch (const std::exception&) { hppDout (notice, "No left ankle joint found"); } try { robot->rightAnkle (findSpecialJoint (robot, prefix + "r_ankle")); } catch (const std::exception&) { hppDout (notice, "No right ankle joint found"); } try { robot->gazeJoint (findSpecialJoint (robot, prefix + "gaze")); } catch (const std::exception&) { hppDout (notice, "No gaze joint found"); } } void fillGaze (const HumanoidRobotPtr_t robot) { vector3_t dir, origin; // Gaze direction is defined by the gaze joint local // orientation. dir[0] = 1; dir[1] = 0; dir[2] = 0; // Gaze position should is defined by the gaze joint local // origin. origin[0] = 0; origin[1] = 0; origin[2] = 0; robot->gaze (dir, origin); } JointModelVariant buildJoint (const std::string& type) { if (type == "freeflyer") return JointCollection::JointModelFreeFlyer(); else if (type == "planar") return JointCollection::JointModelPlanar(); else if (type == "prismatic_x") return JointCollection::JointModelPX(); else if (type == "prismatic_y") return JointCollection::JointModelPY(); else if (type == "translation3d") return JointCollection::JointModelTranslation(); else throw std::invalid_argument ("Root joint type \"" + type + "\" is currently not available."); } void setPrefix (const std::string& prefix, Model& model, GeomModel& geomModel, const JointIndex& idFirstJoint, const FrameIndex& idFirstFrame) { for (JointIndex i = idFirstJoint; i < model.joints.size(); ++i) { model.names[i] = prefix + model.names[i]; } for (FrameIndex i = idFirstFrame; i < model.frames.size(); ++i) { ::pinocchio::Frame& f = model.frames[i]; f.name = prefix + f.name; } BOOST_FOREACH(::pinocchio::GeometryObject& go, geomModel.geometryObjects) { go.name = prefix + go.name; } } void setRootJointBounds(Model& model, const JointIndex& rtIdx, const std::string& rootType) { value_type b = std::numeric_limits<value_type>::infinity(); if (rootType == "freeflyer") { const std::size_t idx = model.joints[rtIdx].idx_q(); model.upperPositionLimit.segment<3>(idx).setConstant(+b); model.lowerPositionLimit.segment<3>(idx).setConstant(-b); // Quaternion bounds b = 1.01; const size_type quat_idx = idx + 3; model.upperPositionLimit.segment<4>(quat_idx).setConstant(+b); model.lowerPositionLimit.segment<4>(quat_idx).setConstant(-b); } else if (rootType == "planar") { const std::size_t idx = model.joints[rtIdx].idx_q(); model.upperPositionLimit.segment<2>(idx).setConstant(+b); model.lowerPositionLimit.segment<2>(idx).setConstant(-b); // Unit complex bounds b = 1.01; const size_type cplx_idx = idx + 2; model.upperPositionLimit.segment<2>(cplx_idx).setConstant(+b); model.lowerPositionLimit.segment<2>(cplx_idx).setConstant(-b); } } std::string makeModelPath (const std::string& package, const std::string& type, const std::string& modelName, const std::string& suffix = "") { std::stringstream ss; ss << "package://" << package << "/" << type << "/" << modelName << suffix << "." << type; return ss.str(); } template <bool XmlString> void _removeCollisionPairs ( const Model& model, GeomModel& geomModel, const std::string& srdf, bool verbose) { ::pinocchio::srdf::removeCollisionPairsFromXML (model, geomModel, srdf, verbose); } template <> void _removeCollisionPairs<false> ( const Model& model, GeomModel& geomModel, const std::string& srdf, bool verbose) { ::pinocchio::srdf::removeCollisionPairs (model, geomModel, srdf, verbose); } template <bool srdfAsXmlString> void _loadModel (const DevicePtr_t& robot, const FrameIndex& baseFrame, std::string prefix, const std::string& rootType, const ::urdf::ModelInterfaceSharedPtr urdfTree, const std::istream& urdfStream, const std::string& srdf) { if (!urdfTree) throw std::invalid_argument ("Failed to parse URDF. Use check_urdf command to know what's wrong."); ModelPtr_t model = (baseFrame==0 ? robot->modelPtr() : ModelPtr_t(new Model)); const JointIndex idFirstJoint = model->joints.size(); const FrameIndex idFirstFrame = model->frames.size(); if (rootType == "anchor") ::pinocchio::urdf::buildModel(urdfTree, *model, verbose); else ::pinocchio::urdf::buildModel(urdfTree, buildJoint(rootType), *model, verbose); hppDout (notice, "Finished parsing URDF file."); GeomModel geomModel; std::vector<std::string> baseDirs = ::pinocchio::rosPaths(); static fcl::MeshLoaderPtr loader (new fcl::CachedMeshLoader (fcl::BV_OBBRSS)); ::pinocchio::urdf::buildGeom(*model, urdfStream, ::pinocchio::COLLISION, geomModel, baseDirs, loader); geomModel.addAllCollisionPairs(); if (!srdf.empty()) { _removeCollisionPairs<srdfAsXmlString> (*model, geomModel, srdf, verbose); if(!srdfAsXmlString) ::pinocchio::srdf::loadReferenceConfigurations(*model,srdf,verbose); else{ hppDout(warning,"Neutral configuration won't be extracted from SRDF string."); //TODO : A method getNeutralConfigurationFromSrdfString must be added in Pinocchio, // similarly to removeCollisionPairsFromSrdf / removeCollisionPairsFromSrdfString } } if (!prefix.empty()) { if (*prefix.rbegin() != '/') prefix += "/"; setPrefix(prefix, *model, geomModel, idFirstJoint, idFirstFrame); } // Update root joint bounds assert((rootType == "anchor") || (model->names[idFirstJoint] == prefix + "root_joint")); setRootJointBounds(*model, idFirstJoint, rootType); if (baseFrame == 0) ::pinocchio::appendGeometryModel(robot->geomModel(), geomModel); else { ModelPtr_t m (new Model); GeomModelPtr_t gm (new GeomModel); ::pinocchio::appendModel(robot->model(), *model, robot->geomModel(), geomModel, baseFrame, Transform3f::Identity(), *m, *gm); robot->setModel (m); robot->setGeomModel (gm); } robot->createData(); robot->createGeomData(); // Build mimic joint table. typedef std::map<std::string, PINOCCHIO_URDF_SHARED_PTR(::urdf::Joint) > UrdfJointMap_t; for (UrdfJointMap_t::const_iterator _joint = urdfTree->joints_.begin(); _joint != urdfTree->joints_.end(); ++_joint) { const PINOCCHIO_URDF_SHARED_PTR(::urdf::Joint)& joint = _joint->second; if (joint && joint->mimic) { Device::JointLinearConstraint constraint; constraint.joint = robot->getJointByName (prefix + joint->name); constraint.reference = robot->getJointByName (prefix + joint->mimic->joint_name); constraint.multiplier = joint->mimic->multiplier; constraint.offset = joint->mimic->offset; robot->addJointConstraint (constraint); } } hppDout (notice, "Finished parsing SRDF file."); } } void loadRobotModel (const DevicePtr_t& robot, const std::string& rootJointType, const std::string& package, const std::string& modelName, const std::string& urdfSuffix, const std::string& srdfSuffix) { loadModel (robot, 0, "", rootJointType, makeModelPath(package, "urdf", modelName, urdfSuffix), makeModelPath(package, "srdf", modelName, srdfSuffix)); } void loadRobotModel (const DevicePtr_t& robot, const FrameIndex& baseFrame, const std::string& prefix, const std::string& rootJointType, const std::string& package, const std::string& modelName, const std::string& urdfSuffix, const std::string& srdfSuffix) { loadModel (robot, baseFrame, (prefix.empty() ? "" : prefix + "/"), rootJointType, makeModelPath(package, "urdf", modelName, urdfSuffix), makeModelPath(package, "srdf", modelName, srdfSuffix)); } void setupHumanoidRobot (const HumanoidRobotPtr_t& robot, const std::string& prefix) { // Look for special joints and attach them to the model. setSpecialJoints (robot, prefix); // Fill gaze position and direction. fillGaze (robot); } void loadUrdfModel (const DevicePtr_t& robot, const FrameIndex& baseFrame, const std::string& prefix, const std::string& rootJointType, const std::string& package, const std::string& filename) { loadModel (robot, baseFrame, (prefix.empty() ? "" : prefix + "/"), rootJointType, makeModelPath(package, "urdf", filename), ""); } void loadUrdfModel (const DevicePtr_t& robot, const std::string& rootType, const std::string& package, const std::string& filename) { loadModel (robot, 0, "", rootType, makeModelPath(package, "urdf", filename), ""); } void loadModel (const DevicePtr_t& robot, const FrameIndex& baseFrame, const std::string& prefix, const std::string& rootType, const std::string& urdfPath, const std::string& srdfPath) { std::vector<std::string> baseDirs = ::pinocchio::rosPaths(); std::string urdfFileName = ::pinocchio::retrieveResourcePath(urdfPath, baseDirs); if (urdfFileName == "") { throw std::invalid_argument (std::string ("Unable to retrieve ") + urdfPath); } std::string srdfFileName; if (!srdfPath.empty()) { srdfFileName = ::pinocchio::retrieveResourcePath(srdfPath, baseDirs); if (srdfFileName == "") { throw std::invalid_argument (std::string ("Unable to retrieve ") + srdfPath); } } ::urdf::ModelInterfaceSharedPtr urdfTree = ::urdf::parseURDFFile(urdfFileName); std::ifstream urdfStream (urdfFileName.c_str()); _loadModel <false> (robot, baseFrame, prefix, rootType, urdfTree, urdfStream, srdfFileName); } void loadModelFromString (const DevicePtr_t& robot, const FrameIndex& baseFrame, const std::string& prefix, const std::string& rootType, const std::string& urdfString, const std::string& srdfString) { ::urdf::ModelInterfaceSharedPtr urdfTree = ::urdf::parseURDF(urdfString); std::istringstream urdfStream (urdfString); _loadModel <true> (robot, baseFrame, prefix, rootType, urdfTree, urdfStream, srdfString); } } // end of namespace urdf. } // end of namespace pinocchio. } // end of namespace hpp. <commit_msg>Do not fail if a fixed joint has mimic info.<commit_after>// Copyright (c) 2016, Joseph Mirabel // Authors: Joseph Mirabel (joseph.mirabel@laas.fr) // // This file is part of hpp-pinocchio. // hpp-pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-pinocchio. If not, see <http://www.gnu.org/licenses/>. #include <hpp/pinocchio/urdf/util.hh> #include <urdf_parser/urdf_parser.h> #include <hpp/fcl/mesh_loader/loader.h> #include <pinocchio/parsers/utils.hpp> #include <pinocchio/parsers/urdf.hpp> #include <pinocchio/multibody/geometry.hpp> #include <pinocchio/algorithm/geometry.hpp> #include <pinocchio/algorithm/model.hpp> #include <pinocchio/parsers/srdf.hpp> #include <hpp/util/debug.hh> #include <hpp/pinocchio/joint.hh> #include <hpp/pinocchio/joint-collection.hh> #include <hpp/pinocchio/device.hh> #include <hpp/pinocchio/humanoid-robot.hh> namespace hpp { namespace pinocchio { namespace urdf { namespace { #ifdef HPP_DEBUG const bool verbose = true; #else const bool verbose = false; #endif JointPtr_t findSpecialJoint (const HumanoidRobotPtr_t& robot, const std::string& linkName) { return robot->getJointByBodyName (linkName); } void setSpecialJoints (const HumanoidRobotPtr_t& robot, std::string prefix) { if (!prefix.empty() && *prefix.rbegin() != '/') prefix += "/"; try { robot->waist (robot->getJointByName(prefix + "root_joint")); } catch (const std::exception&) { hppDout (notice, "No waist joint found"); } try { robot->chest (findSpecialJoint (robot, prefix + "chest")); } catch (const std::exception&) { hppDout (notice, "No chest joint found"); } try { robot->leftWrist (findSpecialJoint (robot, prefix + "l_wrist")); } catch (const std::exception&) { hppDout (notice, "No left wrist joint found"); } try { robot->rightWrist (findSpecialJoint (robot, prefix + "r_wrist")); } catch (const std::exception&) { hppDout (notice, "No right wrist joint found"); } try { robot->leftAnkle (findSpecialJoint (robot, prefix + "l_ankle")); } catch (const std::exception&) { hppDout (notice, "No left ankle joint found"); } try { robot->rightAnkle (findSpecialJoint (robot, prefix + "r_ankle")); } catch (const std::exception&) { hppDout (notice, "No right ankle joint found"); } try { robot->gazeJoint (findSpecialJoint (robot, prefix + "gaze")); } catch (const std::exception&) { hppDout (notice, "No gaze joint found"); } } void fillGaze (const HumanoidRobotPtr_t robot) { vector3_t dir, origin; // Gaze direction is defined by the gaze joint local // orientation. dir[0] = 1; dir[1] = 0; dir[2] = 0; // Gaze position should is defined by the gaze joint local // origin. origin[0] = 0; origin[1] = 0; origin[2] = 0; robot->gaze (dir, origin); } JointModelVariant buildJoint (const std::string& type) { if (type == "freeflyer") return JointCollection::JointModelFreeFlyer(); else if (type == "planar") return JointCollection::JointModelPlanar(); else if (type == "prismatic_x") return JointCollection::JointModelPX(); else if (type == "prismatic_y") return JointCollection::JointModelPY(); else if (type == "translation3d") return JointCollection::JointModelTranslation(); else throw std::invalid_argument ("Root joint type \"" + type + "\" is currently not available."); } void setPrefix (const std::string& prefix, Model& model, GeomModel& geomModel, const JointIndex& idFirstJoint, const FrameIndex& idFirstFrame) { for (JointIndex i = idFirstJoint; i < model.joints.size(); ++i) { model.names[i] = prefix + model.names[i]; } for (FrameIndex i = idFirstFrame; i < model.frames.size(); ++i) { ::pinocchio::Frame& f = model.frames[i]; f.name = prefix + f.name; } BOOST_FOREACH(::pinocchio::GeometryObject& go, geomModel.geometryObjects) { go.name = prefix + go.name; } } void setRootJointBounds(Model& model, const JointIndex& rtIdx, const std::string& rootType) { value_type b = std::numeric_limits<value_type>::infinity(); if (rootType == "freeflyer") { const std::size_t idx = model.joints[rtIdx].idx_q(); model.upperPositionLimit.segment<3>(idx).setConstant(+b); model.lowerPositionLimit.segment<3>(idx).setConstant(-b); // Quaternion bounds b = 1.01; const size_type quat_idx = idx + 3; model.upperPositionLimit.segment<4>(quat_idx).setConstant(+b); model.lowerPositionLimit.segment<4>(quat_idx).setConstant(-b); } else if (rootType == "planar") { const std::size_t idx = model.joints[rtIdx].idx_q(); model.upperPositionLimit.segment<2>(idx).setConstant(+b); model.lowerPositionLimit.segment<2>(idx).setConstant(-b); // Unit complex bounds b = 1.01; const size_type cplx_idx = idx + 2; model.upperPositionLimit.segment<2>(cplx_idx).setConstant(+b); model.lowerPositionLimit.segment<2>(cplx_idx).setConstant(-b); } } std::string makeModelPath (const std::string& package, const std::string& type, const std::string& modelName, const std::string& suffix = "") { std::stringstream ss; ss << "package://" << package << "/" << type << "/" << modelName << suffix << "." << type; return ss.str(); } template <bool XmlString> void _removeCollisionPairs ( const Model& model, GeomModel& geomModel, const std::string& srdf, bool verbose) { ::pinocchio::srdf::removeCollisionPairsFromXML (model, geomModel, srdf, verbose); } template <> void _removeCollisionPairs<false> ( const Model& model, GeomModel& geomModel, const std::string& srdf, bool verbose) { ::pinocchio::srdf::removeCollisionPairs (model, geomModel, srdf, verbose); } template <bool srdfAsXmlString> void _loadModel (const DevicePtr_t& robot, const FrameIndex& baseFrame, std::string prefix, const std::string& rootType, const ::urdf::ModelInterfaceSharedPtr urdfTree, const std::istream& urdfStream, const std::string& srdf) { if (!urdfTree) throw std::invalid_argument ("Failed to parse URDF. Use check_urdf command to know what's wrong."); ModelPtr_t model = (baseFrame==0 ? robot->modelPtr() : ModelPtr_t(new Model)); const JointIndex idFirstJoint = model->joints.size(); const FrameIndex idFirstFrame = model->frames.size(); if (rootType == "anchor") ::pinocchio::urdf::buildModel(urdfTree, *model, verbose); else ::pinocchio::urdf::buildModel(urdfTree, buildJoint(rootType), *model, verbose); hppDout (notice, "Finished parsing URDF file."); GeomModel geomModel; std::vector<std::string> baseDirs = ::pinocchio::rosPaths(); static fcl::MeshLoaderPtr loader (new fcl::CachedMeshLoader (fcl::BV_OBBRSS)); ::pinocchio::urdf::buildGeom(*model, urdfStream, ::pinocchio::COLLISION, geomModel, baseDirs, loader); geomModel.addAllCollisionPairs(); if (!srdf.empty()) { _removeCollisionPairs<srdfAsXmlString> (*model, geomModel, srdf, verbose); if(!srdfAsXmlString) ::pinocchio::srdf::loadReferenceConfigurations(*model,srdf,verbose); else{ hppDout(warning,"Neutral configuration won't be extracted from SRDF string."); //TODO : A method getNeutralConfigurationFromSrdfString must be added in Pinocchio, // similarly to removeCollisionPairsFromSrdf / removeCollisionPairsFromSrdfString } } if (!prefix.empty()) { if (*prefix.rbegin() != '/') prefix += "/"; setPrefix(prefix, *model, geomModel, idFirstJoint, idFirstFrame); } // Update root joint bounds assert((rootType == "anchor") || (model->names[idFirstJoint] == prefix + "root_joint")); setRootJointBounds(*model, idFirstJoint, rootType); if (baseFrame == 0) ::pinocchio::appendGeometryModel(robot->geomModel(), geomModel); else { ModelPtr_t m (new Model); GeomModelPtr_t gm (new GeomModel); ::pinocchio::appendModel(robot->model(), *model, robot->geomModel(), geomModel, baseFrame, Transform3f::Identity(), *m, *gm); robot->setModel (m); robot->setGeomModel (gm); } robot->createData(); robot->createGeomData(); // Build mimic joint table. typedef std::map<std::string, PINOCCHIO_URDF_SHARED_PTR(::urdf::Joint) > UrdfJointMap_t; for (UrdfJointMap_t::const_iterator _joint = urdfTree->joints_.begin(); _joint != urdfTree->joints_.end(); ++_joint) { const PINOCCHIO_URDF_SHARED_PTR(::urdf::Joint)& joint = _joint->second; if (joint && joint->type != ::urdf::Joint::FIXED && joint->mimic) { Device::JointLinearConstraint constraint; constraint.joint = robot->getJointByName (prefix + joint->name); constraint.reference = robot->getJointByName (prefix + joint->mimic->joint_name); constraint.multiplier = joint->mimic->multiplier; constraint.offset = joint->mimic->offset; robot->addJointConstraint (constraint); } } hppDout (notice, "Finished parsing SRDF file."); } } void loadRobotModel (const DevicePtr_t& robot, const std::string& rootJointType, const std::string& package, const std::string& modelName, const std::string& urdfSuffix, const std::string& srdfSuffix) { loadModel (robot, 0, "", rootJointType, makeModelPath(package, "urdf", modelName, urdfSuffix), makeModelPath(package, "srdf", modelName, srdfSuffix)); } void loadRobotModel (const DevicePtr_t& robot, const FrameIndex& baseFrame, const std::string& prefix, const std::string& rootJointType, const std::string& package, const std::string& modelName, const std::string& urdfSuffix, const std::string& srdfSuffix) { loadModel (robot, baseFrame, (prefix.empty() ? "" : prefix + "/"), rootJointType, makeModelPath(package, "urdf", modelName, urdfSuffix), makeModelPath(package, "srdf", modelName, srdfSuffix)); } void setupHumanoidRobot (const HumanoidRobotPtr_t& robot, const std::string& prefix) { // Look for special joints and attach them to the model. setSpecialJoints (robot, prefix); // Fill gaze position and direction. fillGaze (robot); } void loadUrdfModel (const DevicePtr_t& robot, const FrameIndex& baseFrame, const std::string& prefix, const std::string& rootJointType, const std::string& package, const std::string& filename) { loadModel (robot, baseFrame, (prefix.empty() ? "" : prefix + "/"), rootJointType, makeModelPath(package, "urdf", filename), ""); } void loadUrdfModel (const DevicePtr_t& robot, const std::string& rootType, const std::string& package, const std::string& filename) { loadModel (robot, 0, "", rootType, makeModelPath(package, "urdf", filename), ""); } void loadModel (const DevicePtr_t& robot, const FrameIndex& baseFrame, const std::string& prefix, const std::string& rootType, const std::string& urdfPath, const std::string& srdfPath) { std::vector<std::string> baseDirs = ::pinocchio::rosPaths(); std::string urdfFileName = ::pinocchio::retrieveResourcePath(urdfPath, baseDirs); if (urdfFileName == "") { throw std::invalid_argument (std::string ("Unable to retrieve ") + urdfPath); } std::string srdfFileName; if (!srdfPath.empty()) { srdfFileName = ::pinocchio::retrieveResourcePath(srdfPath, baseDirs); if (srdfFileName == "") { throw std::invalid_argument (std::string ("Unable to retrieve ") + srdfPath); } } ::urdf::ModelInterfaceSharedPtr urdfTree = ::urdf::parseURDFFile(urdfFileName); std::ifstream urdfStream (urdfFileName.c_str()); _loadModel <false> (robot, baseFrame, prefix, rootType, urdfTree, urdfStream, srdfFileName); } void loadModelFromString (const DevicePtr_t& robot, const FrameIndex& baseFrame, const std::string& prefix, const std::string& rootType, const std::string& urdfString, const std::string& srdfString) { ::urdf::ModelInterfaceSharedPtr urdfTree = ::urdf::parseURDF(urdfString); std::istringstream urdfStream (urdfString); _loadModel <true> (robot, baseFrame, prefix, rootType, urdfTree, urdfStream, srdfString); } } // end of namespace urdf. } // end of namespace pinocchio. } // end of namespace hpp. <|endoftext|>
<commit_before>#include "x_client.hpp" x_client::x_client(x_connection & c, const xcb_window_t & window) : m_c(c), m_window(window) { m_c.attach(0, XCB_MAP_NOTIFY, this); m_c.attach(0, XCB_UNMAP_NOTIFY, this); m_c.attach(0, XCB_CONFIGURE_NOTIFY, this); m_c.attach(0, XCB_PROPERTY_NOTIFY, this); m_c.update_input(m_window, XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_PROPERTY_CHANGE); update_geometry(); update_net_wm_desktop(); update_parent_window(); update_name_window_pixmap(); } x_client::~x_client(void) { m_c.detach(XCB_MAP_NOTIFY, this); m_c.detach(XCB_UNMAP_NOTIFY, this); m_c.detach(XCB_CONFIGURE_NOTIFY, this); m_c.detach(XCB_PROPERTY_NOTIFY, this); xcb_free_pixmap(m_c(), m_name_window_pixmap); xcb_free_pixmap(m_c(), m_name_window_dummy); } const rectangle & x_client::rect(void) const { return m_rectangle; } const xcb_window_t & x_client::window(void) const { return m_window; } const xcb_window_t & x_client::parent(void) const { return m_parent; } const xcb_window_t & x_client::name_window_pixmap(void) const { return m_name_window_pixmap == XCB_NONE ? m_name_window_dummy : m_name_window_pixmap; } unsigned int x_client::net_wm_desktop(void) const { return m_net_wm_desktop; } void x_client::update_geometry(void) { xcb_get_geometry_reply_t * geometry_reply = xcb_get_geometry_reply(m_c(), xcb_get_geometry(m_c(), m_window), NULL); m_rectangle.x() = geometry_reply->x; m_rectangle.y() = geometry_reply->y; m_rectangle.width() = geometry_reply->width; m_rectangle.height() = geometry_reply->height; delete geometry_reply; } bool x_client::handle(xcb_generic_event_t * ge) { auto update = [this](void) { observable::notify(); }; if (XCB_CONFIGURE_NOTIFY == (ge->response_type & ~0x80)) { xcb_configure_notify_event_t * e = (xcb_configure_notify_event_t *)ge; if (e->window == m_window) { m_rectangle.x() = e->x; m_rectangle.y() = e->y; m_rectangle.width() = e->width; m_rectangle.height() = e->height; } if (e->window == m_c.root_window() || e->window == m_window) { update(); } return true; } else if (XCB_PROPERTY_NOTIFY == (ge->response_type & ~0x80)) { xcb_property_notify_event_t * e = (xcb_property_notify_event_t *)ge; if (e->window != m_window) return true; if (e->atom == a_net_wm_desktop) { update_net_wm_desktop(); } return true; } else if (XCB_MAP_NOTIFY == (ge->response_type & ~0x80)) { xcb_map_notify_event_t * e = (xcb_map_notify_event_t *)ge; if (e->window == m_window) { update(); } return true; } else if (XCB_UNMAP_NOTIFY == (ge->response_type & ~0x80)) { xcb_unmap_notify_event_t * e = (xcb_unmap_notify_event_t *)ge; if (e->window == m_window) { update(); } return true; } return false; } // private void x_client::update_net_wm_desktop(void) { xcb_generic_error_t * error = NULL; xcb_get_property_cookie_t c = xcb_get_property( m_c(), false, m_window, a_net_wm_desktop, XCB_ATOM_CARDINAL, 0, 32); xcb_get_property_reply_t * r = xcb_get_property_reply(m_c(), c, &error); if (error || r->value_len == 0) { delete error; m_net_wm_desktop = 0; } else { m_net_wm_desktop = *(unsigned int *)xcb_get_property_value(r); } if (r) delete r; } void x_client::update_parent_window(void) { xcb_window_t next_parent = m_window; while (next_parent != m_c.root_window() && next_parent != XCB_NONE) { m_parent = next_parent; next_parent = std::get<0>(m_c.query_tree(next_parent)); } } void x_client::update_name_window_pixmap(void) { xcb_free_pixmap(m_c(), m_name_window_pixmap); m_name_window_pixmap = xcb_generate_id(m_c()); xcb_void_cookie_t c = xcb_composite_name_window_pixmap_checked( m_c(), m_parent, m_name_window_pixmap); xcb_generic_error_t * error = xcb_request_check(m_c(), c); if (error) { delete error; m_name_window_pixmap = XCB_NONE; make_dummy(); } } void x_client::make_dummy(void) { xcb_free_pixmap(m_c(), m_name_window_dummy); m_name_window_dummy = xcb_generate_id(m_c()); xcb_create_pixmap(m_c(), 24, m_name_window_dummy, m_c.root_window(), m_rectangle.width(), m_rectangle.height()); xcb_gcontext_t gc = xcb_generate_id(m_c()); uint32_t fg = 0xff808080; xcb_create_gc(m_c(), gc, m_name_window_dummy, XCB_GC_FOREGROUND, &fg); xcb_rectangle_t r = { 0, 0, (uint16_t)m_rectangle.width(), (uint16_t)m_rectangle.height() }; xcb_poly_fill_rectangle(m_c(), m_name_window_dummy, gc, 1, &r); xcb_free_gc(m_c(), gc); } // free functions std::list<x_client> make_x_clients(x_connection & c, const std::vector<xcb_window_t> & windows) { std::list<x_client> x_clients; for (auto & window : windows) { x_clients.emplace_back(c, window); } return x_clients; } bool operator==(const x_client & x_client, const xcb_window_t & window) { return x_client.m_window == window; } bool operator==(const xcb_window_t & window, const x_client & x_client) { return x_client == window; } <commit_msg>Use translate coordinates request to find parent window; more efficient than query tree<commit_after>#include "x_client.hpp" x_client::x_client(x_connection & c, const xcb_window_t & window) : m_c(c), m_window(window) { m_c.attach(0, XCB_MAP_NOTIFY, this); m_c.attach(0, XCB_UNMAP_NOTIFY, this); m_c.attach(0, XCB_CONFIGURE_NOTIFY, this); m_c.attach(0, XCB_PROPERTY_NOTIFY, this); m_c.update_input(m_window, XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_PROPERTY_CHANGE); update_geometry(); update_net_wm_desktop(); update_parent_window(); update_name_window_pixmap(); } x_client::~x_client(void) { m_c.detach(XCB_MAP_NOTIFY, this); m_c.detach(XCB_UNMAP_NOTIFY, this); m_c.detach(XCB_CONFIGURE_NOTIFY, this); m_c.detach(XCB_PROPERTY_NOTIFY, this); xcb_free_pixmap(m_c(), m_name_window_pixmap); xcb_free_pixmap(m_c(), m_name_window_dummy); } const rectangle & x_client::rect(void) const { return m_rectangle; } const xcb_window_t & x_client::window(void) const { return m_window; } const xcb_window_t & x_client::parent(void) const { return m_parent; } const xcb_window_t & x_client::name_window_pixmap(void) const { return m_name_window_pixmap == XCB_NONE ? m_name_window_dummy : m_name_window_pixmap; } unsigned int x_client::net_wm_desktop(void) const { return m_net_wm_desktop; } void x_client::update_geometry(void) { xcb_get_geometry_reply_t * geometry_reply = xcb_get_geometry_reply(m_c(), xcb_get_geometry(m_c(), m_window), NULL); m_rectangle.x() = geometry_reply->x; m_rectangle.y() = geometry_reply->y; m_rectangle.width() = geometry_reply->width; m_rectangle.height() = geometry_reply->height; delete geometry_reply; } bool x_client::handle(xcb_generic_event_t * ge) { auto update = [this](void) { observable::notify(); }; if (XCB_CONFIGURE_NOTIFY == (ge->response_type & ~0x80)) { xcb_configure_notify_event_t * e = (xcb_configure_notify_event_t *)ge; if (e->window == m_window) { m_rectangle.x() = e->x; m_rectangle.y() = e->y; m_rectangle.width() = e->width; m_rectangle.height() = e->height; } if (e->window == m_c.root_window() || e->window == m_window) { update(); } return true; } else if (XCB_PROPERTY_NOTIFY == (ge->response_type & ~0x80)) { xcb_property_notify_event_t * e = (xcb_property_notify_event_t *)ge; if (e->window != m_window) return true; if (e->atom == a_net_wm_desktop) { update_net_wm_desktop(); } return true; } else if (XCB_MAP_NOTIFY == (ge->response_type & ~0x80)) { xcb_map_notify_event_t * e = (xcb_map_notify_event_t *)ge; if (e->window == m_window) { update(); } return true; } else if (XCB_UNMAP_NOTIFY == (ge->response_type & ~0x80)) { xcb_unmap_notify_event_t * e = (xcb_unmap_notify_event_t *)ge; if (e->window == m_window) { update(); } return true; } return false; } // private void x_client::update_net_wm_desktop(void) { xcb_generic_error_t * error = NULL; xcb_get_property_cookie_t c = xcb_get_property( m_c(), false, m_window, a_net_wm_desktop, XCB_ATOM_CARDINAL, 0, 32); xcb_get_property_reply_t * r = xcb_get_property_reply(m_c(), c, &error); if (error || r->value_len == 0) { delete error; m_net_wm_desktop = 0; } else { m_net_wm_desktop = *(unsigned int *)xcb_get_property_value(r); } if (r) delete r; } void x_client::update_parent_window(void) { xcb_translate_coordinates_cookie_t c = xcb_translate_coordinates(m_c(), m_window, m_c.root_window(), 0, 0); xcb_translate_coordinates_reply_t * r = xcb_translate_coordinates_reply(m_c(), c, NULL); m_parent = r->child; delete r; } void x_client::update_name_window_pixmap(void) { xcb_free_pixmap(m_c(), m_name_window_pixmap); m_name_window_pixmap = xcb_generate_id(m_c()); xcb_void_cookie_t c = xcb_composite_name_window_pixmap_checked( m_c(), m_parent, m_name_window_pixmap); xcb_generic_error_t * error = xcb_request_check(m_c(), c); if (error) { delete error; m_name_window_pixmap = XCB_NONE; make_dummy(); } } void x_client::make_dummy(void) { xcb_free_pixmap(m_c(), m_name_window_dummy); m_name_window_dummy = xcb_generate_id(m_c()); xcb_create_pixmap(m_c(), 24, m_name_window_dummy, m_c.root_window(), m_rectangle.width(), m_rectangle.height()); xcb_gcontext_t gc = xcb_generate_id(m_c()); uint32_t fg = 0xff808080; xcb_create_gc(m_c(), gc, m_name_window_dummy, XCB_GC_FOREGROUND, &fg); xcb_rectangle_t r = { 0, 0, (uint16_t)m_rectangle.width(), (uint16_t)m_rectangle.height() }; xcb_poly_fill_rectangle(m_c(), m_name_window_dummy, gc, 1, &r); xcb_free_gc(m_c(), gc); } // free functions std::list<x_client> make_x_clients(x_connection & c, const std::vector<xcb_window_t> & windows) { std::list<x_client> x_clients; for (auto & window : windows) { x_clients.emplace_back(c, window); } return x_clients; } bool operator==(const x_client & x_client, const xcb_window_t & window) { return x_client.m_window == window; } bool operator==(const xcb_window_t & window, const x_client & x_client) { return x_client == window; } <|endoftext|>
<commit_before> #include "opencv2/objdetect.hpp" #include "opencv2/videoio.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/tracking.hpp" // best available resolution / rate: ffplay -pixel_format mjpeg -video_size 1920x1080 /dev/video1 // best recording solution: ffmpeg -framerate 30 -y -f video4linux2 -pixel_format mjpeg -video_size 1920x1080 -i /dev/video1 -f pulse -i default -acodec copy -vcodec copy /tmp/output.mkv // alternate: mencoder tv:// -tv driver=v4l2:width=1920:height=1080:device=/dev/video1:fps=30:outfmt=mjpeg:forceaudio:alsa=1:adevice=default -ovc copy -oac copy -o /tmp/output.mkv #include "FaceTracker.hpp" #include "FrameDerivatives.hpp" #include "FaceMapper.hpp" #include "Metrics.hpp" #include <iostream> #include <cstdio> #include <cstdlib> using namespace std; using namespace cv; using namespace YerFace; String capture_file; String dlib_shape_predictor; String window_name = "Performance Capture Tests"; FrameDerivatives *frameDerivatives; FaceTracker *faceTracker; FaceMapper *faceMapper; Metrics *metrics; unsigned long frameNum = 0; int main(int argc, const char** argv) { //Command line options. CommandLineParser parser(argc, argv, "{help h||Usage message.}" "{dlib_shape_predictor|data/dlib-shape-predictor/shape_predictor_68_face_landmarks.dat|Model for dlib's facial landmark detector.}" "{capture_file|/dev/video0|Video file or video capture device file to open.}"); parser.about("Yer Face: The butt of all the jokes. (A stupid facial performance capture engine for cartoon animation.)"); if(parser.get<bool>("help")) { parser.printMessage(); return 1; } if(parser.check()) { parser.printMessage(); parser.printErrors(); return 1; } capture_file = parser.get<string>("capture_file"); dlib_shape_predictor = parser.get<string>("dlib_shape_predictor"); //A couple of OpenCV classes. VideoCapture capture; Mat frame; //Instantiate our classes. frameDerivatives = new FrameDerivatives(); faceTracker = new FaceTracker(dlib_shape_predictor, frameDerivatives); faceMapper = new FaceMapper(frameDerivatives, faceTracker); metrics = new Metrics(true); //Open the video stream. capture.open(capture_file); if(!capture.isOpened()) { fprintf(stderr, "Failed opening video stream\n"); return 1; } while(capture.read(frame)) { // Start timer metrics->startClock(); frameNum++; if(frame.empty()) { fprintf(stderr, "Breaking on no frame ready...\n"); break; } frameDerivatives->setCurrentFrame(frame); faceTracker->processCurrentFrame(); faceMapper->processCurrentFrame(); faceTracker->renderPreviewHUD(false); faceMapper->renderPreviewHUD(false); metrics->endClock(); Mat previewFrame = frameDerivatives->getPreviewFrame(); fprintf(stderr, "YerFace Frame %lu %s, %s\n", frameNum, metrics->getTimesString(), metrics->getFPSString()); putText(previewFrame, metrics->getTimesString(), Point(25,50), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0,0,255), 2); putText(previewFrame, metrics->getFPSString(), Point(25,75), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0,0,255), 2); //Display preview frame. imshow(window_name, previewFrame); char c = (char)waitKey(1); if(c == 27) { fprintf(stderr, "Breaking on user escape...\n"); break; } } delete metrics; delete faceMapper; delete faceTracker; delete frameDerivatives; return 0; } <commit_msg>implement a preview image sequence output mechanism so we can preview in real time<commit_after> #include "opencv2/objdetect.hpp" #include "opencv2/videoio.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/tracking.hpp" // best available resolution / rate: ffplay -pixel_format mjpeg -video_size 1920x1080 /dev/video1 // best recording solution: ffmpeg -framerate 30 -y -f video4linux2 -pixel_format mjpeg -video_size 1920x1080 -i /dev/video1 -f pulse -i default -acodec copy -vcodec copy /tmp/output.mkv // alternate: mencoder tv:// -tv driver=v4l2:width=1920:height=1080:device=/dev/video1:fps=30:outfmt=mjpeg:forceaudio:alsa=1:adevice=default -ovc copy -oac copy -o /tmp/output.mkv #include "FaceTracker.hpp" #include "FrameDerivatives.hpp" #include "FaceMapper.hpp" #include "Metrics.hpp" #include <iostream> #include <cstdio> #include <cstdlib> using namespace std; using namespace cv; using namespace YerFace; String capture_file; String dlib_shape_predictor; String prev_imgseq; String window_name = "Performance Capture Tests"; FrameDerivatives *frameDerivatives; FaceTracker *faceTracker; FaceMapper *faceMapper; Metrics *metrics; unsigned long frameNum = 0; int main(int argc, const char** argv) { //Command line options. CommandLineParser parser(argc, argv, "{help h||Usage message.}" "{dlib_shape_predictor|data/dlib-shape-predictor/shape_predictor_68_face_landmarks.dat|Model for dlib's facial landmark detector.}" "{capture_file|/dev/video0|Video file or video capture device file to open.}" "{prev_imgseq||If set, is presumed to be the file name prefix of the output preview image sequence.}"); parser.about("Yer Face: The butt of all the jokes. (A stupid facial performance capture engine for cartoon animation.)"); if(parser.get<bool>("help")) { parser.printMessage(); return 1; } if(parser.check()) { parser.printMessage(); parser.printErrors(); return 1; } capture_file = parser.get<string>("capture_file"); dlib_shape_predictor = parser.get<string>("dlib_shape_predictor"); prev_imgseq = parser.get<string>("prev_imgseq"); //A couple of OpenCV classes. VideoCapture capture; Mat frame; //Instantiate our classes. frameDerivatives = new FrameDerivatives(); faceTracker = new FaceTracker(dlib_shape_predictor, frameDerivatives); faceMapper = new FaceMapper(frameDerivatives, faceTracker); metrics = new Metrics(true); //Open the video stream. capture.open(capture_file); if(!capture.isOpened()) { fprintf(stderr, "Failed opening video stream\n"); return 1; } while(capture.read(frame)) { // Start timer metrics->startClock(); frameNum++; if(frame.empty()) { fprintf(stderr, "Breaking on no frame ready...\n"); break; } frameDerivatives->setCurrentFrame(frame); faceTracker->processCurrentFrame(); faceMapper->processCurrentFrame(); faceTracker->renderPreviewHUD(false); faceMapper->renderPreviewHUD(false); metrics->endClock(); Mat previewFrame = frameDerivatives->getPreviewFrame(); fprintf(stderr, "YerFace Frame %lu %s, %s\n", frameNum, metrics->getTimesString(), metrics->getFPSString()); putText(previewFrame, metrics->getTimesString(), Point(25,50), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0,0,255), 2); putText(previewFrame, metrics->getFPSString(), Point(25,75), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0,0,255), 2); //Display preview frame. imshow(window_name, previewFrame); char c = (char)waitKey(1); if(c == 27) { fprintf(stderr, "Breaking on user escape...\n"); break; } //If requested, write image sequence. if(prev_imgseq.length() > 0) { int filenameLength = prev_imgseq.length() + 32; char filename[filenameLength]; snprintf(filename, filenameLength, "%s-%06lu.png", prev_imgseq.c_str(), frameNum); fprintf(stderr, "YerFace writing preview frame to %s ...\n", filename); imwrite(filename, previewFrame); } } delete metrics; delete faceMapper; delete faceTracker; delete frameDerivatives; return 0; } <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "stx/application.h" #include "stx/logging.h" #include "stx/random.h" #include "stx/thread/eventloop.h" #include "stx/thread/threadpool.h" #include "stx/thread/FixedSizeThreadPool.h" #include "stx/io/TerminalOutputStream.h" #include "stx/wallclock.h" #include "stx/json/json.h" #include "stx/json/jsonrpc.h" #include "stx/http/httpclient.h" #include "stx/http/HTTPSSEResponseHandler.h" #include "stx/cli/CLI.h" #include "stx/cli/flagparser.h" #include "stx/cli/term.h" using namespace stx; stx::thread::EventLoop ev; String loadAuth(const cli::FlagParser& global_flags) { auto auth_file_path = FileUtil::joinPaths(getenv("HOME"), ".z1auth"); if (FileUtil::exists(auth_file_path)) { return FileUtil::read(auth_file_path).toString(); } else { if (global_flags.isSet("auth_token")) { return global_flags.getString("auth_token"); } else { RAISE( kRuntimeError, "no auth token found - you must either call 'zli login' or pass the " "--auth_token flag"); } } } void cmd_run( const cli::FlagParser& global_flags, const cli::FlagParser& cmd_flags) { const auto& argv = cmd_flags.getArgv(); if (argv.size() != 1) { RAISE(kUsageError, "usage: $ zli run <script.js>"); } if (!(StringUtil::endsWith(argv[0], "js") || StringUtil::endsWith(argv[0], "sql"))) { RAISE(kUsageError, "unsupported file format"); } auto stdout_os = OutputStream::getStdout(); auto stderr_os = TerminalOutputStream::fromStream(OutputStream::getStderr()); try { auto program_source = FileUtil::read(argv[0]); bool finished = false; bool error = false; String error_string; bool line_dirty = false; bool is_tty = stderr_os->isTTY(); auto event_handler = [&] (const http::HTTPSSEEvent& ev) { if (ev.name.isEmpty()) { return; } if (ev.name.get() == "status") { auto obj = json::parseJSON(ev.data); auto tasks_completed = json::objectGetUInt64(obj, "num_tasks_completed"); auto tasks_total = json::objectGetUInt64(obj, "num_tasks_total"); auto tasks_running = json::objectGetUInt64(obj, "num_tasks_running"); auto progress = json::objectGetFloat(obj, "progress"); auto status_line = StringUtil::format( "[$0/$1] $2 tasks running ($3%)", tasks_completed.isEmpty() ? 0 : tasks_completed.get(), tasks_total.isEmpty() ? 0 : tasks_total.get(), tasks_running.isEmpty() ? 0 : tasks_running.get(), progress.isEmpty() ? 0 : progress.get() * 100); if (is_tty) { stderr_os->eraseLine(); stderr_os->print("\r" + status_line); line_dirty = true; } else { stderr_os->print(status_line + "\n"); } return; } if (line_dirty) { stderr_os->eraseLine(); stderr_os->print("\r"); line_dirty = false; } if (ev.name.get() == "job_started") { //stderr_os->printYellow(">> Job started\n"); return; } if (ev.name.get() == "job_finished") { finished = true; return; } if (ev.name.get() == "error") { error = true; error_string = URI::urlDecode(ev.data); return; } if (ev.name.get() == "result") { stdout_os->write(URI::urlDecode(ev.data)); return; } if (ev.name.get() == "log") { stderr_os->print(URI::urlDecode(ev.data) + "\n"); return; } }; std::string url; //run mapreduce if (StringUtil::endsWith(argv[0], "js")) { url = StringUtil::format( "http://$0/api/v1/mapreduce/execute", global_flags.getString("api_host")); } //run sql query if (StringUtil::endsWith(argv[0], "sql")) { url = StringUtil::format( "http://$0/api/v1/sql_stream?query=$1", global_flags.getString("api_host"), URI::urlEncode(program_source.toString())); program_source.clear(); } auto auth_token = loadAuth(global_flags); http::HTTPMessage::HeaderList auth_headers; auth_headers.emplace_back( "Authorization", StringUtil::format("Token $0", auth_token)); if (is_tty) { stderr_os->print("Launching job..."); line_dirty = true; } else { stderr_os->print("Launching job...\n"); } http::HTTPClient http_client; auto req = http::HTTPRequest::mkPost(url, program_source, auth_headers); auto res = http_client.executeRequest( req, http::HTTPSSEResponseHandler::getFactory(event_handler)); if (line_dirty) { stderr_os->eraseLine(); stderr_os->print("\r"); } if (res.statusCode() != 200) { error = true; error_string = "HTTP Error: " + res.body().toString(); } if (!finished && !error) { error = true; error_string = "connection to server lost"; } if (error) { stderr_os->print( "ERROR:", { TerminalStyle::RED, TerminalStyle::UNDERSCORE }); stderr_os->print(" " + error_string + "\n"); exit(1); } else { stderr_os->printGreen("Job successfully completed\n"); exit(0); } } catch (const StandardException& e) { stderr_os->print( "ERROR:", { TerminalStyle::RED, TerminalStyle::UNDERSCORE }); stderr_os->print(StringUtil::format(" $0\n", e.what())); exit(1); } } void cmd_login( const cli::FlagParser& global_flags, const cli::FlagParser& cmd_flags) { Term term; term.print(">> Username: "); auto username = term.readLine(); term.print(">> Password (will not be echoed): "); auto password = term.readPassword(); term.print("\n"); try { auto url = StringUtil::format( "http://$0/api/v1/auth/login", global_flags.getString("api_host")); auto authdata = StringUtil::format( "userid=$0&password=$1", URI::urlEncode(username), URI::urlEncode(password)); http::HTTPClient http_client; auto req = http::HTTPRequest::mkPost(url, authdata); auto res = http_client.executeRequest(req); switch (res.statusCode()) { case 200: { auto json = json::parseJSON(res.body()); auto auth_token = json::objectGetString(json, "auth_token"); if (!auth_token.isEmpty()) { { auto auth_file_path = FileUtil::joinPaths(getenv("HOME"), ".z1auth"); auto file = File::openFile( auth_file_path, File::O_WRITE | File::O_CREATEOROPEN | File::O_TRUNCATE); file.write(auth_token.get()); } term.printGreen("Login successful\n"); exit(0); } /* fallthrough */ } case 401: { term.printRed("Invalid credentials, please try again\n"); exit(1); } default: RAISEF(kRuntimeError, "HTTP Error: $0", res.body().toString()); } } catch (const StandardException& e) { term.print("ERROR:", { TerminalStyle::RED, TerminalStyle::UNDERSCORE }); term.print(StringUtil::format(" $0\n", e.what())); exit(1); } } void cmd_version( const cli::FlagParser& global_flags, const cli::FlagParser& cmd_flags) { auto stdout_os = OutputStream::getStdout(); stdout_os->write("zli v0.0.1\n"); } int main(int argc, const char** argv) { stx::Application::init(); stx::Application::logToStderr(); stx::cli::FlagParser flags; flags.defineFlag( "api_host", stx::cli::FlagParser::T_STRING, false, NULL, "api.zscale.io", "api host", "<host>"); flags.defineFlag( "auth_token", stx::cli::FlagParser::T_STRING, false, NULL, NULL, "auth token", "<token>"); flags.defineFlag( "loglevel", stx::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); cli::CLI cli; /* command: run */ auto run_cmd = cli.defineCommand("run"); run_cmd->onCall(std::bind(&cmd_run, flags, std::placeholders::_1)); /* command: login */ auto login_cmd = cli.defineCommand("login"); login_cmd->onCall(std::bind(&cmd_login, flags, std::placeholders::_1)); /* command: version */ auto version_cmd = cli.defineCommand("version"); version_cmd->onCall(std::bind(&cmd_version, flags, std::placeholders::_1)); //mr_execute_cmd->flags().defineFlag( // "api_host", // stx::cli::FlagParser::T_STRING, // false, // NULL, // "api.zscale.io", // "api host", // "<host>"); cli.call(flags.getArgv()); return 0; } <commit_msg>dummy commit<commit_after>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "stx/application.h" #include "stx/logging.h" #include "stx/random.h" #include "stx/thread/eventloop.h" #include "stx/thread/threadpool.h" #include "stx/thread/FixedSizeThreadPool.h" #include "stx/io/TerminalOutputStream.h" #include "stx/wallclock.h" #include "stx/json/json.h" #include "stx/json/jsonrpc.h" #include "stx/http/httpclient.h" #include "stx/http/HTTPSSEResponseHandler.h" #include "stx/cli/CLI.h" #include "stx/cli/flagparser.h" #include "stx/cli/term.h" using namespace stx; stx::thread::EventLoop ev; String loadAuth(const cli::FlagParser& global_flags) { auto auth_file_path = FileUtil::joinPaths(getenv("HOME"), ".z1auth"); if (FileUtil::exists(auth_file_path)) { return FileUtil::read(auth_file_path).toString(); } else { if (global_flags.isSet("auth_token")) { return global_flags.getString("auth_token"); } else { RAISE( kRuntimeError, "no auth token found - you must either call 'zli login' or pass the " "--auth_token flag"); } } } void cmd_run( const cli::FlagParser& global_flags, const cli::FlagParser& cmd_flags) { const auto& argv = cmd_flags.getArgv(); if (argv.size() != 1) { RAISE(kUsageError, "usage: $ zli run <script.js>"); } if (!(StringUtil::endsWith(argv[0], "js") || StringUtil::endsWith(argv[0], "sql"))) { RAISE(kUsageError, "unsupported file format"); } auto stdout_os = OutputStream::getStdout(); auto stderr_os = TerminalOutputStream::fromStream(OutputStream::getStderr()); try { auto program_source = FileUtil::read(argv[0]); bool finished = false; bool error = false; String error_string; bool line_dirty = false; bool is_tty = stderr_os->isTTY(); auto event_handler = [&] (const http::HTTPSSEEvent& ev) { if (ev.name.isEmpty()) { return; } if (ev.name.get() == "status") { auto obj = json::parseJSON(ev.data); auto tasks_completed = json::objectGetUInt64(obj, "num_tasks_completed"); auto tasks_total = json::objectGetUInt64(obj, "num_tasks_total"); auto tasks_running = json::objectGetUInt64(obj, "num_tasks_running"); auto progress = json::objectGetFloat(obj, "progress"); auto status_line = StringUtil::format( "[$0/$1] $2 tasks running ($3%)", tasks_completed.isEmpty() ? 0 : tasks_completed.get(), tasks_total.isEmpty() ? 0 : tasks_total.get(), tasks_running.isEmpty() ? 0 : tasks_running.get(), progress.isEmpty() ? 0 : progress.get() * 100); if (is_tty) { stderr_os->eraseLine(); stderr_os->print("\r" + status_line); line_dirty = true; } else { stderr_os->print(status_line + "\n"); } return; } if (line_dirty) { stderr_os->eraseLine(); stderr_os->print("\r"); line_dirty = false; } if (ev.name.get() == "job_started") { //stderr_os->printYellow(">> Job started\n"); return; } if (ev.name.get() == "job_finished") { finished = true; return; } if (ev.name.get() == "error") { error = true; error_string = URI::urlDecode(ev.data); return; } if (ev.name.get() == "result") { stdout_os->write(URI::urlDecode(ev.data)); return; } if (ev.name.get() == "log") { stderr_os->print(URI::urlDecode(ev.data) + "\n"); return; } }; std::string url; //run mapreduce if (StringUtil::endsWith(argv[0], "js")) { url = StringUtil::format( "http://$0/api/v1/mapreduce/execute", global_flags.getString("api_host")); } //run sql query if (StringUtil::endsWith(argv[0], "sql")) { url = StringUtil::format( "http://$0/api/v1/sql_stream?query=$1", global_flags.getString("api_host"), URI::urlEncode(program_source.toString())); program_source.clear(); } auto auth_token = loadAuth(global_flags); http::HTTPMessage::HeaderList auth_headers; auth_headers.emplace_back( "Authorization", StringUtil::format("Token $0", auth_token)); if (is_tty) { stderr_os->print("Launching job..."); line_dirty = true; } else { stderr_os->print("Launching job...\n"); } http::HTTPClient http_client; auto req = http::HTTPRequest::mkPost(url, program_source, auth_headers); auto res = http_client.executeRequest( req, http::HTTPSSEResponseHandler::getFactory(event_handler)); if (line_dirty) { stderr_os->eraseLine(); stderr_os->print("\r"); } if (res.statusCode() != 200) { error = true; error_string = "HTTP Error: " + res.body().toString(); } if (!finished && !error) { error = true; error_string = "connection to server lost"; } if (error) { stderr_os->print( "ERROR:", { TerminalStyle::RED, TerminalStyle::UNDERSCORE }); stderr_os->print(" " + error_string + "\n"); exit(1); } else { stderr_os->printGreen("Job successfully completed\n"); exit(0); } } catch (const StandardException& e) { stderr_os->print( "ERROR:", { TerminalStyle::RED, TerminalStyle::UNDERSCORE }); stderr_os->print(StringUtil::format(" $0\n", e.what())); exit(1); } } void cmd_login( const cli::FlagParser& global_flags, const cli::FlagParser& cmd_flags) { Term term; term.print(">> Username: "); auto username = term.readLine(); term.print(">> Password (will not be echoed): "); auto password = term.readPassword(); term.print("\n"); try { auto url = StringUtil::format( "http://$0/api/v1/auth/login", global_flags.getString("api_host")); auto authdata = StringUtil::format( "userid=$0&password=$1", URI::urlEncode(username), URI::urlEncode(password)); http::HTTPClient http_client; auto req = http::HTTPRequest::mkPost(url, authdata); auto res = http_client.executeRequest(req); switch (res.statusCode()) { case 200: { auto json = json::parseJSON(res.body()); auto auth_token = json::objectGetString(json, "auth_token"); if (!auth_token.isEmpty()) { { auto auth_file_path = FileUtil::joinPaths(getenv("HOME"), ".z1auth"); auto file = File::openFile( auth_file_path, File::O_WRITE | File::O_CREATEOROPEN | File::O_TRUNCATE); file.write(auth_token.get()); } term.printGreen("Login successful\n"); exit(0); } /* fallthrough */ } case 401: { term.printRed("Invalid credentials, please try again\n"); exit(1); } default: RAISEF(kRuntimeError, "HTTP Error: $0", res.body().toString()); } } catch (const StandardException& e) { term.print("ERROR:", { TerminalStyle::RED, TerminalStyle::UNDERSCORE }); term.print(StringUtil::format(" $0\n", e.what())); exit(1); } } void cmd_version( const cli::FlagParser& global_flags, const cli::FlagParser& cmd_flags) { auto stdout_os = OutputStream::getStdout(); stdout_os->write("zli v0.0.1\n"); } int main(int argc, const char** argv) { stx::Application::init(); stx::Application::logToStderr(); stx::cli::FlagParser flags; flags.defineFlag( "api_host", stx::cli::FlagParser::T_STRING, false, NULL, "api.zscale.io", "api host", "<host>"); flags.defineFlag( "auth_token", stx::cli::FlagParser::T_STRING, false, NULL, NULL, "auth token", "<token>"); flags.defineFlag( "loglevel", stx::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); cli::CLI cli; /* command: run */ auto run_cmd = cli.defineCommand("run"); run_cmd->onCall(std::bind(&cmd_run, flags, std::placeholders::_1)); /* command: login */ auto login_cmd = cli.defineCommand("login"); login_cmd->onCall(std::bind(&cmd_login, flags, std::placeholders::_1)); /* command: version */ auto version_cmd = cli.defineCommand("version"); version_cmd->onCall(std::bind(&cmd_version, flags, std::placeholders::_1)); //mr_execute_cmd->flags().defineFlag( // "api_host", // stx::cli::FlagParser::T_STRING, // false, // NULL, // "api.zscale.io", // "api host", // "<host>"); cli.call(flags.getArgv()); return 0; } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Sven Kaulmann #ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH #define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH #include <dune/common/fvector.hh> #include <dune/grid/common/backuprestore.hh> #include <dune/grid/common/grid.hh> #include <dune/grid/common/entity.hh> #include <dune/stuff/common/ranges.hh> #include <dune/stuff/aliases.hh> #include <dune/stuff/fem/namespace.hh> #if HAVE_DUNE_FEM #include <dune/fem/function/common/discretefunction.hh> #include <dune/fem/quadrature/cachingquadrature.hh> #include <dune/fem/space/finitevolume.hh> #include <dune/fem/space/lagrange.hh> #endif #include <dune/grid/io/file/vtk/function.hh> #include <dune/stuff/grid/search.hh> namespace Dune { namespace Stuff { #if HAVE_DUNE_FEM template< class F, class G, int p, template< class > class S > std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType> global_evaluation_points(const Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>& space, const typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::EntityType& target_entity) { const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity); const auto& target_geometry = target_entity.geometry(); const auto quadNop = target_lagrangepoint_set.nop(); std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType> points(quadNop); for(size_t qP = 0; qP < quadNop ; ++qP) { points[qP] = target_geometry.global(target_lagrangepoint_set.point(qP)); } return points; } template< class F, class G, int p, template< class > class S > std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType> global_evaluation_points(const Dune::Fem::FiniteVolumeSpace<F,G,p,S>& /*space*/, const typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::EntityType& target_entity) { assert(false); typedef std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType> Ret; return Ret(1, target_entity.geometry().center()); } template< template< class > class SearchStrategy = Grid::EntityInlevelSearch > class HeterogenousProjection { public: /** If your SearchStrategy only takes a leafview of the source grid, you may use this signature. * Otherwise you'll have to provide an instance of the SearchStrategy to the method below **/ template < class SourceDFImp, class TargetDFImp > static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source, Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target) { SearchStrategy<typename SourceDFImp::GridType::LeafGridView> search(source.gridPart().grid().leafView()); project(source, target, search); } //! signature for non-default SearchStrategy constructions template < class SourceDFImp, class TargetDFImp, class SearchStrategyImp > static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source, Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target, SearchStrategyImp& search) { typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType; static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange; const auto& space = target.space(); // set all DoFs to infinity preprocess(target); const auto endit = space.end(); for(auto it = space.begin(); it != endit ; ++it) { const auto& target_entity = *it; auto target_local_function = target.localFunction(target_entity); const auto global_quads = global_evaluation_points(space, target_entity); const auto evaluation_entity_ptrs = search(global_quads); assert(evaluation_entity_ptrs.size() >= global_quads.size()); int k = 0; typename TargetDiscreteFunctionSpaceType::RangeType source_value; for(size_t qP = 0; qP < global_quads.size() ; ++qP) { if(std::isinf(target_local_function[ k ])) { const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP]; if (source_entity_unique_ptr) { const auto& source_entity_ptr = (*source_entity_unique_ptr); const auto& source_geometry = source_entity_ptr->geometry(); const auto& global_point = global_quads[qP]; const auto& source_local_point = source_geometry.local(global_point); const auto& source_local_function = source.localFunction(*source_entity_ptr); source_local_function.evaluate(source_local_point, source_value); for(int i = 0; i < target_dimRange; ++i, ++k) setDofValue(target_local_function[k], source_value[i]); } else { DUNE_THROW(InvalidStateException, "Did not find the local lagrange point in the source mesh!"); } } else k += target_dimRange; } } postprocess(target); } // ... project(...) protected: template<class TargetDFImp> static void preprocess(Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& func) { typedef typename TargetDFImp::DofType TargetDofType; const auto infinity = DSC::numeric_limits< TargetDofType >::infinity(); // set all DoFs to infinity const auto dend = func.dend(); for( auto dit = func.dbegin(); dit != dend; ++dit ) *dit = infinity; } template<class DofType, class SourceType > static void setDofValue(DofType& dof, const SourceType& value) { dof = value; } template<class TargetDFImp> static void postprocess(typename Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& /*func*/) { return; } }; // class HeterogenousProjection #endif // HAVE_DUNE_FEM #if HAVE_DUNE_GDT template< class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim > std::vector<typename GDT::Spaces::ContinuousLagrangeBase< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >::DomainType> global_evaluation_points(const GDT::Spaces::ContinuousLagrangeBase< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >& space, const typename GDT::Spaces::ContinuousLagrangeBase< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >::EntityType& target_entity) { const auto& target_lagrangepoint_set = space.lagrange_points(target_entity); const auto& target_geometry = target_entity.geometry(); const auto quadNop = target_lagrangepoint_set.size(); std::vector<typename GDT::Spaces::ContinuousLagrangeBase< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >::DomainType> points(quadNop); for(size_t qP = 0; qP < quadNop ; ++qP) { points[qP] = target_geometry.global(target_lagrangepoint_set[qP]); } return points; } template< template< class > class SearchStrategy = Grid::EntityInlevelSearch > class MsFEMProjection { public: //! signature for non-default SearchStrategy constructions template < class SourceSpaceImp, class TargetSpaceImp, class SourceVectorImp, class TargetVectorImp, class SearchStrategyImp > static void project(const GDT::ConstDiscreteFunction< SourceSpaceImp, SourceVectorImp >& source, GDT::DiscreteFunction< TargetSpaceImp, TargetVectorImp >& target, SearchStrategyImp& search) { static const int target_dimRange = TargetSpaceImp::dimRange; const auto& space = target.space(); preprocess(target); for(const auto& target_entity : space) { auto target_local_function = target.local_discrete_function(target_entity); const auto global_quads = global_evaluation_points(space, target_entity); const auto evaluation_entity_ptrs = search(global_quads); assert(evaluation_entity_ptrs.size() >= global_quads.size()); int k = 0; typename GDT::DiscreteFunction< SourceSpaceImp, SourceVectorImp >::RangeType source_value; for(size_t qP = 0; qP < global_quads.size() ; ++qP) { const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP]; if (source_entity_unique_ptr) { const auto& source_entity_ptr = (*source_entity_unique_ptr); const auto& source_geometry = source_entity_ptr->geometry(); const auto& global_point = global_quads[qP]; const auto& source_local_point = source_geometry.local(global_point); const auto& ent = *source_entity_ptr; const auto& source_local_function = source.local_function(ent); source_value = source_local_function->evaluate(source_local_point); for(int i = 0; i < target_dimRange; ++i, ++k) { target_local_function.vector().add(k, source_value[i]); } } else { DUNE_THROW(InvalidStateException, "Did not find the local lagrange point in the source mesh!"); } } } postprocess(target); } // ... project(...) protected: template<class TargetSpaceImp, class VectorImp> static void preprocess(GDT::DiscreteFunction< TargetSpaceImp, VectorImp >& func) { // set all DoFs to zero func.vector() *= 0; } template<class DofType, class SourceType > static void setDofValue(DofType& dof, const SourceType& value) { dof += value; } template<class TargetSpaceImp, class VectorImp> static void postprocess(GDT::DiscreteFunction< TargetSpaceImp, VectorImp >& func) { // compute node to entity relations constexpr static int dimension = TargetSpaceImp::GridViewType::Grid::dimension; std::vector<int> nodeToEntity(func.space().grid_view()->grid().size(dimension), 0); identifySharedNodes(*func.space().grid_view(), nodeToEntity); auto factorsIt = nodeToEntity.begin(); for (auto& dit : func.vector()) { assert(factorsIt!=nodeToEntity.end()); assert(*factorsIt>0); dit /= *factorsIt; ++factorsIt; } return; } template<class GridPartType, class MapType> static void identifySharedNodes(const GridPartType& gridPart, MapType& map) { typedef typename GridPartType::Grid GridType; const auto& indexSet = gridPart.indexSet(); for (auto& entity : DSC::viewRange(gridPart.grid().leafGridView())) { int number_of_nodes_in_entity = entity.template count<GridType::dimension>(); for (int i = 0; i < number_of_nodes_in_entity; ++i) { const auto node = entity.template subEntity<GridType::dimension>(i); const auto global_index_node = indexSet.index(*node); // make sure we don't access non-existing elements assert(map.size() > global_index_node); ++map[global_index_node]; } } } }; #endif // HAVE_DUNE_GDT } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH <commit_msg>[df] msfem projection had a completely unused tpl param<commit_after>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Sven Kaulmann #ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH #define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH #include <dune/common/fvector.hh> #include <dune/grid/common/backuprestore.hh> #include <dune/grid/common/grid.hh> #include <dune/grid/common/entity.hh> #include <dune/stuff/common/ranges.hh> #include <dune/stuff/aliases.hh> #include <dune/stuff/fem/namespace.hh> #if HAVE_DUNE_FEM #include <dune/fem/function/common/discretefunction.hh> #include <dune/fem/quadrature/cachingquadrature.hh> #include <dune/fem/space/finitevolume.hh> #include <dune/fem/space/lagrange.hh> #endif #include <dune/grid/io/file/vtk/function.hh> #include <dune/stuff/grid/search.hh> namespace Dune { namespace Stuff { #if HAVE_DUNE_FEM template< class F, class G, int p, template< class > class S > std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType> global_evaluation_points(const Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>& space, const typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::EntityType& target_entity) { const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity); const auto& target_geometry = target_entity.geometry(); const auto quadNop = target_lagrangepoint_set.nop(); std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType> points(quadNop); for(size_t qP = 0; qP < quadNop ; ++qP) { points[qP] = target_geometry.global(target_lagrangepoint_set.point(qP)); } return points; } template< class F, class G, int p, template< class > class S > std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType> global_evaluation_points(const Dune::Fem::FiniteVolumeSpace<F,G,p,S>& /*space*/, const typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::EntityType& target_entity) { assert(false); typedef std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType> Ret; return Ret(1, target_entity.geometry().center()); } template< template< class > class SearchStrategy = Grid::EntityInlevelSearch > class HeterogenousProjection { public: /** If your SearchStrategy only takes a leafview of the source grid, you may use this signature. * Otherwise you'll have to provide an instance of the SearchStrategy to the method below **/ template < class SourceDFImp, class TargetDFImp > static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source, Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target) { SearchStrategy<typename SourceDFImp::GridType::LeafGridView> search(source.gridPart().grid().leafView()); project(source, target, search); } //! signature for non-default SearchStrategy constructions template < class SourceDFImp, class TargetDFImp, class SearchStrategyImp > static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source, Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target, SearchStrategyImp& search) { typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType; static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange; const auto& space = target.space(); // set all DoFs to infinity preprocess(target); const auto endit = space.end(); for(auto it = space.begin(); it != endit ; ++it) { const auto& target_entity = *it; auto target_local_function = target.localFunction(target_entity); const auto global_quads = global_evaluation_points(space, target_entity); const auto evaluation_entity_ptrs = search(global_quads); assert(evaluation_entity_ptrs.size() >= global_quads.size()); int k = 0; typename TargetDiscreteFunctionSpaceType::RangeType source_value; for(size_t qP = 0; qP < global_quads.size() ; ++qP) { if(std::isinf(target_local_function[ k ])) { const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP]; if (source_entity_unique_ptr) { const auto& source_entity_ptr = (*source_entity_unique_ptr); const auto& source_geometry = source_entity_ptr->geometry(); const auto& global_point = global_quads[qP]; const auto& source_local_point = source_geometry.local(global_point); const auto& source_local_function = source.localFunction(*source_entity_ptr); source_local_function.evaluate(source_local_point, source_value); for(int i = 0; i < target_dimRange; ++i, ++k) setDofValue(target_local_function[k], source_value[i]); } else { DUNE_THROW(InvalidStateException, "Did not find the local lagrange point in the source mesh!"); } } else k += target_dimRange; } } postprocess(target); } // ... project(...) protected: template<class TargetDFImp> static void preprocess(Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& func) { typedef typename TargetDFImp::DofType TargetDofType; const auto infinity = DSC::numeric_limits< TargetDofType >::infinity(); // set all DoFs to infinity const auto dend = func.dend(); for( auto dit = func.dbegin(); dit != dend; ++dit ) *dit = infinity; } template<class DofType, class SourceType > static void setDofValue(DofType& dof, const SourceType& value) { dof = value; } template<class TargetDFImp> static void postprocess(typename Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& /*func*/) { return; } }; // class HeterogenousProjection #endif // HAVE_DUNE_FEM #if HAVE_DUNE_GDT template< class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim > std::vector<typename GDT::Spaces::ContinuousLagrangeBase< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >::DomainType> global_evaluation_points(const GDT::Spaces::ContinuousLagrangeBase< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >& space, const typename GDT::Spaces::ContinuousLagrangeBase< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >::EntityType& target_entity) { const auto& target_lagrangepoint_set = space.lagrange_points(target_entity); const auto& target_geometry = target_entity.geometry(); const auto quadNop = target_lagrangepoint_set.size(); std::vector<typename GDT::Spaces::ContinuousLagrangeBase< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >::DomainType> points(quadNop); for(size_t qP = 0; qP < quadNop ; ++qP) { points[qP] = target_geometry.global(target_lagrangepoint_set[qP]); } return points; } class MsFEMProjection { public: //! signature for non-default SearchStrategy constructions template < class SourceSpaceImp, class TargetSpaceImp, class SourceVectorImp, class TargetVectorImp, class SearchStrategyImp > static void project(const GDT::ConstDiscreteFunction< SourceSpaceImp, SourceVectorImp >& source, GDT::DiscreteFunction< TargetSpaceImp, TargetVectorImp >& target, SearchStrategyImp& search) { static const int target_dimRange = TargetSpaceImp::dimRange; const auto& space = target.space(); preprocess(target); for(const auto& target_entity : space) { auto target_local_function = target.local_discrete_function(target_entity); const auto global_quads = global_evaluation_points(space, target_entity); const auto evaluation_entity_ptrs = search(global_quads); assert(evaluation_entity_ptrs.size() >= global_quads.size()); int k = 0; typename GDT::DiscreteFunction< SourceSpaceImp, SourceVectorImp >::RangeType source_value; for(size_t qP = 0; qP < global_quads.size() ; ++qP) { const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP]; if (source_entity_unique_ptr) { const auto& source_entity_ptr = (*source_entity_unique_ptr); const auto& source_geometry = source_entity_ptr->geometry(); const auto& global_point = global_quads[qP]; const auto& source_local_point = source_geometry.local(global_point); const auto& ent = *source_entity_ptr; const auto& source_local_function = source.local_function(ent); source_value = source_local_function->evaluate(source_local_point); for(int i = 0; i < target_dimRange; ++i, ++k) { target_local_function.vector().add(k, source_value[i]); } } else { DUNE_THROW(InvalidStateException, "Did not find the local lagrange point in the source mesh!"); } } } postprocess(target); } // ... project(...) protected: template<class TargetSpaceImp, class VectorImp> static void preprocess(GDT::DiscreteFunction< TargetSpaceImp, VectorImp >& func) { // set all DoFs to zero func.vector() *= 0; } template<class DofType, class SourceType > static void setDofValue(DofType& dof, const SourceType& value) { dof += value; } template<class TargetSpaceImp, class VectorImp> static void postprocess(GDT::DiscreteFunction< TargetSpaceImp, VectorImp >& func) { // compute node to entity relations constexpr static int dimension = TargetSpaceImp::GridViewType::Grid::dimension; std::vector<int> nodeToEntity(func.space().grid_view()->grid().size(dimension), 0); identifySharedNodes(*func.space().grid_view(), nodeToEntity); auto factorsIt = nodeToEntity.begin(); for (auto& dit : func.vector()) { assert(factorsIt!=nodeToEntity.end()); assert(*factorsIt>0); dit /= *factorsIt; ++factorsIt; } return; } template<class GridPartType, class MapType> static void identifySharedNodes(const GridPartType& gridPart, MapType& map) { typedef typename GridPartType::Grid GridType; const auto& indexSet = gridPart.indexSet(); for (auto& entity : DSC::viewRange(gridPart.grid().leafGridView())) { int number_of_nodes_in_entity = entity.template count<GridType::dimension>(); for (int i = 0; i < number_of_nodes_in_entity; ++i) { const auto node = entity.template subEntity<GridType::dimension>(i); const auto global_index_node = indexSet.index(*node); // make sure we don't access non-existing elements assert(map.size() > global_index_node); ++map[global_index_node]; } } } }; #endif // HAVE_DUNE_GDT } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////////// // PigShipEvent.cpp : Implementation of the CPigShipEvent class. #include "pch.h" #include <TCLib.h> #include <..\TCAtl\ObjectMap.h> #include "Pig.h" #include "PigBehaviorScript.h" #include "PigShip.h" #include "PigShipEvent.h" ///////////////////////////////////////////////////////////////////////////// // CPigShipEvent TC_OBJECT_EXTERN_NON_CREATEABLE_IMPL(CPigShipEvent) ///////////////////////////////////////////////////////////////////////////// // Construction / Destruction HRESULT CPigShipEvent::Init(CPigShip* pPigShip, BSTR bstrTarget) { XLock lock(this); // Save the specified pig ship pointer m_pPigShip = pPigShip; // Perform default processing CPigEvent::Init(m_pPigShip->GetPig()->GetActiveBehavior()->GetMostDerived()); // Set the specified target RETURN_FAILED(SetTarget(bstrTarget)); // Generate an event name CComBSTR bstrFmt; _VERIFYE(bstrFmt.LoadString(IDS_FMT_SHIPEVENT_NAME)); OLECHAR szName[_MAX_PATH]; swprintf(szName, bstrFmt, m_pOwner->GetNextEventNumber()); RETURN_FAILED(put_Name(CComBSTR(szName))); // Indicate success return S_OK; } ///////////////////////////////////////////////////////////////////////////// // Attributes HRESULT CPigShipEvent::SetTarget(BSTR bstrTarget) { // Resolve the specified object name into a model in the current cluster XLock lock(this); m_pTarget = FindTargetName(m_pPigShip->GetPig(), bstrTarget); if (m_pTarget) return S_OK; // Format the error message return FormattedError(IDS_E_FMT_OBJNAME, bstrTarget ? bstrTarget : L""); } ///////////////////////////////////////////////////////////////////////////// // Operations ImodelIGC* CPigShipEvent::FindTargetName(CPig* pPig, BSTR bstrTarget, bool bFriendsOnly) { ImodelIGC* pTarget = NULL; if (pPig && BSTRLen(bstrTarget)) { // Only look in the current cluster IclusterIGC* pCluster = pPig->BaseClient::GetCluster(); if (pCluster) { // Convert the BSTR to ANSI USES_CONVERSION; LPCSTR pszTarget = OLE2CA(bstrTarget); // Get the pig ship's position Vector vPig = pPig->GetShip()->GetPosition(); // Find the nearest model with the specified name float fNearest = 0.f; const ModelListIGC* pModels = pCluster->GetModels(); for (ModelLinkIGC* it = pModels->first(); it; it = it->next()) { ImodelIGC* pModel = it->data(); if (0 == _stricmp(GetModelName(pModel), pszTarget)) { if (bFriendsOnly && pModel->GetSide() != pPig->BaseClient::GetSide()) { //Imago skip! 10/14 } else { float fDistance = (pModel->GetPosition() - vPig).LengthSquared(); if (!pTarget || fDistance < fNearest) { fNearest = fDistance; pTarget = pModel; } } } } } } return pTarget; } ///////////////////////////////////////////////////////////////////////////// // Overrides bool CPigShipEvent::Pulse(bool bExpired) { // Have the ship kill us when expired if (bExpired) m_pPigShip->KillAutoAction(); // Always terminate the event when it expires return bExpired; } bool CPigShipEvent::ModelTerminated(ImodelIGC* pModelIGC) { // Ignore if the specified model is not our action target if (m_pTarget != pModelIGC) return false; // Reset the model pointer m_pTarget = NULL; // Indicate that we should be terminated return true; } ///////////////////////////////////////////////////////////////////////////// // ISupportErrorInfo Interface Methods STDMETHODIMP CPigShipEvent::InterfaceSupportsErrorInfo(REFIID riid) { static const IID* arr[] = { &IID_IPigShipEvent, }; for (int i = 0; i < sizeofArray(arr); ++i) { if (InlineIsEqualGUID(*arr[i], riid)) return S_OK; } return S_FALSE; } ///////////////////////////////////////////////////////////////////////////// // IPigShipEvent Interface Methods STDMETHODIMP CPigShipEvent::get_Target(BSTR* pbstrTarget) { // Initialize the [out] parameter CLEAROUT(pbstrTarget, (BSTR)NULL); // Copy the target name, if any XLock lock(this); if (m_pTarget) *pbstrTarget = CComBSTR(m_pTarget->GetName()).Detach(); // Indicate success return S_OK; } // // ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CPigFaceEvent // ///////////////////////////////////////////////////////////////////////////// // Construction / Destruction HRESULT CPigFaceEvent::Init(CPigShip* pPigShip, VARIANT* pvarTarget, bool bMatchUpVector) { XLock lock(this); // Save the specified pig ship pointer m_pPigShip = pPigShip; // Perform default processing CPigEvent::Init(m_pPigShip->GetPig()->GetActiveBehavior()->GetMostDerived()); // Determine which type of VARIANT was specified if (!pvarTarget) return E_POINTER; VARTYPE vt = V_VT(pvarTarget); switch (vt) { case VT_BSTR: { // Set the specified target as a named model RETURN_FAILED(SetTarget(V_BSTR(pvarTarget))); break; } case VT_DISPATCH: case VT_UNKNOWN: { // See if it's an IAGCModel IAGCModelPtr spModel(V_UNKNOWN(pvarTarget)); if (NULL != spModel) { IAGCPrivatePtr spPrivate(spModel); if (NULL == spPrivate) return E_INVALIDARG; m_pTarget = reinterpret_cast<ImodelIGC*>(spPrivate->GetIGCVoid()); } else { // See if it's an IAGCVector IAGCVectorPtr spVector(V_UNKNOWN(pvarTarget)); IAGCVectorPrivatePtr spPrivate(spVector); if (NULL == spPrivate) return E_INVALIDARG; RETURN_FAILED(spPrivate->CopyVectorTo(&m_vector)); m_bVector = true; } break; } default: return DISP_E_TYPEMISMATCH; } // Get the target's radius, if it's a model if (m_pTarget) m_fTargetRadius = m_pTarget->GetRadius() * 0.25f; // Generate an event name CComBSTR bstrFmt; _VERIFYE(bstrFmt.LoadString(IDS_FMT_SHIPEVENT_NAME)); OLECHAR szName[_MAX_PATH]; swprintf(szName, bstrFmt, m_pOwner->GetNextEventNumber()); RETURN_FAILED(put_Name(CComBSTR(szName))); // Indicate success return S_OK; } ///////////////////////////////////////////////////////////////////////////// // Overrides bool CPigFaceEvent::IsExpired() { // Get the ship object assert(m_pPigShip->GetPig()); IshipIGC* pShip = m_pPigShip->GetPig()->BaseClient::GetShip(); assert(pShip); // We are definitely expired if we are not flying if (PigState_Flying != m_pPigShip->GetPig()->GetCurrentState()) return true; // We are definitely expired if we have no target if (!m_pTarget && !m_bVector) return true; // Get the ship's current controls ControlData cd = pShip->GetControls(); // Determine the vector to face Vector vectorFace(m_bVector ? m_vector : m_pTarget->GetPosition()); // Compute the ship's new controls Vector vectorDelta(vectorFace - pShip->GetPosition()); float deltaAngle = turnToFace(vectorDelta, m_pPigShip->GetPig()->GetUpdateFraction(), pShip, &cd); // Set the ship's new controls pShip->SetControls(cd); // We expire when we are (close to) facing our target // _TRACE1("CPigFaceEvent::IsExpired(): deltaAngle = %f\n", deltaAngle); const static float fMarginStatic = fabs(RadiansFromDegrees(1.f)); float fMargin; if (m_pTarget) { fMargin = fabs(m_fTargetRadius / vectorDelta.Length()); // _TRACE2("CPigFaceEvent::IsExpired(): fabs(deltaAngle) = %f, fMargin = %f\n", // fabs(deltaAngle), fMargin); } else { fMargin = fMarginStatic; } return fabs(deltaAngle) <= fMargin; } void CPigFaceEvent::DoDefaultExpiration() { m_pPigShip->AllStop(NULL); } ///////////////////////////////////////////////////////////////////////////// // IPigShipEvent Interface Methods STDMETHODIMP CPigFaceEvent::get_Target(BSTR* pbstrTarget) { // Initialize the [out] parameter CLEAROUT(pbstrTarget, (BSTR)NULL); // Copy the target name, if any XLock lock(this); if (m_pTarget) *pbstrTarget = CComBSTR(m_pTarget->GetName()).Detach(); else if (m_bVector) *pbstrTarget = CComBSTR(m_vector.GetString()).Detach(); // Indicate success return S_OK; } <commit_msg>guard for a crash in existing pig code<commit_after>///////////////////////////////////////////////////////////////////////////// // PigShipEvent.cpp : Implementation of the CPigShipEvent class. #include "pch.h" #include <TCLib.h> #include <..\TCAtl\ObjectMap.h> #include "Pig.h" #include "PigBehaviorScript.h" #include "PigShip.h" #include "PigShipEvent.h" ///////////////////////////////////////////////////////////////////////////// // CPigShipEvent TC_OBJECT_EXTERN_NON_CREATEABLE_IMPL(CPigShipEvent) ///////////////////////////////////////////////////////////////////////////// // Construction / Destruction HRESULT CPigShipEvent::Init(CPigShip* pPigShip, BSTR bstrTarget) { XLock lock(this); // Save the specified pig ship pointer m_pPigShip = pPigShip; // Perform default processing CPigEvent::Init(m_pPigShip->GetPig()->GetActiveBehavior()->GetMostDerived()); // Set the specified target RETURN_FAILED(SetTarget(bstrTarget)); // Generate an event name CComBSTR bstrFmt; _VERIFYE(bstrFmt.LoadString(IDS_FMT_SHIPEVENT_NAME)); OLECHAR szName[_MAX_PATH]; swprintf(szName, bstrFmt, m_pOwner->GetNextEventNumber()); RETURN_FAILED(put_Name(CComBSTR(szName))); // Indicate success return S_OK; } ///////////////////////////////////////////////////////////////////////////// // Attributes HRESULT CPigShipEvent::SetTarget(BSTR bstrTarget) { // Resolve the specified object name into a model in the current cluster XLock lock(this); m_pTarget = FindTargetName(m_pPigShip->GetPig(), bstrTarget); if (m_pTarget) return S_OK; // Format the error message return FormattedError(IDS_E_FMT_OBJNAME, bstrTarget ? bstrTarget : L""); } ///////////////////////////////////////////////////////////////////////////// // Operations ImodelIGC* CPigShipEvent::FindTargetName(CPig* pPig, BSTR bstrTarget, bool bFriendsOnly) { ImodelIGC* pTarget = NULL; if (pPig && BSTRLen(bstrTarget)) { // Only look in the current cluster IclusterIGC* pCluster = pPig->BaseClient::GetCluster(); if (pCluster) { // Convert the BSTR to ANSI USES_CONVERSION; LPCSTR pszTarget = OLE2CA(bstrTarget); // Get the pig ship's position Vector vPig = pPig->GetShip()->GetPosition(); // Find the nearest model with the specified name float fNearest = 0.f; const ModelListIGC* pModels = pCluster->GetModels(); for (ModelLinkIGC* it = pModels->first(); it; it = it->next()) { ImodelIGC* pModel = it->data(); if (pModel) { //imago 10/14 (model can disappear here) if (0 == _stricmp(GetModelName(pModel), pszTarget)) { if (bFriendsOnly && pModel->GetSide() != pPig->BaseClient::GetSide()) { //Imago skip! 10/14 } else { float fDistance = (pModel->GetPosition() - vPig).LengthSquared(); if (!pTarget || fDistance < fNearest) { fNearest = fDistance; pTarget = pModel; } } } } } } } return pTarget; } ///////////////////////////////////////////////////////////////////////////// // Overrides bool CPigShipEvent::Pulse(bool bExpired) { // Have the ship kill us when expired if (bExpired) m_pPigShip->KillAutoAction(); // Always terminate the event when it expires return bExpired; } bool CPigShipEvent::ModelTerminated(ImodelIGC* pModelIGC) { // Ignore if the specified model is not our action target if (m_pTarget != pModelIGC) return false; // Reset the model pointer m_pTarget = NULL; // Indicate that we should be terminated return true; } ///////////////////////////////////////////////////////////////////////////// // ISupportErrorInfo Interface Methods STDMETHODIMP CPigShipEvent::InterfaceSupportsErrorInfo(REFIID riid) { static const IID* arr[] = { &IID_IPigShipEvent, }; for (int i = 0; i < sizeofArray(arr); ++i) { if (InlineIsEqualGUID(*arr[i], riid)) return S_OK; } return S_FALSE; } ///////////////////////////////////////////////////////////////////////////// // IPigShipEvent Interface Methods STDMETHODIMP CPigShipEvent::get_Target(BSTR* pbstrTarget) { // Initialize the [out] parameter CLEAROUT(pbstrTarget, (BSTR)NULL); // Copy the target name, if any XLock lock(this); if (m_pTarget) *pbstrTarget = CComBSTR(m_pTarget->GetName()).Detach(); // Indicate success return S_OK; } // // ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CPigFaceEvent // ///////////////////////////////////////////////////////////////////////////// // Construction / Destruction HRESULT CPigFaceEvent::Init(CPigShip* pPigShip, VARIANT* pvarTarget, bool bMatchUpVector) { XLock lock(this); // Save the specified pig ship pointer m_pPigShip = pPigShip; // Perform default processing CPigEvent::Init(m_pPigShip->GetPig()->GetActiveBehavior()->GetMostDerived()); // Determine which type of VARIANT was specified if (!pvarTarget) return E_POINTER; VARTYPE vt = V_VT(pvarTarget); switch (vt) { case VT_BSTR: { // Set the specified target as a named model RETURN_FAILED(SetTarget(V_BSTR(pvarTarget))); break; } case VT_DISPATCH: case VT_UNKNOWN: { // See if it's an IAGCModel IAGCModelPtr spModel(V_UNKNOWN(pvarTarget)); if (NULL != spModel) { IAGCPrivatePtr spPrivate(spModel); if (NULL == spPrivate) return E_INVALIDARG; m_pTarget = reinterpret_cast<ImodelIGC*>(spPrivate->GetIGCVoid()); } else { // See if it's an IAGCVector IAGCVectorPtr spVector(V_UNKNOWN(pvarTarget)); IAGCVectorPrivatePtr spPrivate(spVector); if (NULL == spPrivate) return E_INVALIDARG; RETURN_FAILED(spPrivate->CopyVectorTo(&m_vector)); m_bVector = true; } break; } default: return DISP_E_TYPEMISMATCH; } // Get the target's radius, if it's a model if (m_pTarget) m_fTargetRadius = m_pTarget->GetRadius() * 0.25f; // Generate an event name CComBSTR bstrFmt; _VERIFYE(bstrFmt.LoadString(IDS_FMT_SHIPEVENT_NAME)); OLECHAR szName[_MAX_PATH]; swprintf(szName, bstrFmt, m_pOwner->GetNextEventNumber()); RETURN_FAILED(put_Name(CComBSTR(szName))); // Indicate success return S_OK; } ///////////////////////////////////////////////////////////////////////////// // Overrides bool CPigFaceEvent::IsExpired() { // Get the ship object assert(m_pPigShip->GetPig()); IshipIGC* pShip = m_pPigShip->GetPig()->BaseClient::GetShip(); assert(pShip); // We are definitely expired if we are not flying if (PigState_Flying != m_pPigShip->GetPig()->GetCurrentState()) return true; // We are definitely expired if we have no target if (!m_pTarget && !m_bVector) return true; // Get the ship's current controls ControlData cd = pShip->GetControls(); // Determine the vector to face Vector vectorFace(m_bVector ? m_vector : m_pTarget->GetPosition()); // Compute the ship's new controls Vector vectorDelta(vectorFace - pShip->GetPosition()); float deltaAngle = turnToFace(vectorDelta, m_pPigShip->GetPig()->GetUpdateFraction(), pShip, &cd); // Set the ship's new controls pShip->SetControls(cd); // We expire when we are (close to) facing our target // _TRACE1("CPigFaceEvent::IsExpired(): deltaAngle = %f\n", deltaAngle); const static float fMarginStatic = fabs(RadiansFromDegrees(1.f)); float fMargin; if (m_pTarget) { fMargin = fabs(m_fTargetRadius / vectorDelta.Length()); // _TRACE2("CPigFaceEvent::IsExpired(): fabs(deltaAngle) = %f, fMargin = %f\n", // fabs(deltaAngle), fMargin); } else { fMargin = fMarginStatic; } return fabs(deltaAngle) <= fMargin; } void CPigFaceEvent::DoDefaultExpiration() { m_pPigShip->AllStop(NULL); } ///////////////////////////////////////////////////////////////////////////// // IPigShipEvent Interface Methods STDMETHODIMP CPigFaceEvent::get_Target(BSTR* pbstrTarget) { // Initialize the [out] parameter CLEAROUT(pbstrTarget, (BSTR)NULL); // Copy the target name, if any XLock lock(this); if (m_pTarget) *pbstrTarget = CComBSTR(m_pTarget->GetName()).Detach(); else if (m_bVector) *pbstrTarget = CComBSTR(m_vector.GetString()).Detach(); // Indicate success return S_OK; } <|endoftext|>
<commit_before>#include "ProfileGuidedPartitioner.hpp" #include <cstddef> #include <iostream> #include <sstream> #include <fstream> #include <stdexcept> #include <string> #include <unordered_map> #include <vector> #include <cassert> #include "metis/include/metis.h" #include "Partitioner.hpp" #include "SimulationObject.hpp" namespace warped { ProfileGuidedPartitioner::ProfileGuidedPartitioner(std::string stats_file, std::vector<float> part_weights) : stats_file_(stats_file), part_weights_(part_weights) {} std::vector<std::vector<SimulationObject*>> ProfileGuidedPartitioner::partition( const std::vector<SimulationObject*>& objects, const unsigned int num_partitions) const { if (num_partitions == 1) { return {objects}; } if (part_weights_.empty()) { part_weights_.assign(num_partitions, (float)1.0/num_partitions); } else { if (part_weights_.size() != num_partitions) { throw std::runtime_error("The number of weights must equal the number of partitions!"); } float weight_sum = 0.0; for (auto& w : part_weights_) { weight_sum += w; } if (weight_sum != 1.0) { throw std::runtime_error("The sum of partition weights must equal 1.0!"); } } std::ifstream input(stats_file_); if (!input.is_open()) { throw std::runtime_error(std::string("Could not open statistics file ") + stats_file_); } std::vector<std::vector<SimulationObject*>> objects_by_partition(num_partitions); std::vector<std::vector<idx_t>> xadj_by_partition(num_partitions); std::vector<std::vector<idx_t>> adjncy_by_partition(num_partitions); std::vector<std::vector<idx_t>> adjwgt_by_partition(num_partitions); std::vector<std::vector<unsigned int>> numbering_by_partition(num_partitions); // A map of METIS node number -> SimulationObject name that is used to // translate the metis partition info to warped partitions. std::vector<std::string> object_names(objects.size()); // METIS parameters // idx_t is a METIS typedef idx_t nvtxs = 0; // number of verticies idx_t ncon = 1; // number of constraints idx_t nparts = num_partitions; // number of partitions std::vector<idx_t> xadj; // part of the edge list std::vector<idx_t> adjncy; // part of the edge list std::vector<idx_t> adjwgt; // edge weights idx_t edgecut = 0; // output var for the final communication volume std::vector<idx_t> part(objects.size()); // output var for partition list xadj.push_back(0); int i = 0; for (std::string line; std::getline(input, line);) { if (line[0] == '%') { // Skip comment lines unless they are a map comment if (line[1] != ':') { continue; } // The first line is the file format, so store the name at i-1 object_names[i - 1] = line.substr(3); continue; } std::istringstream iss(line); if (i == 0) { int nedges, format; iss >> nvtxs >> nedges >> format; if (format != 1) { throw std::runtime_error("Graph format must be 001."); } if (static_cast<std::size_t>(nvtxs) > objects.size()) { throw std::runtime_error("Invalid statistics file for this simulation."); } } else { int vertex, weight; while (iss >> vertex >> weight) { // The metis file format counts from 1, but the API counts from 0. Cool. adjncy.push_back(vertex - 1); adjwgt.push_back(weight); } xadj.push_back(adjncy.size()); } i++; } input.close(); METIS_PartGraphKway(&nvtxs, // nvtxs &ncon, // ncon &xadj[0], // xadj &adjncy[0], // adjncy NULL, // vwgt NULL, // vsize &adjwgt[0], // adjwgt &nparts, // nparts &part_weights_[0],// tpwgts NULL, // ubvec NULL, // options &edgecut, // edgecut &part[0] // part ); // Create a map of all SimulationObject names -> pointers std::unordered_map<std::string, SimulationObject*> objects_by_name; for (auto ob: objects) { objects_by_name[ob->name_] = ob; } // Add the metis output to partitons, removing partitioned names from the // object map. Any left over objects don't have profiling data associated, // and will be partitioned uniformly. for (unsigned int i = 0; i < num_partitions; i++) { xadj_by_partition[i].push_back(0); } for (int i = 0; i < nvtxs; i++) { auto name = object_names[i]; objects_by_partition[part[i]].push_back(objects_by_name.at(name)); for (int j = xadj[i]; j < xadj[i+1]; j++) { if (part[i] == part[adjncy[j]]) { adjncy_by_partition[part[i]].push_back(adjncy[j]); adjwgt_by_partition[part[i]].push_back(adjwgt[j]); } } xadj_by_partition[part[i]].push_back(adjncy_by_partition[part[i]].size()); numbering_by_partition[part[i]].push_back((unsigned int)i); objects_by_name.erase(name); } // Add any objects that metis didn't partition unsigned int j = 0; for (auto& it : objects_by_name) { objects_by_partition[j % num_partitions].push_back(it.second); j++; } for (unsigned int i = 0; i < num_partitions; i++) { savePartition(i, objects_by_partition[i], xadj_by_partition[i], adjncy_by_partition[i], adjwgt_by_partition[i], numbering_by_partition[i]); } return objects_by_partition; } void ProfileGuidedPartitioner::savePartition(unsigned int part_id, const std::vector<SimulationObject*>& objects, const std::vector<idx_t>& xadj, const std::vector<idx_t>& adjncy, const std::vector<idx_t>& adjwgt, const std::vector<unsigned int>& numbering) const { auto num_vertices = 0; for (unsigned int k = 0; k < objects.size(); k++) { if ((xadj[k+1] - xadj[k]) > 0) num_vertices++; } auto num_edges = adjncy.size() / 2; unsigned int i = 1; std::map<unsigned int, unsigned int> new_number; for (auto& n : numbering) { new_number[n] = i++; } std::ofstream ofs("partition"+std::to_string(part_id)+".out", std::ios::trunc | std::ios::out); ofs << "%% The first line contains the following information:\n" << "%% <# of vertices> <# of edges> <file format>\n" << num_vertices << ' ' << num_edges << ' ' << "001 " << '\n' << "%% Lines that start with %: are comments that are ignored by Metis,\n" << "%% but list the WARPED object name for the Metis node described by \n" << "%% the following line.\n" << "%% The remaining lines each describe a vertex and have the following format:\n" << "%% <<neighbor> <event count>> ..."; i = 0; for (auto& ob : objects) { if ((xadj[i+1] - xadj[i]) == 0) return; ofs << "\n%: " << ob->name_ << '\n'; for (idx_t j = xadj[i]; j < xadj[i+1]; j++) { ofs << new_number[adjncy[j]] << ' ' << adjwgt[j] << ' '; } ++i; } ofs << '\n'; ofs.close(); } } // namespace warped <commit_msg>Save metis data before adding unpartitioned objects<commit_after>#include "ProfileGuidedPartitioner.hpp" #include <cstddef> #include <iostream> #include <sstream> #include <fstream> #include <stdexcept> #include <string> #include <unordered_map> #include <vector> #include <cassert> #include "metis/include/metis.h" #include "Partitioner.hpp" #include "SimulationObject.hpp" namespace warped { ProfileGuidedPartitioner::ProfileGuidedPartitioner(std::string stats_file, std::vector<float> part_weights) : stats_file_(stats_file), part_weights_(part_weights) {} std::vector<std::vector<SimulationObject*>> ProfileGuidedPartitioner::partition( const std::vector<SimulationObject*>& objects, const unsigned int num_partitions) const { if (num_partitions == 1) { return {objects}; } if (part_weights_.empty()) { part_weights_.assign(num_partitions, (float)1.0/num_partitions); } else { if (part_weights_.size() != num_partitions) { throw std::runtime_error("The number of weights must equal the number of partitions!"); } float weight_sum = 0.0; for (auto& w : part_weights_) { weight_sum += w; } if (weight_sum != 1.0) { throw std::runtime_error("The sum of partition weights must equal 1.0!"); } } std::ifstream input(stats_file_); if (!input.is_open()) { throw std::runtime_error(std::string("Could not open statistics file ") + stats_file_); } std::vector<std::vector<SimulationObject*>> objects_by_partition(num_partitions); std::vector<std::vector<idx_t>> xadj_by_partition(num_partitions); std::vector<std::vector<idx_t>> adjncy_by_partition(num_partitions); std::vector<std::vector<idx_t>> adjwgt_by_partition(num_partitions); std::vector<std::vector<unsigned int>> numbering_by_partition(num_partitions); // A map of METIS node number -> SimulationObject name that is used to // translate the metis partition info to warped partitions. std::vector<std::string> object_names(objects.size()); // METIS parameters // idx_t is a METIS typedef idx_t nvtxs = 0; // number of verticies idx_t ncon = 1; // number of constraints idx_t nparts = num_partitions; // number of partitions std::vector<idx_t> xadj; // part of the edge list std::vector<idx_t> adjncy; // part of the edge list std::vector<idx_t> adjwgt; // edge weights idx_t edgecut = 0; // output var for the final communication volume std::vector<idx_t> part(objects.size()); // output var for partition list xadj.push_back(0); int i = 0; for (std::string line; std::getline(input, line);) { if (line[0] == '%') { // Skip comment lines unless they are a map comment if (line[1] != ':') { continue; } // The first line is the file format, so store the name at i-1 object_names[i - 1] = line.substr(3); continue; } std::istringstream iss(line); if (i == 0) { int nedges, format; iss >> nvtxs >> nedges >> format; if (format != 1) { throw std::runtime_error("Graph format must be 001."); } if (static_cast<std::size_t>(nvtxs) > objects.size()) { throw std::runtime_error("Invalid statistics file for this simulation."); } } else { int vertex, weight; while (iss >> vertex >> weight) { // The metis file format counts from 1, but the API counts from 0. Cool. adjncy.push_back(vertex - 1); adjwgt.push_back(weight); } xadj.push_back(adjncy.size()); } i++; } input.close(); METIS_PartGraphKway(&nvtxs, // nvtxs &ncon, // ncon &xadj[0], // xadj &adjncy[0], // adjncy NULL, // vwgt NULL, // vsize &adjwgt[0], // adjwgt &nparts, // nparts &part_weights_[0],// tpwgts NULL, // ubvec NULL, // options &edgecut, // edgecut &part[0] // part ); // Create a map of all SimulationObject names -> pointers std::unordered_map<std::string, SimulationObject*> objects_by_name; for (auto ob: objects) { objects_by_name[ob->name_] = ob; } // Add the metis output to partitons, removing partitioned names from the // object map. Any left over objects don't have profiling data associated, // and will be partitioned uniformly. for (unsigned int i = 0; i < num_partitions; i++) { xadj_by_partition[i].push_back(0); } for (int i = 0; i < nvtxs; i++) { auto name = object_names[i]; objects_by_partition[part[i]].push_back(objects_by_name.at(name)); for (int j = xadj[i]; j < xadj[i+1]; j++) { if (part[i] == part[adjncy[j]]) { adjncy_by_partition[part[i]].push_back(adjncy[j]); adjwgt_by_partition[part[i]].push_back(adjwgt[j]); } } xadj_by_partition[part[i]].push_back(adjncy_by_partition[part[i]].size()); numbering_by_partition[part[i]].push_back((unsigned int)i); objects_by_name.erase(name); } for (unsigned int i = 0; i < num_partitions; i++) { savePartition(i, objects_by_partition[i], xadj_by_partition[i], adjncy_by_partition[i], adjwgt_by_partition[i], numbering_by_partition[i]); } // Add any objects that metis didn't partition unsigned int j = 0; for (auto& it : objects_by_name) { objects_by_partition[j % num_partitions].push_back(it.second); j++; } return objects_by_partition; } void ProfileGuidedPartitioner::savePartition(unsigned int part_id, const std::vector<SimulationObject*>& objects, const std::vector<idx_t>& xadj, const std::vector<idx_t>& adjncy, const std::vector<idx_t>& adjwgt, const std::vector<unsigned int>& numbering) const { auto num_vertices = 0; for (unsigned int k = 0; k < objects.size(); k++) { if ((xadj[k+1] - xadj[k]) > 0) num_vertices++; } auto num_edges = adjncy.size() / 2; unsigned int i = 1; std::map<unsigned int, unsigned int> new_number; for (auto& n : numbering) { new_number[n] = i++; } std::ofstream ofs("partition"+std::to_string(part_id)+".out", std::ios::trunc | std::ios::out); ofs << "%% The first line contains the following information:\n" << "%% <# of vertices> <# of edges> <file format>\n" << num_vertices << ' ' << num_edges << ' ' << "001 " << '\n' << "%% Lines that start with %: are comments that are ignored by Metis,\n" << "%% but list the WARPED object name for the Metis node described by \n" << "%% the following line.\n" << "%% The remaining lines each describe a vertex and have the following format:\n" << "%% <<neighbor> <event count>> ..."; i = 0; for (auto& ob : objects) { if ((xadj[i+1] - xadj[i]) == 0) return; ofs << "\n%: " << ob->name_ << '\n'; for (idx_t j = xadj[i]; j < xadj[i+1]; j++) { ofs << new_number[adjncy[j]] << ' ' << adjwgt[j] << ' '; } ++i; } ofs << '\n'; ofs.close(); } } // namespace warped <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: loadlisteneradapter.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:19:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef EXTENSIONS_BIB_LOADLISTENERADAPTER_HXX #define EXTENSIONS_BIB_LOADLISTENERADAPTER_HXX #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _COM_SUN_STAR_FORM_XLOADABLE_HPP_ #include <com/sun/star/form/XLoadable.hpp> #endif //......................................................................... namespace bib { //......................................................................... class OComponentAdapterBase; //===================================================================== //= OComponentListener //===================================================================== class OComponentListener { friend class OComponentAdapterBase; private: OComponentAdapterBase* m_pAdapter; ::osl::Mutex& m_rMutex; protected: OComponentListener( ::osl::Mutex& _rMutex ) :m_rMutex( _rMutex ) ,m_pAdapter( NULL ) { } virtual ~OComponentListener(); // XEventListener equivalents virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource ) throw( ::com::sun::star::uno::RuntimeException ); protected: void setAdapter( OComponentAdapterBase* _pAdapter ); }; //===================================================================== //= OComponentAdapterBase //===================================================================== class OComponentAdapterBase { friend class OComponentListener; private: ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > m_xComponent; OComponentListener* m_pListener; sal_Int32 m_nLockCount; sal_Bool m_bListening : 1; sal_Bool m_bAutoRelease : 1; // impl method for dispose - virtual, 'cause you at least need to remove the listener from the broadcaster virtual void disposing() = 0; protected: // attribute access for derivees const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& getComponent() const { return m_xComponent; } OComponentListener* getListener() { return m_pListener; } // to be called by derivees which started listening at the component virtual void startComponentListening() = 0; virtual ~OComponentAdapterBase(); public: OComponentAdapterBase( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& _rxComp, sal_Bool _bAutoRelease = sal_True ); // late construction // can be called from within you ctor, to have you're object fully initialized at the moment of // the call (which would not be the case when calling this ctor) void Init( OComponentListener* _pListener ); // base for ref-counting, implemented by OComponentAdapter virtual void SAL_CALL acquire( ) throw () = 0; virtual void SAL_CALL release( ) throw () = 0; // helper /// incremental lock void lock(); /// incremental unlock void unlock(); /// get the lock count sal_Int32 locked() const { return m_nLockCount; } /// dispose the object - stop listening and such void dispose(); protected: // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw( ::com::sun::star::uno::RuntimeException); }; //===================================================================== //= OLoadListener //===================================================================== class OLoadListener : public OComponentListener { friend class OLoadListenerAdapter; protected: OLoadListener( ::osl::Mutex& _rMutex ) : OComponentListener( _rMutex ) { } // XLoadListener equivalents virtual void _loaded( const ::com::sun::star::lang::EventObject& aEvent ) = 0; virtual void _unloading( const ::com::sun::star::lang::EventObject& aEvent ) = 0; virtual void _unloaded( const ::com::sun::star::lang::EventObject& aEvent ) = 0; virtual void _reloading( const ::com::sun::star::lang::EventObject& aEvent ) = 0; virtual void _reloaded( const ::com::sun::star::lang::EventObject& aEvent ) = 0; }; //===================================================================== //= OLoadListenerAdapter //===================================================================== typedef ::cppu::WeakImplHelper1< ::com::sun::star::form::XLoadListener > OLoadListenerAdapter_Base; class OLoadListenerAdapter :public OLoadListenerAdapter_Base ,public OComponentAdapterBase { protected: OLoadListener* getLoadListener( ) { return static_cast< OLoadListener* >( getListener() ); } protected: virtual void disposing(); virtual void startComponentListening(); public: OLoadListenerAdapter( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadable >& _rxLoadable, sal_Bool _bAutoRelease = sal_True ); virtual void SAL_CALL acquire( ) throw (); virtual void SAL_CALL release( ) throw (); protected: // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& _rSource ) throw( ::com::sun::star::uno::RuntimeException); // XLoadListener virtual void SAL_CALL loaded( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL unloading( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL unloaded( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL reloading( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL reloaded( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException); }; //......................................................................... } // namespace bib //......................................................................... #endif // EXTENSIONS_BIB_LOADLISTENERADAPTER_HXX <commit_msg>INTEGRATION: CWS wae4extensions (1.5.388); FILE MERGED 2007/09/27 07:18:23 fs 1.5.388.1: #i81612# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: loadlisteneradapter.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: ihi $ $Date: 2008-01-14 14:40:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef EXTENSIONS_BIB_LOADLISTENERADAPTER_HXX #define EXTENSIONS_BIB_LOADLISTENERADAPTER_HXX #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _COM_SUN_STAR_FORM_XLOADABLE_HPP_ #include <com/sun/star/form/XLoadable.hpp> #endif //......................................................................... namespace bib { //......................................................................... class OComponentAdapterBase; //===================================================================== //= OComponentListener //===================================================================== class OComponentListener { friend class OComponentAdapterBase; private: OComponentAdapterBase* m_pAdapter; ::osl::Mutex& m_rMutex; protected: OComponentListener( ::osl::Mutex& _rMutex ) :m_pAdapter( NULL ) ,m_rMutex( _rMutex ) { } virtual ~OComponentListener(); // XEventListener equivalents virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource ) throw( ::com::sun::star::uno::RuntimeException ); protected: void setAdapter( OComponentAdapterBase* _pAdapter ); }; //===================================================================== //= OComponentAdapterBase //===================================================================== class OComponentAdapterBase { friend class OComponentListener; private: ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > m_xComponent; OComponentListener* m_pListener; sal_Int32 m_nLockCount; sal_Bool m_bListening : 1; sal_Bool m_bAutoRelease : 1; // impl method for dispose - virtual, 'cause you at least need to remove the listener from the broadcaster virtual void disposing() = 0; protected: // attribute access for derivees const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& getComponent() const { return m_xComponent; } OComponentListener* getListener() { return m_pListener; } // to be called by derivees which started listening at the component virtual void startComponentListening() = 0; virtual ~OComponentAdapterBase(); public: OComponentAdapterBase( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& _rxComp, sal_Bool _bAutoRelease = sal_True ); // late construction // can be called from within you ctor, to have you're object fully initialized at the moment of // the call (which would not be the case when calling this ctor) void Init( OComponentListener* _pListener ); // base for ref-counting, implemented by OComponentAdapter virtual void SAL_CALL acquire( ) throw () = 0; virtual void SAL_CALL release( ) throw () = 0; // helper /// incremental lock void lock(); /// incremental unlock void unlock(); /// get the lock count sal_Int32 locked() const { return m_nLockCount; } /// dispose the object - stop listening and such void dispose(); protected: // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw( ::com::sun::star::uno::RuntimeException); }; //===================================================================== //= OLoadListener //===================================================================== class OLoadListener : public OComponentListener { friend class OLoadListenerAdapter; protected: OLoadListener( ::osl::Mutex& _rMutex ) : OComponentListener( _rMutex ) { } // XLoadListener equivalents virtual void _loaded( const ::com::sun::star::lang::EventObject& aEvent ) = 0; virtual void _unloading( const ::com::sun::star::lang::EventObject& aEvent ) = 0; virtual void _unloaded( const ::com::sun::star::lang::EventObject& aEvent ) = 0; virtual void _reloading( const ::com::sun::star::lang::EventObject& aEvent ) = 0; virtual void _reloaded( const ::com::sun::star::lang::EventObject& aEvent ) = 0; }; //===================================================================== //= OLoadListenerAdapter //===================================================================== typedef ::cppu::WeakImplHelper1< ::com::sun::star::form::XLoadListener > OLoadListenerAdapter_Base; class OLoadListenerAdapter :public OLoadListenerAdapter_Base ,public OComponentAdapterBase { protected: OLoadListener* getLoadListener( ) { return static_cast< OLoadListener* >( getListener() ); } protected: virtual void disposing(); virtual void startComponentListening(); public: OLoadListenerAdapter( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadable >& _rxLoadable, sal_Bool _bAutoRelease = sal_True ); virtual void SAL_CALL acquire( ) throw (); virtual void SAL_CALL release( ) throw (); protected: // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& _rSource ) throw( ::com::sun::star::uno::RuntimeException); // XLoadListener virtual void SAL_CALL loaded( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL unloading( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL unloaded( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL reloading( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL reloaded( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException); }; //......................................................................... } // namespace bib //......................................................................... #endif // EXTENSIONS_BIB_LOADLISTENERADAPTER_HXX <|endoftext|>
<commit_before>// Copyright (c) 2016-2018 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/test_syscoin_services.h> #include <util/time.h> #include <rpc/server.h> #include <services/asset.h> #include <base58.h> #include <chainparams.h> #include <boost/test/unit_test.hpp> #include <iterator> #include <key.h> using namespace std; BOOST_GLOBAL_FIXTURE( SyscoinTestingSetup ); BOOST_FIXTURE_TEST_SUITE(syscoin_asset_allocation_tests, BasicSyscoinTestingSetup) BOOST_AUTO_TEST_CASE(generate_asset_allocation_address_sync) { UniValue r; printf("Running generate_asset_allocation_address_sync...\n"); GenerateBlocks(5); string newaddress = GetNewFundedAddress("node1"); BOOST_CHECK_NO_THROW(r = CallExtRPC("node1", "getnewaddress")); string newaddressreceiver = r.get_str(); string guid = AssetNew("node1", newaddress, "data", "''", "8", "10000", "1000000"); AssetSend("node1", guid, "\"[{\\\"address\\\":\\\"" + newaddressreceiver + "\\\",\\\"amount\\\":5000}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddressreceiver )); UniValue balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_NO_THROW(r = CallRPC("node2", "assetallocationinfo " + guid + " " + newaddressreceiver )); balance = find_value(r.get_obj(), "balance"); StopNode("node2"); StartNode("node2"); GenerateBlocks(5, "node2"); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddressreceiver )); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_NO_THROW(r = CallRPC("node2", "assetallocationinfo " + guid + " " + newaddressreceiver )); balance = find_value(r.get_obj(), "balance"); } BOOST_AUTO_TEST_CASE(generate_asset_allocation_lock) { UniValue r; printf("Running generate_asset_allocation_lock...\n"); GenerateBlocks(5); string txid; string newaddress1 = GetNewFundedAddress("node2"); string newaddress = GetNewFundedAddress("node1", txid); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "getrawtransaction " + txid + " true" )); UniValue voutArray = find_value(r.get_obj(), "vout"); int vout = 0; for(unsigned int i = 0;i<voutArray.size();i++){ UniValue scriptObj = find_value(voutArray[i].get_obj(), "scriptPubKey").get_obj(); UniValue addressesArray = find_value(scriptObj, "addresses"); for(unsigned int j = 0;j<addressesArray.size();j++){ if(addressesArray[j].get_str() == newaddress) vout = i; } } string voutstr = itostr(vout); // lock outpoint so other txs can't spend through wallet auto-selection BOOST_CHECK_NO_THROW(CallRPC("node1", "lockunspent false \"[{\\\"txid\\\":\\\"" + txid + "\\\",\\\"vout\\\":" + voutstr + "}]\"" )); string guid = AssetNew("node1", newaddress, "data","''", "8", "1", "100000"); AssetSend("node1", guid, "\"[{\\\"address\\\":\\\"" + newaddress + "\\\",\\\"amount\\\":1}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress )); UniValue balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 1 * COIN); LockAssetAllocation("node1", guid, newaddress, txid, voutstr); // unlock now to test spending BOOST_CHECK_NO_THROW(CallRPC("node1", "lockunspent true \"[{\\\"txid\\\":\\\"" + txid + "\\\",\\\"vout\\\":" + voutstr + "}]\"" )); // cannot spend as normal through sendrawtransaction BOOST_CHECK_NO_THROW(r = CallRPC("node1", "createrawtransaction \"[{\\\"txid\\\":\\\"" + txid + "\\\",\\\"vout\\\":" + voutstr + "}]\", \"[{\\\"" + newaddress1 + "\\\":0.01}]\"")); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "signrawtransactionwithwallet " + r.get_str())); string hex_str = find_value(r.get_obj(), "hex").get_str(); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "testmempoolaccept \"[\\\"" + hex_str + "\\\"]\"")); BOOST_CHECK(find_value(r.get_array()[0].get_obj(), "allowed").get_bool()); BOOST_CHECK_THROW(r = CallRPC("node1", "sendrawtransaction " + hex_str, true, false), runtime_error); string txid0 = AssetAllocationTransfer(false, "node1", guid, newaddress, "\"[{\\\"address\\\":\\\"" + newaddress1 + "\\\",\\\"amount\\\":0.11}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress1 )); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 0.11 * COIN); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "getrawtransaction " + txid0 + " true" )); UniValue vinArray = find_value(r.get_obj(), "vin"); bool found = false; for(unsigned int i = 0;i<vinArray.size();i++){ if(find_value(vinArray[i].get_obj(), "txid").get_str() == txid && find_value(vinArray[i].get_obj(), "vout").get_int() == vout){ found = true; break; } } BOOST_CHECK(found); } BOOST_AUTO_TEST_CASE(generate_asset_allocation_send_address) { UniValue r; printf("Running generate_asset_allocation_send_address...\n"); GenerateBlocks(5); GenerateBlocks(101, "node2"); string newaddress1 = GetNewFundedAddress("node1"); CallRPC("node2", "sendtoaddress " + newaddress1 + " 1", true, false); CallRPC("node2", "sendtoaddress " + newaddress1 + " 1", true, false); GenerateBlocks(5); GenerateBlocks(5, "node2"); BOOST_CHECK_NO_THROW(r = CallExtRPC("node1", "getnewaddress")); string newaddress2 = r.get_str(); string guid = AssetNew("node1", newaddress1, "data","''", "8", "1", "100000"); AssetSend("node1", guid, "\"[{\\\"address\\\":\\\"" + newaddress1 + "\\\",\\\"amount\\\":1}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress1 )); UniValue balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 1 * COIN); string txid0 = AssetAllocationTransfer(false, "node1", guid, newaddress1, "\"[{\\\"address\\\":\\\"" + newaddress2 + "\\\",\\\"amount\\\":0.11}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress2 )); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 0.11 * COIN); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); // send using zdag string txid1 = AssetAllocationTransfer(true, "node1", guid, newaddress1, "\"[{\\\"address\\\":\\\"" + newaddress2 + "\\\",\\\"amount\\\":0.12}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress2)); balance = find_value(r.get_obj(), "balance_zdag"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 0.23 * COIN); // non zdag cannot be found since it was already mined, but ends up briefly in conflict state because sender is conflicted BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // first tx should have to wait 1 sec for good status BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // check just sender BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // wait for 1 second as required by unit test MilliSleep(1000); // second send string txid2 = AssetAllocationTransfer(true, "node1", guid, newaddress1, "\"[{\\\"address\\\":\\\"" + newaddress2 + "\\\",\\\"amount\\\":0.13}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress2 )); balance = find_value(r.get_obj(), "balance_zdag"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 0.36 * COIN); // sender is conflicted so txid0 is conflicted by extension even if its not found BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // first ones now OK because it was found explicitly BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // second one hasn't waited enough time yet BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // check just sender BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // wait for 1.5 second to clear minor warning status MilliSleep(1500); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // check just sender as well BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // after pow, should get not found on all of them GenerateBlocks(1); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); // check just sender as well BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); ECC_Stop(); } BOOST_AUTO_TEST_SUITE_END () <commit_msg>spaces<commit_after>// Copyright (c) 2016-2018 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/test_syscoin_services.h> #include <util/time.h> #include <rpc/server.h> #include <services/asset.h> #include <base58.h> #include <chainparams.h> #include <boost/test/unit_test.hpp> #include <iterator> #include <key.h> using namespace std; BOOST_GLOBAL_FIXTURE( SyscoinTestingSetup ); BOOST_FIXTURE_TEST_SUITE(syscoin_asset_allocation_tests, BasicSyscoinTestingSetup) BOOST_AUTO_TEST_CASE(generate_asset_allocation_address_sync) { UniValue r; printf("Running generate_asset_allocation_address_sync...\n"); GenerateBlocks(5); string newaddress = GetNewFundedAddress("node1"); BOOST_CHECK_NO_THROW(r = CallExtRPC("node1", "getnewaddress")); string newaddressreceiver = r.get_str(); string guid = AssetNew("node1", newaddress, "data", "''", "8", "10000", "1000000"); AssetSend("node1", guid, "\"[{\\\"address\\\":\\\"" + newaddressreceiver + "\\\",\\\"amount\\\":5000}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddressreceiver )); UniValue balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_NO_THROW(r = CallRPC("node2", "assetallocationinfo " + guid + " " + newaddressreceiver )); balance = find_value(r.get_obj(), "balance"); StopNode("node2"); StartNode("node2"); GenerateBlocks(5, "node2"); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddressreceiver )); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_NO_THROW(r = CallRPC("node2", "assetallocationinfo " + guid + " " + newaddressreceiver )); balance = find_value(r.get_obj(), "balance"); } BOOST_AUTO_TEST_CASE(generate_asset_allocation_lock) { UniValue r; printf("Running generate_asset_allocation_lock...\n"); GenerateBlocks(5); string txid; string newaddress1 = GetNewFundedAddress("node2"); string newaddress = GetNewFundedAddress("node1", txid); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "getrawtransaction " + txid + " true" )); UniValue voutArray = find_value(r.get_obj(), "vout"); int vout = 0; for(unsigned int i = 0;i<voutArray.size();i++){ UniValue scriptObj = find_value(voutArray[i].get_obj(), "scriptPubKey").get_obj(); UniValue addressesArray = find_value(scriptObj, "addresses"); for(unsigned int j = 0;j<addressesArray.size();j++){ if(addressesArray[j].get_str() == newaddress) vout = i; } } string voutstr = itostr(vout); // lock outpoint so other txs can't spend through wallet auto-selection BOOST_CHECK_NO_THROW(CallRPC("node1", "lockunspent false \"[{\\\"txid\\\":\\\"" + txid + "\\\",\\\"vout\\\":" + voutstr + "}]\"" )); string guid = AssetNew("node1", newaddress, "data","''", "8", "1", "100000"); AssetSend("node1", guid, "\"[{\\\"address\\\":\\\"" + newaddress + "\\\",\\\"amount\\\":1}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress )); UniValue balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 1 * COIN); LockAssetAllocation("node1", guid, newaddress, txid, voutstr); // unlock now to test spending BOOST_CHECK_NO_THROW(CallRPC("node1", "lockunspent true \"[{\\\"txid\\\":\\\"" + txid + "\\\",\\\"vout\\\":" + voutstr + "}]\"" )); // cannot spend as normal through sendrawtransaction BOOST_CHECK_NO_THROW(r = CallRPC("node1", "createrawtransaction \"[{\\\"txid\\\":\\\"" + txid + "\\\",\\\"vout\\\":" + voutstr + "}]\", \"[{\\\"" + newaddress1 + "\\\":0.01}]\"")); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "signrawtransactionwithwallet " + r.get_str())); string hex_str = find_value(r.get_obj(), "hex").get_str(); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "testmempoolaccept \"[\\\"" + hex_str + "\\\"]\"")); BOOST_CHECK(find_value(r.get_array()[0].get_obj(), "allowed").get_bool()); BOOST_CHECK_THROW(r = CallRPC("node1", "sendrawtransaction " + hex_str, true, false), runtime_error); string txid0 = AssetAllocationTransfer(false, "node1", guid, newaddress, "\"[{\\\"address\\\":\\\"" + newaddress1 + "\\\",\\\"amount\\\":0.11}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress1 )); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 0.11 * COIN); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "getrawtransaction " + txid0 + " true" )); UniValue vinArray = find_value(r.get_obj(), "vin"); bool found = false; for(unsigned int i = 0;i<vinArray.size();i++){ if(find_value(vinArray[i].get_obj(), "txid").get_str() == txid && find_value(vinArray[i].get_obj(), "vout").get_int() == vout){ found = true; break; } } BOOST_CHECK(found); } BOOST_AUTO_TEST_CASE(generate_asset_allocation_send_address) { UniValue r; printf("Running generate_asset_allocation_send_address...\n"); GenerateBlocks(5); GenerateBlocks(101, "node2"); string newaddress1 = GetNewFundedAddress("node1"); CallRPC("node2", "sendtoaddress " + newaddress1 + " 1", true, false); CallRPC("node2", "sendtoaddress " + newaddress1 + " 1", true, false); GenerateBlocks(5); GenerateBlocks(5, "node2"); BOOST_CHECK_NO_THROW(r = CallExtRPC("node1", "getnewaddress")); string newaddress2 = r.get_str(); string guid = AssetNew("node1", newaddress1, "data","''", "8", "1", "100000"); AssetSend("node1", guid, "\"[{\\\"address\\\":\\\"" + newaddress1 + "\\\",\\\"amount\\\":1}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress1 )); UniValue balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 1 * COIN); string txid0 = AssetAllocationTransfer(false, "node1", guid, newaddress1, "\"[{\\\"address\\\":\\\"" + newaddress2 + "\\\",\\\"amount\\\":0.11}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress2 )); balance = find_value(r.get_obj(), "balance"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 0.11 * COIN); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); // send using zdag string txid1 = AssetAllocationTransfer(true, "node1", guid, newaddress1, "\"[{\\\"address\\\":\\\"" + newaddress2 + "\\\",\\\"amount\\\":0.12}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress2)); balance = find_value(r.get_obj(), "balance_zdag"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 0.23 * COIN); // non zdag cannot be found since it was already mined, but ends up briefly in conflict state because sender is conflicted BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // first tx should have to wait 1 sec for good status BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // check just sender BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // wait for 1 second as required by unit test MilliSleep(1000); // second send string txid2 = AssetAllocationTransfer(true, "node1", guid, newaddress1, "\"[{\\\"address\\\":\\\"" + newaddress2 + "\\\",\\\"amount\\\":0.13}]\""); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationinfo " + guid + " " + newaddress2 )); balance = find_value(r.get_obj(), "balance_zdag"); BOOST_CHECK_EQUAL(AssetAmountFromValue(balance, 8), 0.36 * COIN); // sender is conflicted so txid0 is conflicted by extension even if its not found BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // first ones now OK because it was found explicitly BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // second one hasn't waited enough time yet BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // check just sender BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_MINOR_CONFLICT); // wait for 1.5 second to clear minor warning status MilliSleep(1500); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // check just sender as well BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_STATUS_OK); // after pow, should get not found on all of them GenerateBlocks(1); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid0)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid1)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " " + txid2)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); // check just sender as well BOOST_CHECK_NO_THROW(r = CallRPC("node1", "assetallocationsenderstatus " + guid + " " + newaddress1 + " ''")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "status").get_int(), ZDAG_NOT_FOUND); ECC_Stop(); } BOOST_AUTO_TEST_SUITE_END () <|endoftext|>
<commit_before>/* RawSpeed - RAW file decoder. Copyright (C) 2017 Roman Lebedev 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 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "io/Buffer.h" // for Buffer #include "io/FileReader.h" // for FileReader #include <cstdint> // for uint8_t #include <cstdlib> // for EXIT_SUCCESS, size_t #include <iostream> // for operator<<, cout, ostream #include <memory> // for unique_ptr extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size); static int usage() { std::cout << "This is just a placeholder.\nFor fuzzers to actually function, " "you need to build rawspeed with clang compiler, with FUZZ " "build type.\n"; return EXIT_SUCCESS; } static void process(const char* filename) { rawspeed::FileReader reader(filename); auto map(reader.readFile()); LLVMFuzzerTestOneInput(map->getData(0, map->getSize()), map->getSize()); } int main(int argc, char** argv) { if (1 == argc) return usage(); #ifdef _OPENMP #pragma omp parallel for default(shared) schedule(static) #endif for (int i = 1; i < argc; ++i) process(argv[i]); return EXIT_SUCCESS; } <commit_msg>libFuzzer_dummy_main.c: process(): do catch IOException<commit_after>/* RawSpeed - RAW file decoder. Copyright (C) 2017 Roman Lebedev 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 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "io/Buffer.h" // for Buffer #include "io/FileReader.h" // for FileReader #include "io/IOException.h" // for IOException #include <cstdint> // for uint8_t #include <cstdlib> // for EXIT_SUCCESS, size_t #include <iostream> // for operator<<, cout, ostream #include <memory> // for unique_ptr extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size); static int usage() { std::cout << "This is just a placeholder.\nFor fuzzers to actually function, " "you need to build rawspeed with clang compiler, with FUZZ " "build type.\n"; return EXIT_SUCCESS; } static void process(const char* filename) { try { rawspeed::FileReader reader(filename); auto map(reader.readFile()); LLVMFuzzerTestOneInput(map->getData(0, map->getSize()), map->getSize()); } catch (rawspeed::IOException&) { // failed to read the file for some reason. // just ignore it. return; } } int main(int argc, char** argv) { if (1 == argc) return usage(); #ifdef _OPENMP #pragma omp parallel for default(shared) schedule(static) #endif for (int i = 1; i < argc; ++i) process(argv[i]); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: namedvaluecollection.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2007-06-27 14:55:20 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_comphelper.hxx" #ifndef COMPHELPER_NAMEDVALUECOLLECTION_HXX #include <comphelper/namedvaluecollection.hxx> #endif /** === begin UNO includes === **/ #ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_ #include <com/sun/star/beans/NamedValue.hpp> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif /** === end UNO includes === **/ #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <hash_map> //........................................................................ namespace comphelper { //........................................................................ /** === begin UNO using === **/ using ::com::sun::star::uno::Any; using ::com::sun::star::uno::Sequence; using ::com::sun::star::beans::PropertyValue; using ::com::sun::star::beans::NamedValue; using ::com::sun::star::uno::Type; using ::com::sun::star::uno::cpp_acquire; using ::com::sun::star::uno::cpp_release; using ::com::sun::star::uno::cpp_queryInterface; using ::com::sun::star::lang::IllegalArgumentException; using ::com::sun::star::beans::NamedValue; /** === end UNO using === **/ //==================================================================== //= NamedValueCollection_Impl //==================================================================== typedef ::std::hash_map< ::rtl::OUString, Any, ::rtl::OUStringHash > NamedValueRepository; struct NamedValueCollection_Impl { NamedValueRepository aValues; }; //==================================================================== //= NamedValueCollection //==================================================================== //-------------------------------------------------------------------- NamedValueCollection::NamedValueCollection() :m_pImpl( new NamedValueCollection_Impl ) { } //-------------------------------------------------------------------- NamedValueCollection::NamedValueCollection( const Sequence< Any >& _rArguments ) :m_pImpl( new NamedValueCollection_Impl ) { impl_assign( _rArguments ); } //-------------------------------------------------------------------- NamedValueCollection::NamedValueCollection( const Sequence< PropertyValue >& _rArguments ) :m_pImpl( new NamedValueCollection_Impl ) { impl_assign( _rArguments ); } //-------------------------------------------------------------------- NamedValueCollection::NamedValueCollection( const Sequence< NamedValue >& _rArguments ) :m_pImpl( new NamedValueCollection_Impl ) { impl_assign( _rArguments ); } //-------------------------------------------------------------------- NamedValueCollection::~NamedValueCollection() { } //-------------------------------------------------------------------- size_t NamedValueCollection::size() const { return m_pImpl->aValues.size(); } //-------------------------------------------------------------------- bool NamedValueCollection::empty() const { return m_pImpl->aValues.empty(); } //-------------------------------------------------------------------- void NamedValueCollection::impl_assign( const Sequence< Any >& _rArguments ) { { NamedValueRepository aEmpty; m_pImpl->aValues.swap( aEmpty ); } PropertyValue aPropertyValue; NamedValue aNamedValue; const Any* pArgument = _rArguments.getConstArray(); const Any* pArgumentEnd = _rArguments.getConstArray() + _rArguments.getLength(); for ( ; pArgument != pArgumentEnd; ++pArgument ) { if ( *pArgument >>= aPropertyValue ) m_pImpl->aValues[ aPropertyValue.Name ] = aPropertyValue.Value; else if ( *pArgument >>= aNamedValue ) m_pImpl->aValues[ aNamedValue.Name ] = aNamedValue.Value; else OSL_ENSURE( !pArgument->hasValue(), "NamedValueCollection::impl_assign: encountered a value which I cannot handle!" ); } } //-------------------------------------------------------------------- void NamedValueCollection::impl_assign( const Sequence< PropertyValue >& _rArguments ) { { NamedValueRepository aEmpty; m_pImpl->aValues.swap( aEmpty ); } const PropertyValue* pArgument = _rArguments.getConstArray(); const PropertyValue* pArgumentEnd = _rArguments.getConstArray() + _rArguments.getLength(); for ( ; pArgument != pArgumentEnd; ++pArgument ) m_pImpl->aValues[ pArgument->Name ] = pArgument->Value; } //-------------------------------------------------------------------- void NamedValueCollection::impl_assign( const Sequence< NamedValue >& _rArguments ) { { NamedValueRepository aEmpty; m_pImpl->aValues.swap( aEmpty ); } const NamedValue* pArgument = _rArguments.getConstArray(); const NamedValue* pArgumentEnd = _rArguments.getConstArray() + _rArguments.getLength(); for ( ; pArgument != pArgumentEnd; ++pArgument ) m_pImpl->aValues[ pArgument->Name ] = pArgument->Value; } //-------------------------------------------------------------------- bool NamedValueCollection::get_ensureType( const ::rtl::OUString& _rValueName, void* _pValueLocation, const Type& _rExpectedValueType ) const { NamedValueRepository::const_iterator pos = m_pImpl->aValues.find( _rValueName ); if ( pos != m_pImpl->aValues.end() ) { if ( uno_type_assignData( _pValueLocation, _rExpectedValueType.getTypeLibType(), const_cast< void* >( pos->second.getValue() ), pos->second.getValueType().getTypeLibType(), reinterpret_cast< uno_QueryInterfaceFunc >( cpp_queryInterface ), reinterpret_cast< uno_AcquireFunc >( cpp_acquire ), reinterpret_cast< uno_ReleaseFunc >( cpp_release ) ) ) // argument exists, and could be extracted return true; // argument exists, but is of wrong type ::rtl::OUStringBuffer aBuffer; aBuffer.appendAscii( "Invalid value type for '" ); aBuffer.append ( _rValueName ); aBuffer.appendAscii( "'.\nExpected: " ); aBuffer.append ( _rExpectedValueType.getTypeName() ); aBuffer.appendAscii( "\nFound: " ); aBuffer.append ( pos->second.getValueType().getTypeName() ); throw IllegalArgumentException( aBuffer.makeStringAndClear(), NULL, 0 ); } // argument does not exist return false; } //-------------------------------------------------------------------- const Any& NamedValueCollection::impl_get( const ::rtl::OUString& _rValueName ) const { NamedValueRepository::const_iterator pos = m_pImpl->aValues.find( _rValueName ); if ( pos != m_pImpl->aValues.end() ) return pos->second; static Any aEmptyDefault; return aEmptyDefault; } //-------------------------------------------------------------------- bool NamedValueCollection::impl_has( const ::rtl::OUString& _rValueName ) const { NamedValueRepository::const_iterator pos = m_pImpl->aValues.find( _rValueName ); return ( pos != m_pImpl->aValues.end() ); } //-------------------------------------------------------------------- bool NamedValueCollection::impl_remove( const ::rtl::OUString& _rValueName ) { NamedValueRepository::iterator pos = m_pImpl->aValues.find( _rValueName ); if ( pos == m_pImpl->aValues.end() ) return false; m_pImpl->aValues.erase( pos ); return true; } //........................................................................ } // namespace comphelper //........................................................................ <commit_msg>INTEGRATION: CWS dba24c (1.7.40); FILE MERGED 2007/10/09 21:10:50 fs 1.7.40.1: #i82110#: +put / +operator >>=<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: namedvaluecollection.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: ihi $ $Date: 2007-11-21 16:53:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_comphelper.hxx" #ifndef COMPHELPER_NAMEDVALUECOLLECTION_HXX #include <comphelper/namedvaluecollection.hxx> #endif /** === begin UNO includes === **/ #include <com/sun/star/beans/NamedValue.hpp> #include <com/sun/star/lang/IllegalArgumentException.hpp> #include <com/sun/star/beans/PropertyState.hpp> /** === end UNO includes === **/ #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <hash_map> #include <functional> #include <algorithm> //........................................................................ namespace comphelper { //........................................................................ /** === begin UNO using === **/ using ::com::sun::star::uno::Any; using ::com::sun::star::uno::Sequence; using ::com::sun::star::beans::PropertyValue; using ::com::sun::star::beans::NamedValue; using ::com::sun::star::uno::Type; using ::com::sun::star::uno::cpp_acquire; using ::com::sun::star::uno::cpp_release; using ::com::sun::star::uno::cpp_queryInterface; using ::com::sun::star::lang::IllegalArgumentException; using ::com::sun::star::beans::NamedValue; using ::com::sun::star::beans::PropertyState_DIRECT_VALUE; /** === end UNO using === **/ //==================================================================== //= NamedValueCollection_Impl //==================================================================== typedef ::std::hash_map< ::rtl::OUString, Any, ::rtl::OUStringHash > NamedValueRepository; struct NamedValueCollection_Impl { NamedValueRepository aValues; }; //==================================================================== //= NamedValueCollection //==================================================================== //-------------------------------------------------------------------- NamedValueCollection::NamedValueCollection() :m_pImpl( new NamedValueCollection_Impl ) { } //-------------------------------------------------------------------- NamedValueCollection::NamedValueCollection( const Sequence< Any >& _rArguments ) :m_pImpl( new NamedValueCollection_Impl ) { impl_assign( _rArguments ); } //-------------------------------------------------------------------- NamedValueCollection::NamedValueCollection( const Sequence< PropertyValue >& _rArguments ) :m_pImpl( new NamedValueCollection_Impl ) { impl_assign( _rArguments ); } //-------------------------------------------------------------------- NamedValueCollection::NamedValueCollection( const Sequence< NamedValue >& _rArguments ) :m_pImpl( new NamedValueCollection_Impl ) { impl_assign( _rArguments ); } //-------------------------------------------------------------------- NamedValueCollection::~NamedValueCollection() { } //-------------------------------------------------------------------- size_t NamedValueCollection::size() const { return m_pImpl->aValues.size(); } //-------------------------------------------------------------------- bool NamedValueCollection::empty() const { return m_pImpl->aValues.empty(); } //-------------------------------------------------------------------- void NamedValueCollection::impl_assign( const Sequence< Any >& _rArguments ) { { NamedValueRepository aEmpty; m_pImpl->aValues.swap( aEmpty ); } PropertyValue aPropertyValue; NamedValue aNamedValue; const Any* pArgument = _rArguments.getConstArray(); const Any* pArgumentEnd = _rArguments.getConstArray() + _rArguments.getLength(); for ( ; pArgument != pArgumentEnd; ++pArgument ) { if ( *pArgument >>= aPropertyValue ) m_pImpl->aValues[ aPropertyValue.Name ] = aPropertyValue.Value; else if ( *pArgument >>= aNamedValue ) m_pImpl->aValues[ aNamedValue.Name ] = aNamedValue.Value; else OSL_ENSURE( !pArgument->hasValue(), "NamedValueCollection::impl_assign: encountered a value which I cannot handle!" ); } } //-------------------------------------------------------------------- void NamedValueCollection::impl_assign( const Sequence< PropertyValue >& _rArguments ) { { NamedValueRepository aEmpty; m_pImpl->aValues.swap( aEmpty ); } const PropertyValue* pArgument = _rArguments.getConstArray(); const PropertyValue* pArgumentEnd = _rArguments.getConstArray() + _rArguments.getLength(); for ( ; pArgument != pArgumentEnd; ++pArgument ) m_pImpl->aValues[ pArgument->Name ] = pArgument->Value; } //-------------------------------------------------------------------- void NamedValueCollection::impl_assign( const Sequence< NamedValue >& _rArguments ) { { NamedValueRepository aEmpty; m_pImpl->aValues.swap( aEmpty ); } const NamedValue* pArgument = _rArguments.getConstArray(); const NamedValue* pArgumentEnd = _rArguments.getConstArray() + _rArguments.getLength(); for ( ; pArgument != pArgumentEnd; ++pArgument ) m_pImpl->aValues[ pArgument->Name ] = pArgument->Value; } //-------------------------------------------------------------------- bool NamedValueCollection::get_ensureType( const ::rtl::OUString& _rValueName, void* _pValueLocation, const Type& _rExpectedValueType ) const { NamedValueRepository::const_iterator pos = m_pImpl->aValues.find( _rValueName ); if ( pos != m_pImpl->aValues.end() ) { if ( uno_type_assignData( _pValueLocation, _rExpectedValueType.getTypeLibType(), const_cast< void* >( pos->second.getValue() ), pos->second.getValueType().getTypeLibType(), reinterpret_cast< uno_QueryInterfaceFunc >( cpp_queryInterface ), reinterpret_cast< uno_AcquireFunc >( cpp_acquire ), reinterpret_cast< uno_ReleaseFunc >( cpp_release ) ) ) // argument exists, and could be extracted return true; // argument exists, but is of wrong type ::rtl::OUStringBuffer aBuffer; aBuffer.appendAscii( "Invalid value type for '" ); aBuffer.append ( _rValueName ); aBuffer.appendAscii( "'.\nExpected: " ); aBuffer.append ( _rExpectedValueType.getTypeName() ); aBuffer.appendAscii( "\nFound: " ); aBuffer.append ( pos->second.getValueType().getTypeName() ); throw IllegalArgumentException( aBuffer.makeStringAndClear(), NULL, 0 ); } // argument does not exist return false; } //-------------------------------------------------------------------- const Any& NamedValueCollection::impl_get( const ::rtl::OUString& _rValueName ) const { NamedValueRepository::const_iterator pos = m_pImpl->aValues.find( _rValueName ); if ( pos != m_pImpl->aValues.end() ) return pos->second; static Any aEmptyDefault; return aEmptyDefault; } //-------------------------------------------------------------------- bool NamedValueCollection::impl_has( const ::rtl::OUString& _rValueName ) const { NamedValueRepository::const_iterator pos = m_pImpl->aValues.find( _rValueName ); return ( pos != m_pImpl->aValues.end() ); } //-------------------------------------------------------------------- bool NamedValueCollection::impl_put( const ::rtl::OUString& _rValueName, const Any& _rValue ) { bool bHas = impl_has( _rValueName ); m_pImpl->aValues[ _rValueName ] = _rValue; return bHas; } //-------------------------------------------------------------------- bool NamedValueCollection::impl_remove( const ::rtl::OUString& _rValueName ) { NamedValueRepository::iterator pos = m_pImpl->aValues.find( _rValueName ); if ( pos == m_pImpl->aValues.end() ) return false; m_pImpl->aValues.erase( pos ); return true; } //-------------------------------------------------------------------- namespace { struct Value2PropertyValue : public ::std::unary_function< NamedValueRepository::value_type, PropertyValue > { PropertyValue operator()( const NamedValueRepository::value_type& _rValue ) { return PropertyValue( _rValue.first, 0, _rValue.second, PropertyState_DIRECT_VALUE ); } }; struct Value2NamedValue : public ::std::unary_function< NamedValueRepository::value_type, NamedValue > { NamedValue operator()( const NamedValueRepository::value_type& _rValue ) { return NamedValue( _rValue.first, _rValue.second ); } }; } //-------------------------------------------------------------------- sal_Int32 NamedValueCollection::operator >>= ( Sequence< PropertyValue >& _out_rValues ) { _out_rValues.realloc( m_pImpl->aValues.size() ); ::std::transform( m_pImpl->aValues.begin(), m_pImpl->aValues.end(), _out_rValues.getArray(), Value2PropertyValue() ); return _out_rValues.getLength(); } //-------------------------------------------------------------------- sal_Int32 NamedValueCollection::operator >>= ( Sequence< NamedValue >& _out_rValues ) { _out_rValues.realloc( m_pImpl->aValues.size() ); ::std::transform( m_pImpl->aValues.begin(), m_pImpl->aValues.end(), _out_rValues.getArray(), Value2NamedValue() ); return _out_rValues.getLength(); } //........................................................................ } // namespace comphelper //........................................................................ <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ /* model.cpp A simple model that uses a QVector as its data source. */ #include "model.h" /*! Returns the number of items in the string list as the number of rows in the model. */ int LinearModel::rowCount(const QModelIndex &parent) const { Q_USING(parent); return values.count(); } /* Returns an appropriate value for the requested data. If the view requests an invalid index, an invalid variant is returned. If a header is requested then we just return the column or row number, depending on the orientation of the header. Any valid index that corresponds to a string in the list causes that string to be returned. */ /*! Returns a model index for other component to use when referencing the item specified by the given row, column, and type. The parent index is ignored. */ QModelIndex LinearModel::index(int row, int column, const QModelIndex &parent) const { if (parent == QModelIndex() && row >= 0 && row < rowCount() && column == 0) return createIndex(row, column, 0); else return QModelIndex(); } QVariant LinearModel::data(const QModelIndex &index, int role) const { Q_UNUSED(role); if (!index.isValid()) return QVariant(); return values.at(index.row()); } /*! Returns Qt::ItemIsEditable so that all items in the vector can be edited. */ Qt::ItemFlags LinearModel::flags(const QModelIndex &index) const { // all items in the model are editable return QAbstractListModel::flags(index) | Qt::ItemIsEditable; } /*! Changes an item in the string list, but only if the following conditions are met: * The index supplied is valid. * The index corresponds to an item to be shown in a view. * The role associated with editing text is specified. The dataChanged() signal is emitted if the item is changed. */ bool LinearModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (!index.isValid() || role != Qt::EditRole) return false; values.replace(index.row(), value.toInt()); emit dataChanged(index, index); return true; } /*! Inserts a number of rows into the model at the specified position. */ bool LinearModel::insertRows(int position, int rows, const QModelIndex &parent) { beginInsertRows(parent, position, position + rows - 1); values.insert(position, rows, 0); endInsertRows(); return true; } /*! Removes a number of rows from the model at the specified position. */ bool LinearModel::removeRows(int position, int rows, const QModelIndex &parent) { beginRemoveRows(QModelIndex(), position, position+rows-1); values.remove(position, rows); endRemoveRows(); return true; } <commit_msg>Remove ambiguous argument to createIndex.<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ /* model.cpp A simple model that uses a QVector as its data source. */ #include "model.h" /*! Returns the number of items in the string list as the number of rows in the model. */ int LinearModel::rowCount(const QModelIndex &parent) const { Q_USING(parent); return values.count(); } /* Returns an appropriate value for the requested data. If the view requests an invalid index, an invalid variant is returned. If a header is requested then we just return the column or row number, depending on the orientation of the header. Any valid index that corresponds to a string in the list causes that string to be returned. */ /*! Returns a model index for other component to use when referencing the item specified by the given row, column, and type. The parent index is ignored. */ QModelIndex LinearModel::index(int row, int column, const QModelIndex &parent) const { if (parent == QModelIndex() && row >= 0 && row < rowCount() && column == 0) return createIndex(row, column); else return QModelIndex(); } QVariant LinearModel::data(const QModelIndex &index, int role) const { Q_UNUSED(role); if (!index.isValid()) return QVariant(); return values.at(index.row()); } /*! Returns Qt::ItemIsEditable so that all items in the vector can be edited. */ Qt::ItemFlags LinearModel::flags(const QModelIndex &index) const { // all items in the model are editable return QAbstractListModel::flags(index) | Qt::ItemIsEditable; } /*! Changes an item in the string list, but only if the following conditions are met: * The index supplied is valid. * The index corresponds to an item to be shown in a view. * The role associated with editing text is specified. The dataChanged() signal is emitted if the item is changed. */ bool LinearModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (!index.isValid() || role != Qt::EditRole) return false; values.replace(index.row(), value.toInt()); emit dataChanged(index, index); return true; } /*! Inserts a number of rows into the model at the specified position. */ bool LinearModel::insertRows(int position, int rows, const QModelIndex &parent) { beginInsertRows(parent, position, position + rows - 1); values.insert(position, rows, 0); endInsertRows(); return true; } /*! Removes a number of rows from the model at the specified position. */ bool LinearModel::removeRows(int position, int rows, const QModelIndex &parent) { beginRemoveRows(QModelIndex(), position, position+rows-1); values.remove(position, rows); endRemoveRows(); return true; } <|endoftext|>
<commit_before>#include <iostream> #include <set> #include "gtest/gtest.h" #include "onnx/checker.h" #include "onnx/common/constants.h" #include "onnx/defs/schema.h" #include "onnx/onnx-operators_pb.h" #include "onnx/onnx_pb.h" namespace ONNX_NAMESPACE { namespace Test { using namespace checker; using TENSOR_TYPES_MAP = std::unordered_map<std::string, std::vector<std::string>>; void VerifyTypeConstraint( const OpSchema& function_op, const FunctionProto* function_proto, int& counter ) { // TC for function nodes should satisfy the definition defined in the opschema // This is designed to be a best-effort test // TODO: Revisit to have a more consummate check on it TENSOR_TYPES_MAP tc_map; std::set<std::string> primitive_types( OpSchema::all_tensor_types().begin(), OpSchema::all_tensor_types().end()); for (const auto& input : function_op.inputs()) { std::string name = input.GetName(); for (const auto& t : input.GetTypes()) { if (!primitive_types.count(*t)) { return; // skip variable types check for now } tc_map[name].emplace_back(*t); } } for (const auto& output : function_op.outputs()) { std::string name = output.GetName(); for (const auto& t : output.GetTypes()) { if (!primitive_types.count(*t)) { return; // skip variable types check for now } tc_map[name].emplace_back(*t); } } for (auto& node : function_proto->node()) { std::string op_type = node.op_type(); const OpSchema* schema = OpSchemaRegistry::Schema( op_type, function_op.since_version(), function_op.domain()); std::unordered_map<std::string, int> input_tensor_name_idx_map; std::unordered_map<std::string, int> output_tensor_name_idx_map; // Enforce it on input for (unsigned int i = 0; i < schema->inputs().size(); ++i) { auto& input = schema->inputs().at(i); input_tensor_name_idx_map[input.GetName()] = i; } for (auto& tensor_name_tc : tc_map) { auto iter = input_tensor_name_idx_map.find(tensor_name_tc.first); if (iter == input_tensor_name_idx_map.end()) continue; const auto& types = schema->inputs().at(iter->second).GetTypes(); std::unordered_set<std::string> allowed_types; for (auto& s : types) { allowed_types.insert(*s); } for (auto& type : tensor_name_tc.second) { if (allowed_types.find(type) == allowed_types.end()) { fail_check( "Input type " + type + " defined in " + schema->Name() + "'s function body is not allowed in node " + op_type); } } } // Enforce it on output for (unsigned int i = 0; i < schema->outputs().size(); ++i) { auto& output = schema->outputs().at(i); output_tensor_name_idx_map[output.GetName()] = i; } for (auto& tensor_name_tc : tc_map) { auto iter = output_tensor_name_idx_map.find(tensor_name_tc.first); if (iter == output_tensor_name_idx_map.end()) continue; const auto& types = schema->outputs().at(iter->second).GetTypes(); std::unordered_set<std::string> allowed_types; for (auto& s : types) { allowed_types.insert(*s); } for (auto& type : tensor_name_tc.second) { if (allowed_types.find(type) == allowed_types.end()) { fail_check( "Output type " + type + " defined in " + schema->Name() + "'s function body is not allowed in node " + op_type); } } } } ++counter; } void VerifyFunction(const OpSchema& op, const FunctionProto* function_proto, int& counter) { // Verify function proto is valid if (!function_proto) { fail_check("Cannot get function body for op '", op.Name(), "'"); } CheckerContext ctx; std::unordered_map<std::string, int> op_set; if ((int)function_proto->since_version() != op.since_version()) { fail_check("Unmatched since_version defined in function op '", op.Name(), "'"); } auto version_range = OpSchemaRegistry::DomainToVersionRange::Instance().Map().at( op.domain()); if (function_proto->since_version() > version_range.second || function_proto->since_version() < version_range.first) { fail_check("Invalid function version in function op '", op.Name(), "'"); } op_set.insert( {op.domain(), op.since_version()}); ctx.set_opset_imports(op_set); ctx.set_is_main_graph(false); LexicalScopeContext lex_ctx; try { check_function(*function_proto, ctx, lex_ctx); } catch (ValidationError& ex) { fail_check(ex.what()); } // Verify function op has compatible Type constraints defined in // op and function body. VerifyTypeConstraint(op, function_proto, counter); } // Verify registered ops with function body has compatible // definition on TypeConstraints between ops and function body TEST(FunctionVerification, VerifyFunctionOps) { const std::vector<OpSchema> schemas = OpSchemaRegistry::get_all_schemas(); int function_counter = 0, verified_counter = 0; for (const auto s : schemas) { if (!s.HasFunction()) continue; try{ ++function_counter; auto function_body = s.GetFunction(); VerifyFunction(s, function_body, verified_counter); }catch (ONNX_NAMESPACE::checker::ValidationError e){ FAIL() << e.what(); } } std::cerr << "[ ] Verified " << verified_counter << "/" << function_counter << " Functions." << std::endl; } } // namespace Test } // namespace ONNX_NAMESPACE <commit_msg>Fix bug in function body verifier (#2390)<commit_after>#include <iostream> #include <set> #include "gtest/gtest.h" #include "onnx/checker.h" #include "onnx/common/constants.h" #include "onnx/defs/schema.h" #include "onnx/onnx-operators_pb.h" #include "onnx/onnx_pb.h" namespace ONNX_NAMESPACE { namespace Test { using namespace checker; using TENSOR_TYPES_MAP = std::unordered_map<std::string, std::vector<std::string>>; void VerifyTypeConstraint( const OpSchema& function_op, const FunctionProto* function_proto, int& counter) { // This is a simple partial type-checker for a function-body. // TODO: Revisit to make the type-checker more complete. TENSOR_TYPES_MAP tc_map; std::set<std::string> primitive_types( OpSchema::all_tensor_types().begin(), OpSchema::all_tensor_types().end()); for (const auto& input : function_op.inputs()) { std::string name = input.GetName(); for (const auto& t : input.GetTypes()) { tc_map[name].emplace_back(*t); } } for (const auto& output : function_op.outputs()) { std::string name = output.GetName(); for (const auto& t : output.GetTypes()) { tc_map[name].emplace_back(*t); } } for (auto& node : function_proto->node()) { std::string op_type = node.op_type(); const OpSchema* schema = OpSchemaRegistry::Schema( op_type, function_op.since_version(), function_op.domain()); // Check that the types of actual inputs, if known, are legal as per schema // of called op: auto num_formal_inputs = static_cast<size_t>(schema->inputs().size()); auto num_actual_inputs = static_cast<size_t>(node.input_size()); for (size_t i = 0; i < num_actual_inputs; ++i) { auto actual_param_name = node.input(static_cast<int>(i)); auto iter = tc_map.find(actual_param_name); if (iter != tc_map.end()) { // if i >= num_formal_inputs, it is a variadic parameter corresponding // to the last formal parameter. auto formal_i = std::min(i, num_formal_inputs - 1); const auto& types = schema->inputs().at(formal_i).GetTypes(); std::unordered_set<std::string> allowed_types; for (auto& s : types) { allowed_types.insert(*s); } for (auto& actual_type : iter->second) { if (allowed_types.find(actual_type) == allowed_types.end()) { fail_check( "Input type " + actual_type + " of parameter " + actual_param_name + " of function " + function_op.Name() + " is not allowed by operator " + op_type); } } } } // No simple check exists for outputs: we need to integrate type inference // to identify the possible output types and verify that they are included // in the function-schema. } ++counter; } void VerifyFunction( const OpSchema& op, const FunctionProto* function_proto, int& counter) { // Verify function proto is valid if (!function_proto) { fail_check("Cannot get function body for op '", op.Name(), "'"); } CheckerContext ctx; std::unordered_map<std::string, int> op_set; if ((int)function_proto->since_version() != op.since_version()) { fail_check( "Unmatched since_version defined in function op '", op.Name(), "'"); } auto version_range = OpSchemaRegistry::DomainToVersionRange::Instance().Map().at(op.domain()); if (function_proto->since_version() > version_range.second || function_proto->since_version() < version_range.first) { fail_check("Invalid function version in function op '", op.Name(), "'"); } op_set.insert({op.domain(), op.since_version()}); ctx.set_opset_imports(op_set); ctx.set_is_main_graph(false); LexicalScopeContext lex_ctx; try { check_function(*function_proto, ctx, lex_ctx); } catch (ValidationError& ex) { fail_check(ex.what()); } // Verify function op has compatible Type constraints defined in // op and function body. VerifyTypeConstraint(op, function_proto, counter); } // Verify registered ops with function body has compatible // definition on TypeConstraints between ops and function body TEST(FunctionVerification, VerifyFunctionOps) { const std::vector<OpSchema> schemas = OpSchemaRegistry::get_all_schemas(); int function_counter = 0, verified_counter = 0; for (const auto s : schemas) { if (!s.HasFunction()) continue; // Skip test for functions with known errors that need to be fixed: // Range currently permits int16 parameters, but the operator Sub, called // from the body of Range does not yet support int16 parameter. if (s.Name() == "Range") continue; try { ++function_counter; auto function_body = s.GetFunction(); VerifyFunction(s, function_body, verified_counter); } catch (ONNX_NAMESPACE::checker::ValidationError e) { FAIL() << e.what(); } } std::cerr << "[ ] Verified " << verified_counter << "/" << function_counter << " Functions." << std::endl; } } // namespace Test } // namespace ONNX_NAMESPACE <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <set> #include <cstdlib> namespace { typedef std::vector<uint16_t> MEM; MEM mem_; typedef std::set<uint16_t> SET; SET set_; } int main(int argc, char* argv[]); int main(int argc, char* argv[]) { uint32_t size = 10000; mem_.resize(size); for(int i = 0; i < size; ++i) { mem_[i] = rand(); } uint16_t min = 65535; uint16_t max = 0; uint32_t ave = 0; for(int i = 0; i < size; ++i) { if(min > mem_[i]) min = mem_[i]; if(max < mem_[i]) max = mem_[i]; ave += mem_[i]; set_.insert(mem_[i]); } ave /= size; auto s = set_.size(); auto it = set_.cbegin(); uint16_t n; for(int i = 0; i < (s / 2); ++i) ++it; if(s & 1) { ++it; n = *it; } else { uint32_t nn = *it; ++it; nn += *it; n = nn / 2; } std::cout << "Size: " << size << std::endl; std::cout << "Min: " << static_cast<int>(min) << std::endl; std::cout << "Max: " << static_cast<int>(max) << std::endl; std::cout << "Average: " << static_cast<int>(ave) << std::endl; std::cout << "SET Size: " << s << std::endl; std::cout << "SET Median: " << n << std::endl; } <commit_msg>update map median<commit_after>#include <iostream> #include <vector> #include <map> #include <algorithm> #include <functional> namespace { typedef std::vector<uint16_t> MEM; MEM mem_; typedef std::map<uint16_t, uint16_t> MAP; MAP map_; } int main(int argc, char* argv[]); int main(int argc, char* argv[]) { uint32_t size = 10000; mem_.resize(size); for(int i = 0; i < size; ++i) { mem_[i] = rand(); } // std::map「median」 uint16_t min = 65535; uint16_t max = 0; uint32_t ave = 0; for(int i = 0; i < size; ++i) { if(min > mem_[i]) min = mem_[i]; if(max < mem_[i]) max = mem_[i]; ave += mem_[i]; auto ret = map_.emplace(mem_[i], 1); if(!ret.second) { auto& v = ret.first; ++v->second; } } ave /= size; std::cout << "Map size: " << map_.size() << std::endl; int sum = 0; int med = 0; for(MAP::iterator it = map_.begin(); it != map_.end(); ++it) { int cnt = it->second; sum += cnt; if(sum >= (size / 2)) { med = it->first; if((size & 1) == 0) { ++it; med += it->first; med /= 2; } break; } } std::cout << "Total: " << sum << std::endl; // 通常の「median」 std::sort(mem_.begin(), mem_.end()); int sa = mem_[(size / 2) - 1]; if((size & 1) == 0) { sa += mem_[(size / 2)]; sa /= 2; } std::cout << "Median: " << sa << std::endl; std::cout << "Size: " << size << std::endl; std::cout << "Min: " << static_cast<int>(min) << std::endl; std::cout << "Max: " << static_cast<int>(max) << std::endl; std::cout << "Average: " << static_cast<int>(ave) << std::endl; std::cout << "SET Median: " << med << std::endl; } <|endoftext|>
<commit_before>/* * Copyright © 2010 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /** * \file lower_if_to_cond_assign.cpp * * This attempts to flatten if-statements to conditional assignments for * GPUs with limited or no flow control support. * * It can't handle other control flow being inside of its block, such * as calls or loops. Hopefully loop unrolling and inlining will take * care of those. * * Drivers for GPUs with no control flow support should simply call * * lower_if_to_cond_assign(instructions) * * to attempt to flatten all if-statements. * * Some GPUs (such as i965 prior to gen6) do support control flow, but have a * maximum nesting depth N. Drivers for such hardware can call * * lower_if_to_cond_assign(instructions, N) * * to attempt to flatten any if-statements appearing at depth > N. */ #include "glsl_types.h" #include "ir.h" class ir_if_to_cond_assign_visitor : public ir_hierarchical_visitor { public: ir_if_to_cond_assign_visitor(unsigned max_depth) { this->progress = false; this->max_depth = max_depth; this->depth = 0; } ir_visitor_status visit_enter(ir_if *); ir_visitor_status visit_leave(ir_if *); bool progress; unsigned max_depth; unsigned depth; }; bool lower_if_to_cond_assign(exec_list *instructions, unsigned max_depth) { ir_if_to_cond_assign_visitor v(max_depth); visit_list_elements(&v, instructions); return v.progress; } void check_control_flow(ir_instruction *ir, void *data) { bool *found_control_flow = (bool *)data; switch (ir->ir_type) { case ir_type_call: case ir_type_discard: case ir_type_loop: case ir_type_loop_jump: case ir_type_return: *found_control_flow = true; break; default: break; } } void move_block_to_cond_assign(void *mem_ctx, ir_if *if_ir, ir_variable *cond_var, bool then) { exec_list *instructions; if (then) { instructions = &if_ir->then_instructions; } else { instructions = &if_ir->else_instructions; } foreach_iter(exec_list_iterator, iter, *instructions) { ir_instruction *ir = (ir_instruction *)iter.get(); if (ir->ir_type == ir_type_assignment) { ir_assignment *assign = (ir_assignment *)ir; ir_rvalue *cond_expr; ir_dereference *deref = new(mem_ctx) ir_dereference_variable(cond_var); if (then) { cond_expr = deref; } else { cond_expr = new(mem_ctx) ir_expression(ir_unop_logic_not, glsl_type::bool_type, deref, NULL); } if (!assign->condition) { assign->condition = cond_expr; } else { assign->condition = new(mem_ctx) ir_expression(ir_binop_logic_and, glsl_type::bool_type, cond_expr, assign->condition); } } /* Now, move from the if block to the block surrounding it. */ ir->remove(); if_ir->insert_before(ir); } } ir_visitor_status ir_if_to_cond_assign_visitor::visit_enter(ir_if *ir) { (void) ir; this->depth++; return visit_continue; } ir_visitor_status ir_if_to_cond_assign_visitor::visit_leave(ir_if *ir) { /* Only flatten when beyond the GPU's maximum supported nesting depth. */ if (this->depth <= this->max_depth) return visit_continue; this->depth--; bool found_control_flow = false; ir_variable *cond_var; ir_assignment *assign; ir_dereference_variable *deref; /* Check that both blocks don't contain anything we can't support. */ foreach_iter(exec_list_iterator, then_iter, ir->then_instructions) { ir_instruction *then_ir = (ir_instruction *)then_iter.get(); visit_tree(then_ir, check_control_flow, &found_control_flow); } foreach_iter(exec_list_iterator, else_iter, ir->else_instructions) { ir_instruction *else_ir = (ir_instruction *)else_iter.get(); visit_tree(else_ir, check_control_flow, &found_control_flow); } if (found_control_flow) return visit_continue; void *mem_ctx = ralloc_parent(ir); /* Store the condition to a variable so the assignment conditions are * simpler. */ cond_var = new(mem_ctx) ir_variable(glsl_type::bool_type, "if_to_cond_assign_condition", ir_var_temporary); ir->insert_before(cond_var); deref = new(mem_ctx) ir_dereference_variable(cond_var); assign = new(mem_ctx) ir_assignment(deref, ir->condition, NULL); ir->insert_before(assign); /* Now, move all of the instructions out of the if blocks, putting * conditions on assignments. */ move_block_to_cond_assign(mem_ctx, ir, cond_var, true); move_block_to_cond_assign(mem_ctx, ir, cond_var, false); ir->remove(); this->progress = true; return visit_continue; } <commit_msg>glsl: Fix depth unbalancing problem in if-statement flattening<commit_after>/* * Copyright © 2010 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /** * \file lower_if_to_cond_assign.cpp * * This attempts to flatten if-statements to conditional assignments for * GPUs with limited or no flow control support. * * It can't handle other control flow being inside of its block, such * as calls or loops. Hopefully loop unrolling and inlining will take * care of those. * * Drivers for GPUs with no control flow support should simply call * * lower_if_to_cond_assign(instructions) * * to attempt to flatten all if-statements. * * Some GPUs (such as i965 prior to gen6) do support control flow, but have a * maximum nesting depth N. Drivers for such hardware can call * * lower_if_to_cond_assign(instructions, N) * * to attempt to flatten any if-statements appearing at depth > N. */ #include "glsl_types.h" #include "ir.h" class ir_if_to_cond_assign_visitor : public ir_hierarchical_visitor { public: ir_if_to_cond_assign_visitor(unsigned max_depth) { this->progress = false; this->max_depth = max_depth; this->depth = 0; } ir_visitor_status visit_enter(ir_if *); ir_visitor_status visit_leave(ir_if *); bool progress; unsigned max_depth; unsigned depth; }; bool lower_if_to_cond_assign(exec_list *instructions, unsigned max_depth) { ir_if_to_cond_assign_visitor v(max_depth); visit_list_elements(&v, instructions); return v.progress; } void check_control_flow(ir_instruction *ir, void *data) { bool *found_control_flow = (bool *)data; switch (ir->ir_type) { case ir_type_call: case ir_type_discard: case ir_type_loop: case ir_type_loop_jump: case ir_type_return: *found_control_flow = true; break; default: break; } } void move_block_to_cond_assign(void *mem_ctx, ir_if *if_ir, ir_variable *cond_var, bool then) { exec_list *instructions; if (then) { instructions = &if_ir->then_instructions; } else { instructions = &if_ir->else_instructions; } foreach_iter(exec_list_iterator, iter, *instructions) { ir_instruction *ir = (ir_instruction *)iter.get(); if (ir->ir_type == ir_type_assignment) { ir_assignment *assign = (ir_assignment *)ir; ir_rvalue *cond_expr; ir_dereference *deref = new(mem_ctx) ir_dereference_variable(cond_var); if (then) { cond_expr = deref; } else { cond_expr = new(mem_ctx) ir_expression(ir_unop_logic_not, glsl_type::bool_type, deref, NULL); } if (!assign->condition) { assign->condition = cond_expr; } else { assign->condition = new(mem_ctx) ir_expression(ir_binop_logic_and, glsl_type::bool_type, cond_expr, assign->condition); } } /* Now, move from the if block to the block surrounding it. */ ir->remove(); if_ir->insert_before(ir); } } ir_visitor_status ir_if_to_cond_assign_visitor::visit_enter(ir_if *ir) { (void) ir; this->depth++; return visit_continue; } ir_visitor_status ir_if_to_cond_assign_visitor::visit_leave(ir_if *ir) { /* Only flatten when beyond the GPU's maximum supported nesting depth. */ if (this->depth-- <= this->max_depth) return visit_continue; bool found_control_flow = false; ir_variable *cond_var; ir_assignment *assign; ir_dereference_variable *deref; /* Check that both blocks don't contain anything we can't support. */ foreach_iter(exec_list_iterator, then_iter, ir->then_instructions) { ir_instruction *then_ir = (ir_instruction *)then_iter.get(); visit_tree(then_ir, check_control_flow, &found_control_flow); } foreach_iter(exec_list_iterator, else_iter, ir->else_instructions) { ir_instruction *else_ir = (ir_instruction *)else_iter.get(); visit_tree(else_ir, check_control_flow, &found_control_flow); } if (found_control_flow) return visit_continue; void *mem_ctx = ralloc_parent(ir); /* Store the condition to a variable so the assignment conditions are * simpler. */ cond_var = new(mem_ctx) ir_variable(glsl_type::bool_type, "if_to_cond_assign_condition", ir_var_temporary); ir->insert_before(cond_var); deref = new(mem_ctx) ir_dereference_variable(cond_var); assign = new(mem_ctx) ir_assignment(deref, ir->condition, NULL); ir->insert_before(assign); /* Now, move all of the instructions out of the if blocks, putting * conditions on assignments. */ move_block_to_cond_assign(mem_ctx, ir, cond_var, true); move_block_to_cond_assign(mem_ctx, ir, cond_var, false); ir->remove(); this->progress = true; return visit_continue; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: loaddispatchlistener.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2006-06-19 11:24:15 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ //_______________________________________________ // includes of own project #ifndef __FRAMEWORK_LOADENV_LOADDISPATCHLISTENER_HXX_ #include <loadenv/loaddispatchlistener.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_ #include <threadhelp/writeguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif //_______________________________________________ // includes of uno interface #ifndef _COM_SUN_STAR_FRAME_DISPATCHRESULTSTATE_HPP_ #include <com/sun/star/frame/DispatchResultState.hpp> #endif //_______________________________________________ // includes of an other project #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif //_______________________________________________ // namespace namespace framework{ // may there exist already a define .-( #ifndef css namespace css = ::com::sun::star; #endif //_______________________________________________ // declarations //----------------------------------------------- DEFINE_XINTERFACE_2(LoadDispatchListener , OWeakObject , DIRECT_INTERFACE (css::frame::XDispatchResultListener ), DERIVED_INTERFACE(css::lang::XEventListener, css::frame::XDispatchResultListener)) //----------------------------------------------- LoadDispatchListener::LoadDispatchListener() : ThreadHelpBase(&Application::GetSolarMutex()) { // reset the condition object - so our user can wait there. m_aUserWait.reset(); // set defined state for our result value m_aResult.State = css::frame::DispatchResultState::DONTKNOW; m_aResult.Result.clear(); } //----------------------------------------------- LoadDispatchListener::~LoadDispatchListener() { } //----------------------------------------------- void SAL_CALL LoadDispatchListener::dispatchFinished(const css::frame::DispatchResultEvent& aEvent) throw(css::uno::RuntimeException) { // SAFE -> ---------------------------------- WriteGuard aWriteLock(m_aLock); m_aResult = aEvent; aWriteLock.unlock(); // <- SAFE ---------------------------------- // inform user about this arrived event m_aUserWait.set(); } //----------------------------------------------- void SAL_CALL LoadDispatchListener::disposing(const css::lang::EventObject&) throw(css::uno::RuntimeException) { // SAFE -> ---------------------------------- WriteGuard aWriteLock(m_aLock); m_aResult.State = css::frame::DispatchResultState::DONTKNOW; m_aResult.Result.clear(); aWriteLock.unlock(); // <- SAFE ---------------------------------- // inform user about this arrived event m_aUserWait.set(); } //----------------------------------------------- void LoadDispatchListener::setURL(const ::rtl::OUString & sURL) { // SAFE -> ---------------------------------- WriteGuard aWriteLock(m_aLock); m_sURL = sURL; aWriteLock.unlock(); // <- SAFE ---------------------------------- } //----------------------------------------------- sal_Bool LoadDispatchListener::wait(sal_Int32 /*nWait_ms*/) { // Wait till an event occures m_aUserWait.wait(0); // reset the condition, so this method can be called again. // Of course a new action has to be started outside too! m_aUserWait.reset(); // TODO implement real timeout :-) return sal_True; } //----------------------------------------------- css::frame::DispatchResultEvent LoadDispatchListener::getResult() const { // SAFE -> ---------------------------------- ReadGuard aReadLock(m_aLock); return m_aResult; // <- SAFE ---------------------------------- } } // namespace framework <commit_msg>INTEGRATION: CWS pchfix02 (1.4.52); FILE MERGED 2006/09/01 17:29:15 kaib 1.4.52.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: loaddispatchlistener.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-16 14:05:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_framework.hxx" //_______________________________________________ // includes of own project #ifndef __FRAMEWORK_LOADENV_LOADDISPATCHLISTENER_HXX_ #include <loadenv/loaddispatchlistener.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_ #include <threadhelp/writeguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif //_______________________________________________ // includes of uno interface #ifndef _COM_SUN_STAR_FRAME_DISPATCHRESULTSTATE_HPP_ #include <com/sun/star/frame/DispatchResultState.hpp> #endif //_______________________________________________ // includes of an other project #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif //_______________________________________________ // namespace namespace framework{ // may there exist already a define .-( #ifndef css namespace css = ::com::sun::star; #endif //_______________________________________________ // declarations //----------------------------------------------- DEFINE_XINTERFACE_2(LoadDispatchListener , OWeakObject , DIRECT_INTERFACE (css::frame::XDispatchResultListener ), DERIVED_INTERFACE(css::lang::XEventListener, css::frame::XDispatchResultListener)) //----------------------------------------------- LoadDispatchListener::LoadDispatchListener() : ThreadHelpBase(&Application::GetSolarMutex()) { // reset the condition object - so our user can wait there. m_aUserWait.reset(); // set defined state for our result value m_aResult.State = css::frame::DispatchResultState::DONTKNOW; m_aResult.Result.clear(); } //----------------------------------------------- LoadDispatchListener::~LoadDispatchListener() { } //----------------------------------------------- void SAL_CALL LoadDispatchListener::dispatchFinished(const css::frame::DispatchResultEvent& aEvent) throw(css::uno::RuntimeException) { // SAFE -> ---------------------------------- WriteGuard aWriteLock(m_aLock); m_aResult = aEvent; aWriteLock.unlock(); // <- SAFE ---------------------------------- // inform user about this arrived event m_aUserWait.set(); } //----------------------------------------------- void SAL_CALL LoadDispatchListener::disposing(const css::lang::EventObject&) throw(css::uno::RuntimeException) { // SAFE -> ---------------------------------- WriteGuard aWriteLock(m_aLock); m_aResult.State = css::frame::DispatchResultState::DONTKNOW; m_aResult.Result.clear(); aWriteLock.unlock(); // <- SAFE ---------------------------------- // inform user about this arrived event m_aUserWait.set(); } //----------------------------------------------- void LoadDispatchListener::setURL(const ::rtl::OUString & sURL) { // SAFE -> ---------------------------------- WriteGuard aWriteLock(m_aLock); m_sURL = sURL; aWriteLock.unlock(); // <- SAFE ---------------------------------- } //----------------------------------------------- sal_Bool LoadDispatchListener::wait(sal_Int32 /*nWait_ms*/) { // Wait till an event occures m_aUserWait.wait(0); // reset the condition, so this method can be called again. // Of course a new action has to be started outside too! m_aUserWait.reset(); // TODO implement real timeout :-) return sal_True; } //----------------------------------------------- css::frame::DispatchResultEvent LoadDispatchListener::getResult() const { // SAFE -> ---------------------------------- ReadGuard aReadLock(m_aLock); return m_aResult; // <- SAFE ---------------------------------- } } // namespace framework <|endoftext|>
<commit_before>//game loop #include "game.h" #include <Windows.h> Game::Game() { } void Game::run() { while (running) { //throttle the game //throttling code inputManager.handle(); grahicsManager.render(this); } } <commit_msg>Update game.cpp<commit_after>//game loop #include "game.h" #include <Windows.h> Game::Game() { inputManager = new InputManager; graphicsManager = new GraphicsManager; } void Game::run() { while (running) { //throttle the game //throttling code inputManager.handleinput(this); grahicsManager.render(this); } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #include <boost/python.hpp> #include <boost/python/implicit.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <mapnik/rule.hpp> #include <mapnik/filter.hpp> #include <mapnik/filter_factory.hpp> using namespace boost::python; using mapnik::rule_type; using mapnik::filter; using mapnik::filter_ptr; using mapnik::filter_factory; using mapnik::Feature; using mapnik::point_symbolizer; using mapnik::line_symbolizer; using mapnik::line_pattern_symbolizer; using mapnik::polygon_symbolizer; using mapnik::polygon_pattern_symbolizer; using mapnik::raster_symbolizer; using mapnik::shield_symbolizer; using mapnik::text_symbolizer; using mapnik::building_symbolizer; using mapnik::symbolizer; using mapnik::symbolizers; struct rule_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(const rule_type& r) { return boost::python::make_tuple(r.get_name(),r.get_title(),r.get_min_scale(),r.get_max_scale()); } static boost::python::tuple getstate(const rule_type& r) { boost::python::list syms; symbolizers::const_iterator it = r.begin(); symbolizers::const_iterator end = r.end(); for (; it != end; ++it) { syms.append( *it ); } // Here the filter string is used rather than the actual Filter object // Need to look into how to get the Filter object std::string filter_expr = r.get_filter()->to_string(); return boost::python::make_tuple(r.get_abstract(),filter_expr,r.has_else_filter(),syms); } static void setstate (rule_type& r, boost::python::tuple state) { using namespace boost::python; if (len(state) != 4) { PyErr_SetObject(PyExc_ValueError, ("expected 4-item tuple in call to __setstate__; got %s" % state).ptr() ); throw_error_already_set(); } if (state[0]) { r.set_title(extract<std::string>(state[0])); } if (state[1]) { std::string filter_expr=extract<std::string>(state[1]); r.set_filter(mapnik::create_filter(filter_expr,"utf8")); } if (state[2]) { r.set_else(true); } boost::python::list syms=extract<boost::python::list>(state[3]); for (int i=0;i<len(syms);++i) { r.append(extract<symbolizer>(syms[i])); } } }; void export_rule() { implicitly_convertible<point_symbolizer,symbolizer>(); implicitly_convertible<line_symbolizer,symbolizer>(); implicitly_convertible<line_pattern_symbolizer,symbolizer>(); implicitly_convertible<polygon_symbolizer,symbolizer>(); implicitly_convertible<building_symbolizer,symbolizer>(); implicitly_convertible<polygon_pattern_symbolizer,symbolizer>(); implicitly_convertible<raster_symbolizer,symbolizer>(); implicitly_convertible<shield_symbolizer,symbolizer>(); implicitly_convertible<text_symbolizer,symbolizer>(); class_<symbolizers>("Symbolizers",init<>("TODO")) .def(vector_indexing_suite<symbolizers>()) ; class_<rule_type>("Rule",init<>("default constructor")) .def(init<std::string const&, boost::python::optional<std::string const&,double,double> >()) .def_pickle(rule_pickle_suite() ) .add_property("name",make_function (&rule_type::get_name, return_value_policy<copy_const_reference>()), &rule_type::set_name) .add_property("title",make_function (&rule_type::get_title,return_value_policy<copy_const_reference>()), &rule_type::set_title) .add_property("abstract",make_function (&rule_type::get_abstract,return_value_policy<copy_const_reference>()), &rule_type::set_abstract) .add_property("filter",make_function (&rule_type::get_filter,return_value_policy<copy_const_reference>()), &rule_type::set_filter) .add_property("min_scale",&rule_type::get_min_scale,&rule_type::set_min_scale) .add_property("max_scale",&rule_type::get_max_scale,&rule_type::set_max_scale) .def("set_else",&rule_type::set_else) .def("has_else",&rule_type::has_else_filter) .def("active",&rule_type::active) .add_property("symbols",make_function (&rule_type::get_symbolizers,return_value_policy<reference_existing_object>())) ; } <commit_msg>remove unneeded include added in r921<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #include <boost/python.hpp> #include <boost/python/implicit.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <mapnik/rule.hpp> #include <mapnik/filter_factory.hpp> using namespace boost::python; using mapnik::rule_type; using mapnik::filter; using mapnik::filter_ptr; using mapnik::filter_factory; using mapnik::Feature; using mapnik::point_symbolizer; using mapnik::line_symbolizer; using mapnik::line_pattern_symbolizer; using mapnik::polygon_symbolizer; using mapnik::polygon_pattern_symbolizer; using mapnik::raster_symbolizer; using mapnik::shield_symbolizer; using mapnik::text_symbolizer; using mapnik::building_symbolizer; using mapnik::symbolizer; using mapnik::symbolizers; struct rule_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(const rule_type& r) { return boost::python::make_tuple(r.get_name(),r.get_title(),r.get_min_scale(),r.get_max_scale()); } static boost::python::tuple getstate(const rule_type& r) { boost::python::list syms; symbolizers::const_iterator it = r.begin(); symbolizers::const_iterator end = r.end(); for (; it != end; ++it) { syms.append( *it ); } // Here the filter string is used rather than the actual Filter object // Need to look into how to get the Filter object std::string filter_expr = r.get_filter()->to_string(); return boost::python::make_tuple(r.get_abstract(),filter_expr,r.has_else_filter(),syms); } static void setstate (rule_type& r, boost::python::tuple state) { using namespace boost::python; if (len(state) != 4) { PyErr_SetObject(PyExc_ValueError, ("expected 4-item tuple in call to __setstate__; got %s" % state).ptr() ); throw_error_already_set(); } if (state[0]) { r.set_title(extract<std::string>(state[0])); } if (state[1]) { std::string filter_expr=extract<std::string>(state[1]); r.set_filter(mapnik::create_filter(filter_expr,"utf8")); } if (state[2]) { r.set_else(true); } boost::python::list syms=extract<boost::python::list>(state[3]); for (int i=0;i<len(syms);++i) { r.append(extract<symbolizer>(syms[i])); } } }; void export_rule() { implicitly_convertible<point_symbolizer,symbolizer>(); implicitly_convertible<line_symbolizer,symbolizer>(); implicitly_convertible<line_pattern_symbolizer,symbolizer>(); implicitly_convertible<polygon_symbolizer,symbolizer>(); implicitly_convertible<building_symbolizer,symbolizer>(); implicitly_convertible<polygon_pattern_symbolizer,symbolizer>(); implicitly_convertible<raster_symbolizer,symbolizer>(); implicitly_convertible<shield_symbolizer,symbolizer>(); implicitly_convertible<text_symbolizer,symbolizer>(); class_<symbolizers>("Symbolizers",init<>("TODO")) .def(vector_indexing_suite<symbolizers>()) ; class_<rule_type>("Rule",init<>("default constructor")) .def(init<std::string const&, boost::python::optional<std::string const&,double,double> >()) .def_pickle(rule_pickle_suite() ) .add_property("name",make_function (&rule_type::get_name, return_value_policy<copy_const_reference>()), &rule_type::set_name) .add_property("title",make_function (&rule_type::get_title,return_value_policy<copy_const_reference>()), &rule_type::set_title) .add_property("abstract",make_function (&rule_type::get_abstract,return_value_policy<copy_const_reference>()), &rule_type::set_abstract) .add_property("filter",make_function (&rule_type::get_filter,return_value_policy<copy_const_reference>()), &rule_type::set_filter) .add_property("min_scale",&rule_type::get_min_scale,&rule_type::set_min_scale) .add_property("max_scale",&rule_type::get_max_scale,&rule_type::set_max_scale) .def("set_else",&rule_type::set_else) .def("has_else",&rule_type::has_else_filter) .def("active",&rule_type::active) .add_property("symbols",make_function (&rule_type::get_symbolizers,return_value_policy<reference_existing_object>())) ; } <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "TiledMeshGenerator.h" #include "CastUniquePointer.h" #include "libmesh/replicated_mesh.h" #include "libmesh/distributed_mesh.h" #include "libmesh/boundary_info.h" #include "libmesh/mesh_modification.h" #include "libmesh/bounding_box.h" #include "libmesh/mesh_tools.h" #include "libmesh/point.h" #include <typeinfo> registerMooseObject("MooseApp", TiledMeshGenerator); defineLegacyParams(TiledMeshGenerator); InputParameters TiledMeshGenerator::validParams() { InputParameters params = MeshGenerator::validParams(); params.addRequiredParam<MeshGeneratorName>("input", "The mesh we want to repeat"); // x boundary names params.addParam<BoundaryName>("left_boundary", "left", "name of the left (x) boundary"); params.addParam<BoundaryName>("right_boundary", "right", "name of the right (x) boundary"); // y boundary names params.addParam<BoundaryName>("top_boundary", "top", "name of the top (y) boundary"); params.addParam<BoundaryName>("bottom_boundary", "bottom", "name of the bottom (y) boundary"); // z boundary names params.addParam<BoundaryName>("front_boundary", "front", "name of the front (z) boundary"); params.addParam<BoundaryName>("back_boundary", "back", "name of the back (z) boundary"); // The number of tiles is 1 in each direction unless otherwise specified. // An x_tiles value of 1 means do not stitch any extra meshes together in // the x-direction. params.addParam<unsigned int>( "x_tiles", 1, "Number of tiles to stitch together (left to right) in the x-direction"); params.addParam<unsigned int>( "y_tiles", 1, "Number of tiles to stitch together (top to bottom) in the y-direction"); params.addParam<unsigned int>( "z_tiles", 1, "Number of tiles to stitch together (front to back) in the z-direction"); params.addClassDescription("Use the supplied mesh and create a tiled grid by repeating this mesh " "in the x,y, and z directions."); return params; } TiledMeshGenerator::TiledMeshGenerator(const InputParameters & parameters) : MeshGenerator(parameters), _input(getMesh("input")) { if (dynamic_pointer_cast<DistributedMesh>(_input) != nullptr) mooseError("TiledMeshGenerator only works with ReplicatedMesh."); } std::unique_ptr<MeshBase> TiledMeshGenerator::generate() { std::unique_ptr<MeshBase> initial_mesh = std::move(_input); std::unique_ptr<ReplicatedMesh> mesh = dynamic_pointer_cast<ReplicatedMesh>(initial_mesh); // Getting the x,y,z widths std::set<subdomain_id_type> sub_ids; mesh->subdomain_ids(sub_ids); BoundingBox bbox(Point(std::numeric_limits<Real>::max(), std::numeric_limits<Real>::max(), std::numeric_limits<Real>::max()), Point(std::numeric_limits<Real>::lowest(), std::numeric_limits<Real>::lowest(), std::numeric_limits<Real>::lowest())); for (auto id : sub_ids) { BoundingBox sub_bbox = MeshTools::create_subdomain_bounding_box(*mesh, id); bbox.union_with(sub_bbox); } _x_width = bbox.max()(0) - bbox.min()(0); _y_width = bbox.max()(1) - bbox.min()(1); _z_width = bbox.max()(2) - bbox.min()(2); boundary_id_type left = mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("left_boundary")); boundary_id_type right = mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("right_boundary")); boundary_id_type top = mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("top_boundary")); boundary_id_type bottom = mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("bottom_boundary")); boundary_id_type front = mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("front_boundary")); boundary_id_type back = mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("back_boundary")); { std::unique_ptr<MeshBase> clone = mesh->clone(); // Build X Tiles for (unsigned int i = 1; i < getParam<unsigned int>("x_tiles"); ++i) { MeshTools::Modification::translate(*clone, _x_width, 0, 0); mesh->stitch_meshes(dynamic_cast<ReplicatedMesh &>(*clone), right, left, TOLERANCE, /*clear_stitched_boundary_ids=*/true); } } { std::unique_ptr<MeshBase> clone = mesh->clone(); // Build Y Tiles for (unsigned int i = 1; i < getParam<unsigned int>("y_tiles"); ++i) { MeshTools::Modification::translate(*clone, 0, _y_width, 0); mesh->stitch_meshes(dynamic_cast<ReplicatedMesh &>(*clone), top, bottom, TOLERANCE, /*clear_stitched_boundary_ids=*/true); } } { std::unique_ptr<MeshBase> clone = mesh->clone(); // Build Z Tiles for (unsigned int i = 1; i < getParam<unsigned int>("z_tiles"); ++i) { MeshTools::Modification::translate(*clone, 0, 0, _z_width); mesh->stitch_meshes(dynamic_cast<ReplicatedMesh &>(*clone), front, back, TOLERANCE, /*clear_stitched_boundary_ids=*/true); } } return dynamic_pointer_cast<MeshBase>(mesh); } <commit_msg>Use no-param c-tor to build an empty bounding box<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "TiledMeshGenerator.h" #include "CastUniquePointer.h" #include "libmesh/replicated_mesh.h" #include "libmesh/distributed_mesh.h" #include "libmesh/boundary_info.h" #include "libmesh/mesh_modification.h" #include "libmesh/bounding_box.h" #include "libmesh/mesh_tools.h" #include "libmesh/point.h" #include <typeinfo> registerMooseObject("MooseApp", TiledMeshGenerator); defineLegacyParams(TiledMeshGenerator); InputParameters TiledMeshGenerator::validParams() { InputParameters params = MeshGenerator::validParams(); params.addRequiredParam<MeshGeneratorName>("input", "The mesh we want to repeat"); // x boundary names params.addParam<BoundaryName>("left_boundary", "left", "name of the left (x) boundary"); params.addParam<BoundaryName>("right_boundary", "right", "name of the right (x) boundary"); // y boundary names params.addParam<BoundaryName>("top_boundary", "top", "name of the top (y) boundary"); params.addParam<BoundaryName>("bottom_boundary", "bottom", "name of the bottom (y) boundary"); // z boundary names params.addParam<BoundaryName>("front_boundary", "front", "name of the front (z) boundary"); params.addParam<BoundaryName>("back_boundary", "back", "name of the back (z) boundary"); // The number of tiles is 1 in each direction unless otherwise specified. // An x_tiles value of 1 means do not stitch any extra meshes together in // the x-direction. params.addParam<unsigned int>( "x_tiles", 1, "Number of tiles to stitch together (left to right) in the x-direction"); params.addParam<unsigned int>( "y_tiles", 1, "Number of tiles to stitch together (top to bottom) in the y-direction"); params.addParam<unsigned int>( "z_tiles", 1, "Number of tiles to stitch together (front to back) in the z-direction"); params.addClassDescription("Use the supplied mesh and create a tiled grid by repeating this mesh " "in the x,y, and z directions."); return params; } TiledMeshGenerator::TiledMeshGenerator(const InputParameters & parameters) : MeshGenerator(parameters), _input(getMesh("input")) { if (dynamic_pointer_cast<DistributedMesh>(_input) != nullptr) mooseError("TiledMeshGenerator only works with ReplicatedMesh."); } std::unique_ptr<MeshBase> TiledMeshGenerator::generate() { std::unique_ptr<MeshBase> initial_mesh = std::move(_input); std::unique_ptr<ReplicatedMesh> mesh = dynamic_pointer_cast<ReplicatedMesh>(initial_mesh); // Getting the x,y,z widths std::set<subdomain_id_type> sub_ids; mesh->subdomain_ids(sub_ids); BoundingBox bbox; for (auto id : sub_ids) { BoundingBox sub_bbox = MeshTools::create_subdomain_bounding_box(*mesh, id); bbox.union_with(sub_bbox); } _x_width = bbox.max()(0) - bbox.min()(0); _y_width = bbox.max()(1) - bbox.min()(1); _z_width = bbox.max()(2) - bbox.min()(2); boundary_id_type left = mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("left_boundary")); boundary_id_type right = mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("right_boundary")); boundary_id_type top = mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("top_boundary")); boundary_id_type bottom = mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("bottom_boundary")); boundary_id_type front = mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("front_boundary")); boundary_id_type back = mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("back_boundary")); { std::unique_ptr<MeshBase> clone = mesh->clone(); // Build X Tiles for (unsigned int i = 1; i < getParam<unsigned int>("x_tiles"); ++i) { MeshTools::Modification::translate(*clone, _x_width, 0, 0); mesh->stitch_meshes(dynamic_cast<ReplicatedMesh &>(*clone), right, left, TOLERANCE, /*clear_stitched_boundary_ids=*/true); } } { std::unique_ptr<MeshBase> clone = mesh->clone(); // Build Y Tiles for (unsigned int i = 1; i < getParam<unsigned int>("y_tiles"); ++i) { MeshTools::Modification::translate(*clone, 0, _y_width, 0); mesh->stitch_meshes(dynamic_cast<ReplicatedMesh &>(*clone), top, bottom, TOLERANCE, /*clear_stitched_boundary_ids=*/true); } } { std::unique_ptr<MeshBase> clone = mesh->clone(); // Build Z Tiles for (unsigned int i = 1; i < getParam<unsigned int>("z_tiles"); ++i) { MeshTools::Modification::translate(*clone, 0, 0, _z_width); mesh->stitch_meshes(dynamic_cast<ReplicatedMesh &>(*clone), front, back, TOLERANCE, /*clear_stitched_boundary_ids=*/true); } } return dynamic_pointer_cast<MeshBase>(mesh); } <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "UiConsoleManager.h" #include "ui_ConsoleWidget.h" #include "ConsoleProxyWidget.h" #include "ConsoleAPI.h" #include "UiAPI.h" #include "UiProxyWidget.h" #include "UiGraphicsView.h" #include "EventManager.h" #include "Framework.h" #include <QGraphicsView> #include <QString> #include <QRegExp> #include <QRectF> #include "MemoryLeakCheck.h" UiConsoleManager::UiConsoleManager(Foundation::Framework *fw) : framework(fw), graphicsView(fw->Ui()->GraphicsView()), consoleUi(0), consoleWidget(0), proxyWidget(0), visible(false), commandHistoryIndex(-1) { if (framework->IsHeadless()) return; consoleUi = new Ui::ConsoleWidget(); consoleWidget = new QWidget(); // Init internals consoleUi->setupUi(consoleWidget); proxyWidget = framework->Ui()->AddWidgetToScene(consoleWidget); proxyWidget->setMinimumHeight(0); proxyWidget->setGeometry(QRect(0, 0, graphicsView->width(), 0)); proxyWidget->setOpacity(0.8); ///<\todo Read opacity from config? proxyWidget->setZValue(20000); connect(framework->Ui()->GraphicsView(), SIGNAL(sceneRectChanged(const QRectF&)), SLOT(AdjustToSceneRect(const QRectF&))); // Init animation slideAnimation.setTargetObject(proxyWidget); slideAnimation.setPropertyName("geometry"); slideAnimation.setDuration(300); ///<\todo Read animation speed from config? connect(consoleUi->ConsoleInputArea, SIGNAL(returnPressed()), SLOT(HandleInput())); consoleUi->ConsoleInputArea->installEventFilter(this); } UiConsoleManager::~UiConsoleManager() { // consoleWidget gets deleted by the scene it is in currently if (consoleUi) SAFE_DELETE(consoleUi); } void UiConsoleManager::PrintToConsole(const QString &text) { if (framework->IsHeadless()) return; QString html = Qt::escape(text); DecorateString(html); consoleUi->ConsoleTextArea->appendHtml(html); } void UiConsoleManager::ToggleConsole() { if (framework->IsHeadless()) return; if (!graphicsView) return; QGraphicsScene *current_scene = proxyWidget->scene(); if (!current_scene) return; visible = !visible; int current_height = graphicsView->height()*0.5; if (visible) { slideAnimation.setStartValue(QRect(0, 0, graphicsView->width(), 0)); slideAnimation.setEndValue(QRect(0, 0, graphicsView->width(), current_height)); // Not bringing to front, works in UiProxyWidgets, hmm... current_scene->setActiveWindow(proxyWidget); current_scene->setFocusItem(proxyWidget, Qt::ActiveWindowFocusReason); consoleUi->ConsoleInputArea->setFocus(Qt::MouseFocusReason); proxyWidget->show(); } else { slideAnimation.setStartValue(QRect(0, 0, graphicsView->width(), current_height)); slideAnimation.setEndValue(QRect(0, 0, graphicsView->width(), 0)); proxyWidget->hide(); } slideAnimation.start(); } void UiConsoleManager::HandleInput() { if (framework->IsHeadless()) return; QString cmd = consoleUi->ConsoleInputArea->text(); framework->Console()->ExecuteCommand(cmd); consoleUi->ConsoleInputArea->clear(); commandHistory.push_front(cmd); } void UiConsoleManager::AdjustToSceneRect(const QRectF& rect) { if (visible) { QRectF new_size = rect; new_size.setHeight(rect.height() * 0.5); ///<\todo Read height from config? proxyWidget->setGeometry(new_size); } else { proxyWidget->hide(); } } bool UiConsoleManager::eventFilter(QObject *obj, QEvent *e) { if (e->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(e); if (keyEvent) { // if (keyEvent->isAutoRepeat()) // return true; switch(keyEvent->key()) { case Qt::Key_Up: { if (commandHistoryIndex+1 < commandHistory.size()) consoleUi->ConsoleInputArea->setText(commandHistory[++commandHistoryIndex]); return true; } case Qt::Key_Down: { --commandHistoryIndex; if (commandHistoryIndex < 0) commandHistoryIndex = -1; if (commandHistoryIndex == -1) consoleUi->ConsoleInputArea->clear(); // Putty-like behavior: clear line edit. else if (commandHistoryIndex > -1 && commandHistoryIndex < commandHistory.size()-1) consoleUi->ConsoleInputArea->setText(commandHistory[commandHistoryIndex]); return true; } ///\todo Autocompletion/suggestion //case Qt::Key_Tab: default: return QObject::eventFilter(obj, e); } } } return QObject::eventFilter(obj, e); } void UiConsoleManager::DecorateString(QString &str) { // Make all timestamp + module name blocks white int block_end_index = str.indexOf("]"); if (block_end_index != -1) { QString span_start("<span style='color:white;'>"); QString span_end("</span>"); block_end_index += span_start.length() + 1; str.insert(0, "<span style='color:white;'>"); str.insert(block_end_index, "</span>"); block_end_index += span_end.length(); } else block_end_index = 0; QRegExp regexp; regexp.setPattern(".*Debug:.*"); if (regexp.exactMatch(str)) { str.insert(block_end_index, "<FONT COLOR=\"#999999\">"); str.push_back("</FONT>"); return; } regexp.setPattern(".*Notice:.*"); if (regexp.exactMatch(str)) { str.insert(block_end_index, "<FONT COLOR=\"#0000FF\">"); str.push_back("</FONT>"); return; } regexp.setPattern(".*Warning:.*"); if (regexp.exactMatch(str)) { str.insert(block_end_index, "<FONT COLOR=\"#FFFF00\">"); str.push_back("</FONT>"); return; } regexp.setPattern(".*Error:.*"); if (regexp.exactMatch(str)) { str.insert(block_end_index, "<FONT COLOR=\"#FF3300\">"); str.push_back("</FONT>"); return; } regexp.setPattern(".*Critical:.*"); if (regexp.exactMatch(str)) { str.insert(block_end_index, "<FONT COLOR=\"#FF0000\">"); str.push_back("</FONT>"); return; } regexp.setPattern(".*Fatal:.*"); if (regexp.exactMatch(str)) { str.insert(block_end_index, "<FONT COLOR=\"#9933CC\">"); str.push_back("</FONT>"); return; } } <commit_msg>Fix erroneous signal-slot connection.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "UiConsoleManager.h" #include "ui_ConsoleWidget.h" #include "ConsoleProxyWidget.h" #include "ConsoleAPI.h" #include "UiAPI.h" #include "UiProxyWidget.h" #include "UiGraphicsView.h" #include "EventManager.h" #include "Framework.h" #include <QGraphicsView> #include <QString> #include <QRegExp> #include <QRectF> #include "MemoryLeakCheck.h" UiConsoleManager::UiConsoleManager(Foundation::Framework *fw) : framework(fw), graphicsView(fw->Ui()->GraphicsView()), consoleUi(0), consoleWidget(0), proxyWidget(0), visible(false), commandHistoryIndex(-1) { if (framework->IsHeadless()) return; consoleUi = new Ui::ConsoleWidget(); consoleWidget = new QWidget(); // Init internals consoleUi->setupUi(consoleWidget); proxyWidget = framework->Ui()->AddWidgetToScene(consoleWidget); proxyWidget->setMinimumHeight(0); proxyWidget->setGeometry(QRect(0, 0, graphicsView->width(), 0)); /// \todo Opacity has no effect atm. proxyWidget->setOpacity(0.8); ///<\todo Read opacity from config? proxyWidget->setZValue(20000); connect(framework->Ui()->GraphicsScene(), SIGNAL(sceneRectChanged(const QRectF&)), SLOT(AdjustToSceneRect(const QRectF&))); // Init animation slideAnimation.setTargetObject(proxyWidget); slideAnimation.setPropertyName("geometry"); slideAnimation.setDuration(300); ///<\todo Read animation speed from config? connect(consoleUi->ConsoleInputArea, SIGNAL(returnPressed()), SLOT(HandleInput())); consoleUi->ConsoleInputArea->installEventFilter(this); } UiConsoleManager::~UiConsoleManager() { // consoleWidget gets deleted by the scene it is in currently if (consoleUi) SAFE_DELETE(consoleUi); } void UiConsoleManager::PrintToConsole(const QString &text) { if (framework->IsHeadless()) return; QString html = Qt::escape(text); DecorateString(html); consoleUi->ConsoleTextArea->appendHtml(html); } void UiConsoleManager::ToggleConsole() { if (framework->IsHeadless()) return; if (!graphicsView) return; QGraphicsScene *current_scene = proxyWidget->scene(); if (!current_scene) return; visible = !visible; int current_height = graphicsView->height()*0.5; if (visible) { slideAnimation.setStartValue(QRect(0, 0, graphicsView->width(), 0)); slideAnimation.setEndValue(QRect(0, 0, graphicsView->width(), current_height)); // Not bringing to front, works in UiProxyWidgets, hmm... current_scene->setActiveWindow(proxyWidget); current_scene->setFocusItem(proxyWidget, Qt::ActiveWindowFocusReason); consoleUi->ConsoleInputArea->setFocus(Qt::MouseFocusReason); proxyWidget->show(); } else { slideAnimation.setStartValue(QRect(0, 0, graphicsView->width(), current_height)); slideAnimation.setEndValue(QRect(0, 0, graphicsView->width(), 0)); proxyWidget->hide(); } slideAnimation.start(); } void UiConsoleManager::HandleInput() { if (framework->IsHeadless()) return; QString cmd = consoleUi->ConsoleInputArea->text(); framework->Console()->ExecuteCommand(cmd); consoleUi->ConsoleInputArea->clear(); commandHistory.push_front(cmd); } void UiConsoleManager::AdjustToSceneRect(const QRectF& rect) { if (visible) { QRectF new_size = rect; new_size.setHeight(rect.height() * 0.5); ///<\todo Read height from config? proxyWidget->setGeometry(new_size); } else { proxyWidget->hide(); } } bool UiConsoleManager::eventFilter(QObject *obj, QEvent *e) { if (e->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(e); if (keyEvent) { // if (keyEvent->isAutoRepeat()) // return true; switch(keyEvent->key()) { case Qt::Key_Up: { if (commandHistoryIndex+1 < commandHistory.size()) consoleUi->ConsoleInputArea->setText(commandHistory[++commandHistoryIndex]); return true; } case Qt::Key_Down: { --commandHistoryIndex; if (commandHistoryIndex < 0) commandHistoryIndex = -1; if (commandHistoryIndex == -1) consoleUi->ConsoleInputArea->clear(); // Putty-like behavior: clear line edit. else if (commandHistoryIndex > -1 && commandHistoryIndex < commandHistory.size()-1) consoleUi->ConsoleInputArea->setText(commandHistory[commandHistoryIndex]); return true; } ///\todo Autocompletion/suggestion //case Qt::Key_Tab: default: return QObject::eventFilter(obj, e); } } } return QObject::eventFilter(obj, e); } void UiConsoleManager::DecorateString(QString &str) { // Make all timestamp + module name blocks white int block_end_index = str.indexOf("]"); if (block_end_index != -1) { QString span_start("<span style='color:white;'>"); QString span_end("</span>"); block_end_index += span_start.length() + 1; str.insert(0, "<span style='color:white;'>"); str.insert(block_end_index, "</span>"); block_end_index += span_end.length(); } else block_end_index = 0; QRegExp regexp; regexp.setPattern(".*Debug:.*"); if (regexp.exactMatch(str)) { str.insert(block_end_index, "<FONT COLOR=\"#999999\">"); str.push_back("</FONT>"); return; } regexp.setPattern(".*Notice:.*"); if (regexp.exactMatch(str)) { str.insert(block_end_index, "<FONT COLOR=\"#0000FF\">"); str.push_back("</FONT>"); return; } regexp.setPattern(".*Warning:.*"); if (regexp.exactMatch(str)) { str.insert(block_end_index, "<FONT COLOR=\"#FFFF00\">"); str.push_back("</FONT>"); return; } regexp.setPattern(".*Error:.*"); if (regexp.exactMatch(str)) { str.insert(block_end_index, "<FONT COLOR=\"#FF3300\">"); str.push_back("</FONT>"); return; } regexp.setPattern(".*Critical:.*"); if (regexp.exactMatch(str)) { str.insert(block_end_index, "<FONT COLOR=\"#FF0000\">"); str.push_back("</FONT>"); return; } regexp.setPattern(".*Fatal:.*"); if (regexp.exactMatch(str)) { str.insert(block_end_index, "<FONT COLOR=\"#9933CC\">"); str.push_back("</FONT>"); return; } } <|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "libmesh/libmesh_config.h" #ifdef LIBMESH_TRILINOS_HAVE_DTK #include "Moose.h" #include "DTKInterpolationEvaluator.h" #include "DTKInterpolationAdapter.h" #include "Transfer.h" #include "libmesh/mesh.h" #include "libmesh/numeric_vector.h" #include "libmesh/elem.h" #include <DTK_MeshTypes.hpp> #include <vector> DTKInterpolationAdapter::DTKInterpolationAdapter(Teuchos::RCP<const Teuchos::MpiComm<int> > in_comm, EquationSystems & in_es, const Point & offset, unsigned int from_dim): comm(in_comm), es(in_es), _offset(offset), mesh(in_es.get_mesh()), dim(mesh.mesh_dimension()) { MPI_Comm old_comm = Moose::swapLibMeshComm(*comm->getRawMpiComm()); std::set<GlobalOrdinal> semi_local_nodes; get_semi_local_nodes(semi_local_nodes); num_local_nodes = semi_local_nodes.size(); vertices.resize(num_local_nodes); Teuchos::ArrayRCP<double> coordinates(num_local_nodes * dim); Teuchos::ArrayRCP<double> target_coordinates(num_local_nodes * from_dim); // Fill in the vertices and coordinates { GlobalOrdinal i = 0; for (std::set<GlobalOrdinal>::iterator it = semi_local_nodes.begin(); it != semi_local_nodes.end(); ++it) { const Node & node = mesh.node(*it); vertices[i] = node.id(); for (GlobalOrdinal j=0; j<dim; j++) coordinates[(j*num_local_nodes) + i] = node(j) + offset(j); for (GlobalOrdinal j=0; j<from_dim; j++) target_coordinates[(j*num_local_nodes) + i] = node(j) + offset(j); i++; } } // Currently assuming all elements are the same! DataTransferKit::DTK_ElementTopology element_topology = get_element_topology(mesh.elem(0)); GlobalOrdinal n_nodes_per_elem = mesh.elem(0)->n_nodes(); GlobalOrdinal n_local_elem = mesh.n_local_elem(); elements.resize(n_local_elem); Teuchos::ArrayRCP<GlobalOrdinal> connectivity(n_nodes_per_elem*n_local_elem); Teuchos::ArrayRCP<double> elem_centroid_coordinates(n_local_elem*from_dim); // Fill in the elements and connectivity { GlobalOrdinal i = 0; MeshBase::const_element_iterator end = mesh.local_elements_end(); for (MeshBase::const_element_iterator it = mesh.local_elements_begin(); it != end; ++it) { const Elem & elem = *(*it); elements[i] = elem.id(); for (GlobalOrdinal j=0; j<n_nodes_per_elem; j++) connectivity[(j*n_local_elem)+i] = elem.node(j); { Point centroid = elem.centroid(); for (GlobalOrdinal j=0; j<from_dim; j++) elem_centroid_coordinates[(j*n_local_elem) + i] = centroid(j) + offset(j); } i++; } } Teuchos::ArrayRCP<int> permutation_list(n_nodes_per_elem); for (GlobalOrdinal i = 0; i < n_nodes_per_elem; ++i ) permutation_list[i] = i; /* Moose::out<<"n_nodes_per_elem: "<<n_nodes_per_elem<<std::endl; Moose::out<<"Dim: "<<dim<<std::endl; Moose::err<<"Vertices size: "<<vertices.size()<<std::endl; { Moose::err<<libMesh::processor_id()<<" Vertices: "; for (unsigned int i=0; i<vertices.size(); i++) Moose::err<<vertices[i]<<" "; Moose::err<<std::endl; } Moose::err<<"Coordinates size: "<<coordinates.size()<<std::endl; { Moose::err<<libMesh::processor_id()<<" Coordinates: "; for (unsigned int i=0; i<coordinates.size(); i++) Moose::err<<coordinates[i]<<" "; Moose::err<<std::endl; } Moose::err<<"Connectivity size: "<<connectivity.size()<<std::endl; { Moose::err<<libMesh::processor_id()<<" Connectivity: "; for (unsigned int i=0; i<connectivity.size(); i++) Moose::err<<connectivity[i]<<" "; Moose::err<<std::endl; } Moose::err<<"Permutation_List size: "<<permutation_list.size()<<std::endl; { Moose::err<<libMesh::processor_id()<<" Permutation_List: "; for (unsigned int i=0; i<permutation_list.size(); i++) Moose::err<<permutation_list[i]<<" "; Moose::err<<std::endl; } */ Teuchos::RCP<MeshContainerType> mesh_container = Teuchos::rcp( new MeshContainerType(dim, vertices, coordinates, element_topology, n_nodes_per_elem, elements, connectivity, permutation_list) ); // We only have 1 element topology in this grid so we make just one mesh block Teuchos::ArrayRCP<Teuchos::RCP<MeshContainerType> > mesh_blocks(1); mesh_blocks[0] = mesh_container; // Create the MeshManager mesh_manager = Teuchos::rcp(new DataTransferKit::MeshManager<MeshContainerType>(mesh_blocks, comm, dim) ); // Pack the coordinates into a field, this will be the positions we'll ask for other systems fields at if (from_dim == dim) target_coords = Teuchos::rcp(new DataTransferKit::FieldManager<MeshContainerType>(mesh_container, comm)); else { Teuchos::ArrayRCP<GlobalOrdinal> empty_elements(0); Teuchos::ArrayRCP<GlobalOrdinal> empty_connectivity(0); Teuchos::RCP<MeshContainerType> coords_only_mesh_container = Teuchos::rcp( new MeshContainerType(from_dim, vertices, target_coordinates, element_topology, n_nodes_per_elem, empty_elements, empty_connectivity, permutation_list) ); target_coords = Teuchos::rcp(new DataTransferKit::FieldManager<MeshContainerType>(coords_only_mesh_container, comm)); } { Teuchos::ArrayRCP<GlobalOrdinal> empty_elements(0); Teuchos::ArrayRCP<GlobalOrdinal> empty_connectivity(0); Teuchos::RCP<MeshContainerType> centroid_coords_only_mesh_container = Teuchos::rcp( new MeshContainerType(from_dim, elements, elem_centroid_coordinates, element_topology, n_nodes_per_elem, empty_elements, empty_connectivity, permutation_list) ); elem_centroid_coords = Teuchos::rcp(new DataTransferKit::FieldManager<MeshContainerType>(centroid_coords_only_mesh_container, comm)); } // Swap back Moose::swapLibMeshComm(old_comm); } DTKInterpolationAdapter::RCP_Evaluator DTKInterpolationAdapter::get_variable_evaluator(std::string var_name) { if (evaluators.find(var_name) == evaluators.end()) // We haven't created an evaluator for the variable yet { System * sys = Transfer::find_sys(es, var_name); // Create the FieldEvaluator evaluators[var_name] = Teuchos::rcp(new DTKInterpolationEvaluator(*sys, var_name, _offset)); } return evaluators[var_name]; } Teuchos::RCP<DataTransferKit::FieldManager<DTKInterpolationAdapter::FieldContainerType> > DTKInterpolationAdapter::get_values_to_fill(std::string var_name) { if (values_to_fill.find(var_name) == values_to_fill.end()) { System * sys = Transfer::find_sys(es, var_name); unsigned int var_num = sys->variable_number(var_name); bool is_nodal = sys->variable_type(var_num).family == LAGRANGE; Teuchos::ArrayRCP<double> data_space; if (is_nodal) data_space = Teuchos::ArrayRCP<double>(vertices.size()); else data_space = Teuchos::ArrayRCP<double>(elements.size()); Teuchos::RCP<FieldContainerType> field_container = Teuchos::rcp(new FieldContainerType(data_space, 1)); values_to_fill[var_name] = Teuchos::rcp(new DataTransferKit::FieldManager<FieldContainerType>(field_container, comm)); } return values_to_fill[var_name]; } void DTKInterpolationAdapter::update_variable_values(std::string var_name, Teuchos::ArrayView<GlobalOrdinal> missed_points) { MPI_Comm old_comm = Moose::swapLibMeshComm(*comm->getRawMpiComm()); System * sys = Transfer::find_sys(es, var_name); unsigned int var_num = sys->variable_number(var_name); bool is_nodal = sys->variable_type(var_num).family == LAGRANGE; Teuchos::RCP<FieldContainerType> values = values_to_fill[var_name]->field(); // Create a vector containing true or false for each point saying whether it was missed or not // We're only going to update values for points that were not missed std::vector<bool> missed(values->size(), false); for (Teuchos::ArrayView<const GlobalOrdinal>::const_iterator i=missed_points.begin(); i != missed_points.end(); ++i) missed[*i] = true; unsigned int i=0; // Loop over the values (one for each node) and assign the value of this variable at each node for (FieldContainerType::iterator it=values->begin(); it != values->end(); ++it) { // If this point "missed" then skip it if (missed[i]) { i++; continue; } const DofObject * dof_object = NULL; if (is_nodal) dof_object = mesh.node_ptr(vertices[i]); else dof_object = mesh.elem(elements[i]); if (dof_object->processor_id() == mesh.processor_id()) { // The 0 is for the component... this only works for LAGRANGE! dof_id_type dof = dof_object->dof_number(sys->number(), var_num, 0); sys->solution->set(dof, *it); } i++; } sys->solution->close(); // Swap back Moose::swapLibMeshComm(old_comm); } DataTransferKit::DTK_ElementTopology DTKInterpolationAdapter::get_element_topology(const Elem * elem) { ElemType type = elem->type(); if (type == EDGE2) return DataTransferKit::DTK_LINE_SEGMENT; else if (type == TRI3) return DataTransferKit::DTK_TRIANGLE; else if (type == QUAD4) return DataTransferKit::DTK_QUADRILATERAL; else if (type == TET4) return DataTransferKit::DTK_TETRAHEDRON; else if (type == HEX8) return DataTransferKit::DTK_HEXAHEDRON; else if (type == PYRAMID5) return DataTransferKit::DTK_PYRAMID; libMesh::err<<"Element type not supported by DTK!"<<std::endl; libmesh_error(); } void DTKInterpolationAdapter::get_semi_local_nodes(std::set<GlobalOrdinal> & semi_local_nodes) { MeshBase::const_element_iterator end = mesh.local_elements_end(); for (MeshBase::const_element_iterator it = mesh.local_elements_begin(); it != end; ++it) { const Elem & elem = *(*it); for (unsigned int j=0; j<elem.n_nodes(); j++) semi_local_nodes.insert(elem.node(j)); } } #endif // #ifdef LIBMESH_TRILINOS_HAVE_DTK <commit_msg>Added 2nd order element support to DTK Adapter, Issue #6004<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "libmesh/libmesh_config.h" #ifdef LIBMESH_TRILINOS_HAVE_DTK #include "Moose.h" #include "DTKInterpolationEvaluator.h" #include "DTKInterpolationAdapter.h" #include "Transfer.h" #include "libmesh/mesh.h" #include "libmesh/numeric_vector.h" #include "libmesh/elem.h" #include <DTK_MeshTypes.hpp> #include <vector> DTKInterpolationAdapter::DTKInterpolationAdapter(Teuchos::RCP<const Teuchos::MpiComm<int> > in_comm, EquationSystems & in_es, const Point & offset, unsigned int from_dim): comm(in_comm), es(in_es), _offset(offset), mesh(in_es.get_mesh()), dim(mesh.mesh_dimension()) { MPI_Comm old_comm = Moose::swapLibMeshComm(*comm->getRawMpiComm()); std::set<GlobalOrdinal> semi_local_nodes; get_semi_local_nodes(semi_local_nodes); num_local_nodes = semi_local_nodes.size(); vertices.resize(num_local_nodes); Teuchos::ArrayRCP<double> coordinates(num_local_nodes * dim); Teuchos::ArrayRCP<double> target_coordinates(num_local_nodes * from_dim); // Fill in the vertices and coordinates { GlobalOrdinal i = 0; for (std::set<GlobalOrdinal>::iterator it = semi_local_nodes.begin(); it != semi_local_nodes.end(); ++it) { const Node & node = mesh.node(*it); vertices[i] = node.id(); for (GlobalOrdinal j=0; j<dim; j++) coordinates[(j*num_local_nodes) + i] = node(j) + offset(j); for (GlobalOrdinal j=0; j<from_dim; j++) target_coordinates[(j*num_local_nodes) + i] = node(j) + offset(j); i++; } } // Currently assuming all elements are the same! DataTransferKit::DTK_ElementTopology element_topology = get_element_topology(mesh.elem(0)); GlobalOrdinal n_nodes_per_elem = mesh.elem(0)->n_nodes(); GlobalOrdinal n_local_elem = mesh.n_local_elem(); elements.resize(n_local_elem); Teuchos::ArrayRCP<GlobalOrdinal> connectivity(n_nodes_per_elem*n_local_elem); Teuchos::ArrayRCP<double> elem_centroid_coordinates(n_local_elem*from_dim); // Fill in the elements and connectivity { GlobalOrdinal i = 0; MeshBase::const_element_iterator end = mesh.local_elements_end(); for (MeshBase::const_element_iterator it = mesh.local_elements_begin(); it != end; ++it) { const Elem & elem = *(*it); elements[i] = elem.id(); for (GlobalOrdinal j=0; j<n_nodes_per_elem; j++) connectivity[(j*n_local_elem)+i] = elem.node(j); { Point centroid = elem.centroid(); for (GlobalOrdinal j=0; j<from_dim; j++) elem_centroid_coordinates[(j*n_local_elem) + i] = centroid(j) + offset(j); } i++; } } Teuchos::ArrayRCP<int> permutation_list(n_nodes_per_elem); for (GlobalOrdinal i = 0; i < n_nodes_per_elem; ++i ) permutation_list[i] = i; /* Moose::out<<"n_nodes_per_elem: "<<n_nodes_per_elem<<std::endl; Moose::out<<"Dim: "<<dim<<std::endl; Moose::err<<"Vertices size: "<<vertices.size()<<std::endl; { Moose::err<<libMesh::processor_id()<<" Vertices: "; for (unsigned int i=0; i<vertices.size(); i++) Moose::err<<vertices[i]<<" "; Moose::err<<std::endl; } Moose::err<<"Coordinates size: "<<coordinates.size()<<std::endl; { Moose::err<<libMesh::processor_id()<<" Coordinates: "; for (unsigned int i=0; i<coordinates.size(); i++) Moose::err<<coordinates[i]<<" "; Moose::err<<std::endl; } Moose::err<<"Connectivity size: "<<connectivity.size()<<std::endl; { Moose::err<<libMesh::processor_id()<<" Connectivity: "; for (unsigned int i=0; i<connectivity.size(); i++) Moose::err<<connectivity[i]<<" "; Moose::err<<std::endl; } Moose::err<<"Permutation_List size: "<<permutation_list.size()<<std::endl; { Moose::err<<libMesh::processor_id()<<" Permutation_List: "; for (unsigned int i=0; i<permutation_list.size(); i++) Moose::err<<permutation_list[i]<<" "; Moose::err<<std::endl; } */ Teuchos::RCP<MeshContainerType> mesh_container = Teuchos::rcp( new MeshContainerType(dim, vertices, coordinates, element_topology, n_nodes_per_elem, elements, connectivity, permutation_list) ); // We only have 1 element topology in this grid so we make just one mesh block Teuchos::ArrayRCP<Teuchos::RCP<MeshContainerType> > mesh_blocks(1); mesh_blocks[0] = mesh_container; // Create the MeshManager mesh_manager = Teuchos::rcp(new DataTransferKit::MeshManager<MeshContainerType>(mesh_blocks, comm, dim) ); // Pack the coordinates into a field, this will be the positions we'll ask for other systems fields at if (from_dim == dim) target_coords = Teuchos::rcp(new DataTransferKit::FieldManager<MeshContainerType>(mesh_container, comm)); else { Teuchos::ArrayRCP<GlobalOrdinal> empty_elements(0); Teuchos::ArrayRCP<GlobalOrdinal> empty_connectivity(0); Teuchos::RCP<MeshContainerType> coords_only_mesh_container = Teuchos::rcp( new MeshContainerType(from_dim, vertices, target_coordinates, element_topology, n_nodes_per_elem, empty_elements, empty_connectivity, permutation_list) ); target_coords = Teuchos::rcp(new DataTransferKit::FieldManager<MeshContainerType>(coords_only_mesh_container, comm)); } { Teuchos::ArrayRCP<GlobalOrdinal> empty_elements(0); Teuchos::ArrayRCP<GlobalOrdinal> empty_connectivity(0); Teuchos::RCP<MeshContainerType> centroid_coords_only_mesh_container = Teuchos::rcp( new MeshContainerType(from_dim, elements, elem_centroid_coordinates, element_topology, n_nodes_per_elem, empty_elements, empty_connectivity, permutation_list) ); elem_centroid_coords = Teuchos::rcp(new DataTransferKit::FieldManager<MeshContainerType>(centroid_coords_only_mesh_container, comm)); } // Swap back Moose::swapLibMeshComm(old_comm); } DTKInterpolationAdapter::RCP_Evaluator DTKInterpolationAdapter::get_variable_evaluator(std::string var_name) { if (evaluators.find(var_name) == evaluators.end()) // We haven't created an evaluator for the variable yet { System * sys = Transfer::find_sys(es, var_name); // Create the FieldEvaluator evaluators[var_name] = Teuchos::rcp(new DTKInterpolationEvaluator(*sys, var_name, _offset)); } return evaluators[var_name]; } Teuchos::RCP<DataTransferKit::FieldManager<DTKInterpolationAdapter::FieldContainerType> > DTKInterpolationAdapter::get_values_to_fill(std::string var_name) { if (values_to_fill.find(var_name) == values_to_fill.end()) { System * sys = Transfer::find_sys(es, var_name); unsigned int var_num = sys->variable_number(var_name); bool is_nodal = sys->variable_type(var_num).family == LAGRANGE; Teuchos::ArrayRCP<double> data_space; if (is_nodal) data_space = Teuchos::ArrayRCP<double>(vertices.size()); else data_space = Teuchos::ArrayRCP<double>(elements.size()); Teuchos::RCP<FieldContainerType> field_container = Teuchos::rcp(new FieldContainerType(data_space, 1)); values_to_fill[var_name] = Teuchos::rcp(new DataTransferKit::FieldManager<FieldContainerType>(field_container, comm)); } return values_to_fill[var_name]; } void DTKInterpolationAdapter::update_variable_values(std::string var_name, Teuchos::ArrayView<GlobalOrdinal> missed_points) { MPI_Comm old_comm = Moose::swapLibMeshComm(*comm->getRawMpiComm()); System * sys = Transfer::find_sys(es, var_name); unsigned int var_num = sys->variable_number(var_name); bool is_nodal = sys->variable_type(var_num).family == LAGRANGE; Teuchos::RCP<FieldContainerType> values = values_to_fill[var_name]->field(); // Create a vector containing true or false for each point saying whether it was missed or not // We're only going to update values for points that were not missed std::vector<bool> missed(values->size(), false); for (Teuchos::ArrayView<const GlobalOrdinal>::const_iterator i=missed_points.begin(); i != missed_points.end(); ++i) missed[*i] = true; unsigned int i=0; // Loop over the values (one for each node) and assign the value of this variable at each node for (FieldContainerType::iterator it=values->begin(); it != values->end(); ++it) { // If this point "missed" then skip it if (missed[i]) { i++; continue; } const DofObject * dof_object = NULL; if (is_nodal) dof_object = mesh.node_ptr(vertices[i]); else dof_object = mesh.elem(elements[i]); if (dof_object->processor_id() == mesh.processor_id()) { // The 0 is for the component... this only works for LAGRANGE! dof_id_type dof = dof_object->dof_number(sys->number(), var_num, 0); sys->solution->set(dof, *it); } i++; } sys->solution->close(); // Swap back Moose::swapLibMeshComm(old_comm); } DataTransferKit::DTK_ElementTopology DTKInterpolationAdapter::get_element_topology(const Elem * elem) { ElemType type = elem->type(); if (type == EDGE2) return DataTransferKit::DTK_LINE_SEGMENT; else if (type == TRI3) return DataTransferKit::DTK_TRIANGLE; else if (type == QUAD4) return DataTransferKit::DTK_QUADRILATERAL; else if (type == QUAD8) return DataTransferKit::DTK_QUADRILATERAL; else if (type == QUAD9) return DataTransferKit::DTK_QUADRILATERAL; else if (type == TET4) return DataTransferKit::DTK_TETRAHEDRON; else if (type == HEX8) return DataTransferKit::DTK_HEXAHEDRON; else if (type == HEX27) return DataTransferKit::DTK_HEXAHEDRON; else if (type == PYRAMID5) return DataTransferKit::DTK_PYRAMID; libMesh::err<<"Element type not supported by DTK!"<<std::endl; libmesh_error(); } void DTKInterpolationAdapter::get_semi_local_nodes(std::set<GlobalOrdinal> & semi_local_nodes) { MeshBase::const_element_iterator end = mesh.local_elements_end(); for (MeshBase::const_element_iterator it = mesh.local_elements_begin(); it != end; ++it) { const Elem & elem = *(*it); for (unsigned int j=0; j<elem.n_nodes(); j++) semi_local_nodes.insert(elem.node(j)); } } #endif // #ifdef LIBMESH_TRILINOS_HAVE_DTK <|endoftext|>
<commit_before>#include "log.hpp" #include "boost_root.hpp" #include "temporary.hpp" #include "cdm_boost.hpp" #include "cdm/cmake_generator.hpp" #include <boost/test/unit_test.hpp> #include <boost/range/adaptor/filtered.hpp> #include <silicium/sink/ostream_sink.hpp> #include <cdm/locate_cache.hpp> #include <ventura/cmake.hpp> #include <boost/algorithm/string/split.hpp> namespace { ventura::absolute_path const this_file = *ventura::absolute_path::create(__FILE__); ventura::absolute_path const test = *ventura::parent(this_file); ventura::absolute_path const repository = *ventura::parent(test); } BOOST_AUTO_TEST_CASE(test_using_cppnetlib_v2) { cdm::travis_keep_alive_printer keep_travis_alive; ventura::absolute_path const app_source = repository / "application/using_cppnetlib_v2"; ventura::absolute_path const app_cdm_source = app_source / "cdm"; ventura::absolute_path const tmp = cdm::get_temporary_root_for_testing() / "cdm"; ventura::absolute_path const module_temporaries = tmp / "mod"; ventura::absolute_path const application_build_dir = tmp / "using_cppnetlib_v2"; ventura::recreate_directories(module_temporaries, Si::throw_); ventura::recreate_directories(application_build_dir, Si::throw_); #if CDM_TESTS_RUNNING_ON_TRAVIS_CI auto output = Si::Sink<char, Si::success>::erase(Si::ostream_ref_sink(std::cerr)); #else std::unique_ptr<std::ofstream> log_file = cdm::open_log(application_build_dir / "test_using_cppnetlib_v2.txt"); auto output = cdm::make_program_output_printer(Si::ostream_ref_sink(*log_file)); #endif ventura::absolute_path const build_configure = module_temporaries / "build_configure"; ventura::recreate_directories(build_configure, Si::throw_); { std::vector<Si::noexcept_string> arguments; { ventura::absolute_path const include = repository / "dependencies/silicium"; arguments.emplace_back("-DSILICIUM_INCLUDE_DIR=" + ventura::to_utf8_string(include)); } { ventura::absolute_path const include = repository / "dependencies/ventura"; arguments.emplace_back("-DVENTURA_INCLUDE_DIR=" + ventura::to_utf8_string(include)); } Si::optional<ventura::absolute_path> const boost_root = cdm::get_boost_root_for_testing(); if (boost_root) { cdm::generate_cmake_definitions_for_using_boost(Si::make_container_sink(arguments), *boost_root); #if CDM_TESTS_RUNNING_ON_APPVEYOR arguments.emplace_back("-DBOOST_LIBRARYDIR=" + ventura::to_utf8_string(*boost_root / "lib32-msvc-14.0")); #endif } ventura::absolute_path const modules = repository / "modules"; arguments.emplace_back("-DCDM_CONFIGURE_INCLUDE_DIRS=" + ventura::to_utf8_string(modules) + ";" + ventura::to_utf8_string(repository)); arguments.emplace_back(ventura::to_utf8_string(app_cdm_source)); cdm::generate_default_cmake_generator_arguments(Si::make_container_sink(arguments)); BOOST_REQUIRE_EQUAL(0, ventura::run_process(ventura::cmake_exe, arguments, build_configure, output, std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(), ventura::environment_inheritance::inherit).get()); } { std::vector<Si::noexcept_string> arguments; arguments.emplace_back("--build"); arguments.emplace_back("."); BOOST_REQUIRE_EQUAL(0, ventura::run_process(ventura::cmake_exe, arguments, build_configure, output, std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(), ventura::environment_inheritance::inherit).get()); } { Si::noexcept_string generated_cmake_arguments; { std::vector<Si::noexcept_string> arguments; ventura::relative_path const relative( #ifdef _WIN32 "Debug/" #endif "configure" #ifdef _WIN32 ".exe" #endif ); auto configure_sink = Si::Sink<char, Si::success>::erase(Si::make_container_sink(generated_cmake_arguments)); ventura::process_parameters parameters; parameters.executable = build_configure / relative; parameters.arguments = ventura::arguments_to_os_strings(arguments); parameters.current_path = build_configure; parameters.err = &output; parameters.out = &configure_sink; BOOST_REQUIRE_EQUAL(0, ventura::run_process(parameters)); BOOST_REQUIRE(!generated_cmake_arguments.empty()); } { std::vector<Si::noexcept_string> arguments; boost::algorithm::split(arguments, generated_cmake_arguments, [](char c) { return c >= 0 && c <= ' '; }); BOOST_REQUIRE(!arguments.empty()); BOOST_REQUIRE(arguments.back().empty()); arguments.pop_back(); cdm::generate_default_cmake_generator_arguments(Si::make_container_sink(arguments)); BOOST_REQUIRE_EQUAL(0, ventura::run_process(ventura::cmake_exe, arguments, application_build_dir, output, std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(), ventura::environment_inheritance::inherit).get()); } } { std::vector<Si::noexcept_string> arguments; arguments.emplace_back("--build"); arguments.emplace_back("."); BOOST_REQUIRE_EQUAL(0, ventura::run_process(ventura::cmake_exe, arguments, application_build_dir, output, std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(), ventura::environment_inheritance::inherit).get()); } { std::vector<Si::os_string> arguments; ventura::relative_path const relative( #ifdef _WIN32 "Debug/" #endif "using_cppnetlib_v2" #ifdef _WIN32 ".exe" #endif ); BOOST_REQUIRE_EQUAL(0, ventura::run_process(application_build_dir / relative, arguments, application_build_dir, output, std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(), ventura::environment_inheritance::inherit)); } } <commit_msg>do not print boost build log to the console because that is too much for travis<commit_after>#include "log.hpp" #include "boost_root.hpp" #include "temporary.hpp" #include "cdm_boost.hpp" #include "cdm/cmake_generator.hpp" #include <boost/test/unit_test.hpp> #include <boost/range/adaptor/filtered.hpp> #include <silicium/sink/ostream_sink.hpp> #include <cdm/locate_cache.hpp> #include <ventura/cmake.hpp> #include <boost/algorithm/string/split.hpp> namespace { ventura::absolute_path const this_file = *ventura::absolute_path::create(__FILE__); ventura::absolute_path const test = *ventura::parent(this_file); ventura::absolute_path const repository = *ventura::parent(test); } BOOST_AUTO_TEST_CASE(test_using_cppnetlib_v2) { cdm::travis_keep_alive_printer keep_travis_alive; ventura::absolute_path const app_source = repository / "application/using_cppnetlib_v2"; ventura::absolute_path const app_cdm_source = app_source / "cdm"; ventura::absolute_path const tmp = cdm::get_temporary_root_for_testing() / "cdm"; ventura::absolute_path const module_temporaries = tmp / "mod"; ventura::absolute_path const application_build_dir = tmp / "using_cppnetlib_v2"; ventura::recreate_directories(module_temporaries, Si::throw_); ventura::recreate_directories(application_build_dir, Si::throw_); std::unique_ptr<std::ofstream> log_file = cdm::open_log(application_build_dir / "test_using_cppnetlib_v2.txt"); auto output = cdm::make_program_output_printer(Si::ostream_ref_sink(*log_file)); ventura::absolute_path const build_configure = module_temporaries / "build_configure"; ventura::recreate_directories(build_configure, Si::throw_); { std::vector<Si::noexcept_string> arguments; { ventura::absolute_path const include = repository / "dependencies/silicium"; arguments.emplace_back("-DSILICIUM_INCLUDE_DIR=" + ventura::to_utf8_string(include)); } { ventura::absolute_path const include = repository / "dependencies/ventura"; arguments.emplace_back("-DVENTURA_INCLUDE_DIR=" + ventura::to_utf8_string(include)); } Si::optional<ventura::absolute_path> const boost_root = cdm::get_boost_root_for_testing(); if (boost_root) { cdm::generate_cmake_definitions_for_using_boost(Si::make_container_sink(arguments), *boost_root); #if CDM_TESTS_RUNNING_ON_APPVEYOR arguments.emplace_back("-DBOOST_LIBRARYDIR=" + ventura::to_utf8_string(*boost_root / "lib32-msvc-14.0")); #endif } ventura::absolute_path const modules = repository / "modules"; arguments.emplace_back("-DCDM_CONFIGURE_INCLUDE_DIRS=" + ventura::to_utf8_string(modules) + ";" + ventura::to_utf8_string(repository)); arguments.emplace_back(ventura::to_utf8_string(app_cdm_source)); cdm::generate_default_cmake_generator_arguments(Si::make_container_sink(arguments)); BOOST_REQUIRE_EQUAL(0, ventura::run_process(ventura::cmake_exe, arguments, build_configure, output, std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(), ventura::environment_inheritance::inherit).get()); } { std::vector<Si::noexcept_string> arguments; arguments.emplace_back("--build"); arguments.emplace_back("."); BOOST_REQUIRE_EQUAL(0, ventura::run_process(ventura::cmake_exe, arguments, build_configure, output, std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(), ventura::environment_inheritance::inherit).get()); } { Si::noexcept_string generated_cmake_arguments; { std::vector<Si::noexcept_string> arguments; ventura::relative_path const relative( #ifdef _WIN32 "Debug/" #endif "configure" #ifdef _WIN32 ".exe" #endif ); auto configure_sink = Si::Sink<char, Si::success>::erase(Si::make_container_sink(generated_cmake_arguments)); ventura::process_parameters parameters; parameters.executable = build_configure / relative; parameters.arguments = ventura::arguments_to_os_strings(arguments); parameters.current_path = build_configure; auto console_output = Si::Sink<char, Si::success>::erase(Si::ostream_ref_sink(std::cerr)); parameters.err = &console_output; parameters.out = &configure_sink; BOOST_REQUIRE_EQUAL(0, ventura::run_process(parameters)); BOOST_REQUIRE(!generated_cmake_arguments.empty()); } { std::vector<Si::noexcept_string> arguments; boost::algorithm::split(arguments, generated_cmake_arguments, [](char c) { return c >= 0 && c <= ' '; }); BOOST_REQUIRE(!arguments.empty()); BOOST_REQUIRE(arguments.back().empty()); arguments.pop_back(); cdm::generate_default_cmake_generator_arguments(Si::make_container_sink(arguments)); BOOST_REQUIRE_EQUAL(0, ventura::run_process(ventura::cmake_exe, arguments, application_build_dir, output, std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(), ventura::environment_inheritance::inherit).get()); } } { std::vector<Si::noexcept_string> arguments; arguments.emplace_back("--build"); arguments.emplace_back("."); BOOST_REQUIRE_EQUAL(0, ventura::run_process(ventura::cmake_exe, arguments, application_build_dir, output, std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(), ventura::environment_inheritance::inherit).get()); } { std::vector<Si::os_string> arguments; ventura::relative_path const relative( #ifdef _WIN32 "Debug/" #endif "using_cppnetlib_v2" #ifdef _WIN32 ".exe" #endif ); BOOST_REQUIRE_EQUAL(0, ventura::run_process(application_build_dir / relative, arguments, application_build_dir, output, std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(), ventura::environment_inheritance::inherit)); } } <|endoftext|>
<commit_before>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Internal.hxx" #include "Request.hxx" #include "Handler.hxx" #include "http_upgrade.hxx" #include "pool.hxx" #include "strmap.hxx" #include "header_parser.hxx" #include "istream/istream_null.hxx" #include "http/List.hxx" #include "util/StringUtil.hxx" #include "util/StringView.hxx" #include <limits.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <sys/socket.h> inline bool HttpServerConnection::ParseRequestLine(const char *line, size_t length) { assert(request.read_state == Request::START); assert(request.request == nullptr); assert(!response.pending_drained); if (unlikely(length < 5)) { ProtocolError("malformed request line"); return false; } const char *eol = line + length; http_method_t method = HTTP_METHOD_NULL; switch (line[0]) { case 'D': if (likely(line[1] == 'E' && line[2] == 'L' && line[3] == 'E' && line[4] == 'T' && line[5] == 'E' && line[6] == ' ')) { method = HTTP_METHOD_DELETE; line += 7; } break; case 'G': if (likely(line[1] == 'E' && line[2] == 'T' && line[3] == ' ')) { method = HTTP_METHOD_GET; line += 4; } break; case 'P': if (likely(line[1] == 'O' && line[2] == 'S' && line[3] == 'T' && line[4] == ' ')) { method = HTTP_METHOD_POST; line += 5; } else if (line[1] == 'U' && line[2] == 'T' && line[3] == ' ') { method = HTTP_METHOD_PUT; line += 4; } else if (memcmp(line + 1, "ATCH ", 5) == 0) { method = HTTP_METHOD_PATCH; line += 6; } else if (memcmp(line + 1, "ROPFIND ", 8) == 0) { method = HTTP_METHOD_PROPFIND; line += 9; } else if (memcmp(line + 1, "ROPPATCH ", 9) == 0) { method = HTTP_METHOD_PROPPATCH; line += 10; } break; case 'H': if (likely(line[1] == 'E' && line[2] == 'A' && line[3] == 'D' && line[4] == ' ')) { method = HTTP_METHOD_HEAD; line += 5; } break; case 'O': if (memcmp(line + 1, "PTIONS ", 7) == 0) { method = HTTP_METHOD_OPTIONS; line += 8; } break; case 'T': if (memcmp(line + 1, "RACE ", 5) == 0) { method = HTTP_METHOD_TRACE; line += 6; } break; case 'M': if (memcmp(line + 1, "KCOL ", 5) == 0) { method = HTTP_METHOD_MKCOL; line += 6; } else if (memcmp(line + 1, "OVE ", 4) == 0) { method = HTTP_METHOD_MOVE; line += 5; } break; case 'C': if (memcmp(line + 1, "OPY ", 4) == 0) { method = HTTP_METHOD_COPY; line += 5; } break; case 'L': if (memcmp(line + 1, "OCK ", 4) == 0) { method = HTTP_METHOD_LOCK; line += 5; } break; case 'U': if (memcmp(line + 1, "NLOCK ", 6) == 0) { method = HTTP_METHOD_UNLOCK; line += 7; } break; } if (method == HTTP_METHOD_NULL) { /* invalid request method */ ProtocolError("unrecognized request method"); return false; } const char *space = (const char *)memchr(line, ' ', eol - line); if (unlikely(space == nullptr || space + 6 > line + length || memcmp(space + 1, "HTTP/", 5) != 0)) { /* refuse HTTP 0.9 requests */ static const char msg[] = "This server requires HTTP 1.1."; ssize_t nbytes = socket.Write(msg, sizeof(msg) - 1); if (nbytes != WRITE_DESTROYED) Done(); return false; } request.request = http_server_request_new(this, method, {line, space}); request.read_state = Request::HEADERS; request.http_1_0 = space + 9 <= line + length && space[8] == '0' && space[7] == '.' && space[6] == '1'; return true; } /** * @return false if the connection has been closed */ inline bool HttpServerConnection::HeadersFinished() { auto &r = *request.request; /* disable the idle+headers timeout; the request body timeout will be tracked by filtered_socket (auto-refreshing) */ idle_timeout.Cancel(); const char *value = r.headers.Get("expect"); request.expect_100_continue = value != nullptr && strcmp(value, "100-continue") == 0; request.expect_failed = value != nullptr && strcmp(value, "100-continue") != 0; value = r.headers.Get("connection"); /* we disable keep-alive support on ancient HTTP 1.0, because that feature was not well-defined and led to problems with some clients */ keep_alive = !request.http_1_0 && (value == nullptr || !http_list_contains_i(value, "close")); const bool upgrade = !request.http_1_0 && value != nullptr && http_is_upgrade(value); value = r.headers.Get("transfer-encoding"); const struct timeval *read_timeout = &http_server_read_timeout; off_t content_length = -1; const bool chunked = value != nullptr && strcasecmp(value, "chunked") == 0; if (!chunked) { value = r.headers.Get("content-length"); if (upgrade) { if (value != nullptr) { ProtocolError("cannot upgrade with Content-Length request header"); return false; } /* disable timeout */ read_timeout = nullptr; /* forward incoming data as-is */ keep_alive = false; } else if (value == nullptr) { /* no body at all */ r.body = nullptr; request.read_state = Request::END; return true; } else { char *endptr; content_length = strtoul(value, &endptr, 10); if (unlikely(*endptr != 0 || content_length < 0)) { ProtocolError("invalid Content-Length header in HTTP request"); return false; } if (content_length == 0) { /* empty body */ r.body = istream_null_new(&r.pool); request.read_state = Request::END; return true; } } } else if (upgrade) { ProtocolError("cannot upgrade chunked request"); return false; } request_body_reader = NewFromPool<RequestBodyReader>(r.pool, r.pool, *this); r.body = &request_body_reader->Init(GetEventLoop(), content_length, chunked); request.read_state = Request::BODY; /* for the request body, the FilteredSocket class tracks inactivity timeout */ socket.ScheduleReadTimeout(false, read_timeout); return true; } /** * @return false if the connection has been closed */ inline bool HttpServerConnection::HandleLine(const char *line, size_t length) { assert(request.read_state == Request::START || request.read_state == Request::HEADERS); if (unlikely(request.read_state == Request::START)) { assert(request.request == nullptr); return ParseRequestLine(line, length); } else if (likely(length > 0)) { assert(request.read_state == Request::HEADERS); assert(request.request != nullptr); header_parse_line(request.request->pool, request.request->headers, {line, length}); return true; } else { assert(request.read_state == Request::HEADERS); assert(request.request != nullptr); return HeadersFinished(); } } inline BufferedResult HttpServerConnection::FeedHeaders(const void *_data, size_t length) { assert(request.read_state == Request::START || request.read_state == Request::HEADERS); if (request.bytes_received >= 64 * 1024) { ProtocolError("too many request headers"); return BufferedResult::CLOSED; } const char *const buffer = (const char *)_data; const char *const buffer_end = buffer + length; const char *start = buffer, *end, *next = nullptr; while ((end = (const char *)memchr(start, '\n', buffer_end - start)) != nullptr) { next = end + 1; end = StripRight(start, end); if (!HandleLine(start, end - start)) return BufferedResult::CLOSED; if (request.read_state != Request::HEADERS) break; start = next; } size_t consumed = 0; if (next != nullptr) { consumed = next - buffer; request.bytes_received += consumed; socket.Consumed(consumed); } return request.read_state == Request::HEADERS ? BufferedResult::MORE : (consumed == length ? BufferedResult::OK : BufferedResult::PARTIAL); } inline bool HttpServerConnection::SubmitRequest() { if (request.read_state == Request::END) /* re-enable the event, to detect client disconnect while we're processing the request */ socket.ScheduleReadNoTimeout(false); const ScopePoolRef ref(*pool TRACE_ARGS); if (request.expect_failed) http_server_send_message(request.request, HTTP_STATUS_EXPECTATION_FAILED, "Unrecognized expectation"); else { request.in_handler = true; handler->HandleHttpRequest(*request.request, request.cancel_ptr); request.in_handler = false; } return IsValid(); } BufferedResult HttpServerConnection::Feed(const void *data, size_t length) { assert(!response.pending_drained); switch (request.read_state) { BufferedResult result; case Request::START: if (score == HTTP_SERVER_NEW) score = HTTP_SERVER_FIRST; case Request::HEADERS: result = FeedHeaders(data, length); if ((result == BufferedResult::OK || result == BufferedResult::PARTIAL) && (request.read_state == Request::BODY || request.read_state == Request::END)) { if (request.read_state == Request::BODY) result = request_body_reader->RequireMore() ? BufferedResult::AGAIN_EXPECT : BufferedResult::AGAIN_OPTIONAL; if (!SubmitRequest()) result = BufferedResult::CLOSED; } return result; case Request::BODY: return FeedRequestBody(data, length); case Request::END: /* check if the connection was closed by the client while we were processing the request */ if (socket.IsFull()) /* the buffer is full, the peer has been pipelining too much - that would disallow us to detect a disconnect; let's disable keep-alive now and discard all data */ keep_alive = false; if (!keep_alive) { /* discard all pipelined input when keep-alive has been disabled */ socket.Consumed(length); return BufferedResult::OK; } return BufferedResult::MORE; } assert(false); gcc_unreachable(); } DirectResult HttpServerConnection::TryRequestBodyDirect(int fd, FdType fd_type) { assert(IsValid()); assert(request.read_state == Request::BODY); assert(!response.pending_drained); if (!MaybeSend100Continue()) return DirectResult::CLOSED; ssize_t nbytes = request_body_reader->TryDirect(fd, fd_type); if (nbytes == ISTREAM_RESULT_BLOCKING) /* the destination fd blocks */ return DirectResult::BLOCKING; if (nbytes == ISTREAM_RESULT_CLOSED) /* the stream (and the whole connection) has been closed during the direct() callback (-3); no further checks */ return DirectResult::CLOSED; if (nbytes < 0) { if (errno == EAGAIN) return DirectResult::EMPTY; return DirectResult::ERRNO; } if (nbytes == ISTREAM_RESULT_EOF) return DirectResult::END; request.bytes_received += nbytes; if (request_body_reader->IsEOF()) { request.read_state = Request::END; request_body_reader->DestroyEof(); return IsValid() ? DirectResult::OK : DirectResult::CLOSED; } else { return DirectResult::OK; } } void HttpServerConnection::OnDeferredRead() { socket.Read(false); } <commit_msg>http_server/read: add [[fallthrough]] attribute<commit_after>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Internal.hxx" #include "Request.hxx" #include "Handler.hxx" #include "http_upgrade.hxx" #include "pool.hxx" #include "strmap.hxx" #include "header_parser.hxx" #include "istream/istream_null.hxx" #include "http/List.hxx" #include "util/StringUtil.hxx" #include "util/StringView.hxx" #include <limits.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <sys/socket.h> inline bool HttpServerConnection::ParseRequestLine(const char *line, size_t length) { assert(request.read_state == Request::START); assert(request.request == nullptr); assert(!response.pending_drained); if (unlikely(length < 5)) { ProtocolError("malformed request line"); return false; } const char *eol = line + length; http_method_t method = HTTP_METHOD_NULL; switch (line[0]) { case 'D': if (likely(line[1] == 'E' && line[2] == 'L' && line[3] == 'E' && line[4] == 'T' && line[5] == 'E' && line[6] == ' ')) { method = HTTP_METHOD_DELETE; line += 7; } break; case 'G': if (likely(line[1] == 'E' && line[2] == 'T' && line[3] == ' ')) { method = HTTP_METHOD_GET; line += 4; } break; case 'P': if (likely(line[1] == 'O' && line[2] == 'S' && line[3] == 'T' && line[4] == ' ')) { method = HTTP_METHOD_POST; line += 5; } else if (line[1] == 'U' && line[2] == 'T' && line[3] == ' ') { method = HTTP_METHOD_PUT; line += 4; } else if (memcmp(line + 1, "ATCH ", 5) == 0) { method = HTTP_METHOD_PATCH; line += 6; } else if (memcmp(line + 1, "ROPFIND ", 8) == 0) { method = HTTP_METHOD_PROPFIND; line += 9; } else if (memcmp(line + 1, "ROPPATCH ", 9) == 0) { method = HTTP_METHOD_PROPPATCH; line += 10; } break; case 'H': if (likely(line[1] == 'E' && line[2] == 'A' && line[3] == 'D' && line[4] == ' ')) { method = HTTP_METHOD_HEAD; line += 5; } break; case 'O': if (memcmp(line + 1, "PTIONS ", 7) == 0) { method = HTTP_METHOD_OPTIONS; line += 8; } break; case 'T': if (memcmp(line + 1, "RACE ", 5) == 0) { method = HTTP_METHOD_TRACE; line += 6; } break; case 'M': if (memcmp(line + 1, "KCOL ", 5) == 0) { method = HTTP_METHOD_MKCOL; line += 6; } else if (memcmp(line + 1, "OVE ", 4) == 0) { method = HTTP_METHOD_MOVE; line += 5; } break; case 'C': if (memcmp(line + 1, "OPY ", 4) == 0) { method = HTTP_METHOD_COPY; line += 5; } break; case 'L': if (memcmp(line + 1, "OCK ", 4) == 0) { method = HTTP_METHOD_LOCK; line += 5; } break; case 'U': if (memcmp(line + 1, "NLOCK ", 6) == 0) { method = HTTP_METHOD_UNLOCK; line += 7; } break; } if (method == HTTP_METHOD_NULL) { /* invalid request method */ ProtocolError("unrecognized request method"); return false; } const char *space = (const char *)memchr(line, ' ', eol - line); if (unlikely(space == nullptr || space + 6 > line + length || memcmp(space + 1, "HTTP/", 5) != 0)) { /* refuse HTTP 0.9 requests */ static const char msg[] = "This server requires HTTP 1.1."; ssize_t nbytes = socket.Write(msg, sizeof(msg) - 1); if (nbytes != WRITE_DESTROYED) Done(); return false; } request.request = http_server_request_new(this, method, {line, space}); request.read_state = Request::HEADERS; request.http_1_0 = space + 9 <= line + length && space[8] == '0' && space[7] == '.' && space[6] == '1'; return true; } /** * @return false if the connection has been closed */ inline bool HttpServerConnection::HeadersFinished() { auto &r = *request.request; /* disable the idle+headers timeout; the request body timeout will be tracked by filtered_socket (auto-refreshing) */ idle_timeout.Cancel(); const char *value = r.headers.Get("expect"); request.expect_100_continue = value != nullptr && strcmp(value, "100-continue") == 0; request.expect_failed = value != nullptr && strcmp(value, "100-continue") != 0; value = r.headers.Get("connection"); /* we disable keep-alive support on ancient HTTP 1.0, because that feature was not well-defined and led to problems with some clients */ keep_alive = !request.http_1_0 && (value == nullptr || !http_list_contains_i(value, "close")); const bool upgrade = !request.http_1_0 && value != nullptr && http_is_upgrade(value); value = r.headers.Get("transfer-encoding"); const struct timeval *read_timeout = &http_server_read_timeout; off_t content_length = -1; const bool chunked = value != nullptr && strcasecmp(value, "chunked") == 0; if (!chunked) { value = r.headers.Get("content-length"); if (upgrade) { if (value != nullptr) { ProtocolError("cannot upgrade with Content-Length request header"); return false; } /* disable timeout */ read_timeout = nullptr; /* forward incoming data as-is */ keep_alive = false; } else if (value == nullptr) { /* no body at all */ r.body = nullptr; request.read_state = Request::END; return true; } else { char *endptr; content_length = strtoul(value, &endptr, 10); if (unlikely(*endptr != 0 || content_length < 0)) { ProtocolError("invalid Content-Length header in HTTP request"); return false; } if (content_length == 0) { /* empty body */ r.body = istream_null_new(&r.pool); request.read_state = Request::END; return true; } } } else if (upgrade) { ProtocolError("cannot upgrade chunked request"); return false; } request_body_reader = NewFromPool<RequestBodyReader>(r.pool, r.pool, *this); r.body = &request_body_reader->Init(GetEventLoop(), content_length, chunked); request.read_state = Request::BODY; /* for the request body, the FilteredSocket class tracks inactivity timeout */ socket.ScheduleReadTimeout(false, read_timeout); return true; } /** * @return false if the connection has been closed */ inline bool HttpServerConnection::HandleLine(const char *line, size_t length) { assert(request.read_state == Request::START || request.read_state == Request::HEADERS); if (unlikely(request.read_state == Request::START)) { assert(request.request == nullptr); return ParseRequestLine(line, length); } else if (likely(length > 0)) { assert(request.read_state == Request::HEADERS); assert(request.request != nullptr); header_parse_line(request.request->pool, request.request->headers, {line, length}); return true; } else { assert(request.read_state == Request::HEADERS); assert(request.request != nullptr); return HeadersFinished(); } } inline BufferedResult HttpServerConnection::FeedHeaders(const void *_data, size_t length) { assert(request.read_state == Request::START || request.read_state == Request::HEADERS); if (request.bytes_received >= 64 * 1024) { ProtocolError("too many request headers"); return BufferedResult::CLOSED; } const char *const buffer = (const char *)_data; const char *const buffer_end = buffer + length; const char *start = buffer, *end, *next = nullptr; while ((end = (const char *)memchr(start, '\n', buffer_end - start)) != nullptr) { next = end + 1; end = StripRight(start, end); if (!HandleLine(start, end - start)) return BufferedResult::CLOSED; if (request.read_state != Request::HEADERS) break; start = next; } size_t consumed = 0; if (next != nullptr) { consumed = next - buffer; request.bytes_received += consumed; socket.Consumed(consumed); } return request.read_state == Request::HEADERS ? BufferedResult::MORE : (consumed == length ? BufferedResult::OK : BufferedResult::PARTIAL); } inline bool HttpServerConnection::SubmitRequest() { if (request.read_state == Request::END) /* re-enable the event, to detect client disconnect while we're processing the request */ socket.ScheduleReadNoTimeout(false); const ScopePoolRef ref(*pool TRACE_ARGS); if (request.expect_failed) http_server_send_message(request.request, HTTP_STATUS_EXPECTATION_FAILED, "Unrecognized expectation"); else { request.in_handler = true; handler->HandleHttpRequest(*request.request, request.cancel_ptr); request.in_handler = false; } return IsValid(); } BufferedResult HttpServerConnection::Feed(const void *data, size_t length) { assert(!response.pending_drained); switch (request.read_state) { BufferedResult result; case Request::START: if (score == HTTP_SERVER_NEW) score = HTTP_SERVER_FIRST; [[fallthrough]] case Request::HEADERS: result = FeedHeaders(data, length); if ((result == BufferedResult::OK || result == BufferedResult::PARTIAL) && (request.read_state == Request::BODY || request.read_state == Request::END)) { if (request.read_state == Request::BODY) result = request_body_reader->RequireMore() ? BufferedResult::AGAIN_EXPECT : BufferedResult::AGAIN_OPTIONAL; if (!SubmitRequest()) result = BufferedResult::CLOSED; } return result; case Request::BODY: return FeedRequestBody(data, length); case Request::END: /* check if the connection was closed by the client while we were processing the request */ if (socket.IsFull()) /* the buffer is full, the peer has been pipelining too much - that would disallow us to detect a disconnect; let's disable keep-alive now and discard all data */ keep_alive = false; if (!keep_alive) { /* discard all pipelined input when keep-alive has been disabled */ socket.Consumed(length); return BufferedResult::OK; } return BufferedResult::MORE; } assert(false); gcc_unreachable(); } DirectResult HttpServerConnection::TryRequestBodyDirect(int fd, FdType fd_type) { assert(IsValid()); assert(request.read_state == Request::BODY); assert(!response.pending_drained); if (!MaybeSend100Continue()) return DirectResult::CLOSED; ssize_t nbytes = request_body_reader->TryDirect(fd, fd_type); if (nbytes == ISTREAM_RESULT_BLOCKING) /* the destination fd blocks */ return DirectResult::BLOCKING; if (nbytes == ISTREAM_RESULT_CLOSED) /* the stream (and the whole connection) has been closed during the direct() callback (-3); no further checks */ return DirectResult::CLOSED; if (nbytes < 0) { if (errno == EAGAIN) return DirectResult::EMPTY; return DirectResult::ERRNO; } if (nbytes == ISTREAM_RESULT_EOF) return DirectResult::END; request.bytes_received += nbytes; if (request_body_reader->IsEOF()) { request.read_state = Request::END; request_body_reader->DestroyEof(); return IsValid() ? DirectResult::OK : DirectResult::CLOSED; } else { return DirectResult::OK; } } void HttpServerConnection::OnDeferredRead() { socket.Read(false); } <|endoftext|>
<commit_before>/* FUSE: Filesystem in Userspace Copyright (C) 2001-2007 Miklos Szeredi <miklos@szeredi.hu> This program can be distributed under the terms of the GNU GPL. See the file COPYING. gcc -Wall hello_ll.c `pkg-config fuse --cflags --libs` -o hello_ll */ #define FUSE_USE_VERSION 30 #include <map> #include <string> #include <deque> #include <vector> #include <fuse/fuse.h> #include <fuse/fuse_lowlevel.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <assert.h> #include <gasnet.h> /* * Helpers */ class Mutex { public: Mutex() { pthread_mutex_init(&mutex_, NULL); } void Lock() { pthread_mutex_lock(&mutex_); } void Unlock() { pthread_mutex_unlock(&mutex_); } private: pthread_mutex_t mutex_; }; class MutexLock { public: explicit MutexLock(Mutex *mutex) : mutex_(mutex) { mutex_->Lock(); } ~MutexLock() { mutex_->Unlock(); } private: Mutex *mutex_; }; #define GASNET_SAFE(fncall) do { \ int _retval; \ if ((_retval = fncall) != GASNET_OK) { \ fprintf(stderr, "ERROR calling: %s\n" \ " at: %s:%i\n" \ " error: %s (%s)\n", \ #fncall, __FILE__, __LINE__, \ gasnet_ErrorName(_retval), gasnet_ErrorDesc(_retval)); \ fflush(stderr); \ gasnet_exit(_retval); \ } \ } while(0) /* * Block Allocation * * The entire GASNet address space is divided into fixed size blocks. New * blocks are allocated from a free list, otherwise new blocks are assigned in * round-robin across all GASNet segments. */ #define BLOCK_SIZE 1048576 class BlockAllocator { public: struct Block { gasnet_node_t node; size_t addr; size_t size; }; BlockAllocator(gasnet_seginfo_t *segments, unsigned nsegments) { // FIXME: we don't really fill up the global address space at this point, // but it we need to be making sure that everything is aligned when we // approach the end of a segment. for (unsigned i = 0; i < nsegments; i++) { Node n; n.addr = (size_t)segments[i].addr; n.size = segments[i].size; n.curr = n.addr; nodes_.push_back(n); } curr_node = 0; num_nodes = nsegments; } int GetBlock(Block *bp) { MutexLock l(&mutex_); if (!free_blks_.empty()) { Block b = free_blks_.front(); free_blks_.pop_front(); *bp = b; return 0; } // node we are allocating from Node& n = nodes_[curr_node]; Block bb; bb.node = curr_node; bb.addr = n.curr; bb.size = BLOCK_SIZE; n.curr += BLOCK_SIZE; if (n.curr >= (n.addr + n.size)) return -ENOSPC; // next node to allocate from curr_node = (curr_node + 1) % num_nodes; *bp = bb; return 0; } void ReturnBlock(Block b) { MutexLock l(&mutex_); free_blks_.push_back(b); } private: struct Node { size_t addr; size_t size; size_t curr; }; std::deque<Block> free_blks_; unsigned curr_node, num_nodes; std::vector<Node> nodes_; Mutex mutex_; }; class Inode; static std::map<fuse_ino_t, Inode*> ino_inodes; class Inode { public: Inode() : ref_(1) {} void get() { assert(ref_); ref_++; printf("get: ino:%lu ref:%ld\n", ino, ref_); fflush(0); } void put(long int dec = 1) { assert(ref_); ref_ -= dec; assert(ref_ >= 0); printf("put: ino:%lu ref:%ld\n", ino, ref_); fflush(0); if (ref_ == 0) { assert(ino_inodes.count(ino)); ino_inodes.erase(ino); delete this; } } fuse_ino_t ino; struct stat i_st; private: long int ref_; }; static std::map<std::string, Inode*> path_inodes; static fuse_ino_t next_inode_num = FUSE_ROOT_ID + 1; static pthread_mutex_t mutex; /* * */ static void ll_create(fuse_req_t req, fuse_ino_t parent, const char *name, mode_t mode, struct fuse_file_info *fi) { assert(parent == FUSE_ROOT_ID); printf("create: parent:%lu name:%s\n", parent, name); fflush(0); pthread_mutex_lock(&mutex); Inode *in; std::string fname(name); if (path_inodes.count(fname) == 0) { in = new Inode; memset(&in->i_st, 0, sizeof(in->i_st)); in->ino = next_inode_num++; in->get(); path_inodes[fname] = in; ino_inodes[in->ino] = in; } else assert(0); in->i_st.st_ino = in->ino; in->i_st.st_mode = S_IFREG | 0666; in->i_st.st_nlink = 1; in->i_st.st_blksize = 4096; struct fuse_entry_param fe; memset(&fe, 0, sizeof(fe)); fe.attr = in->i_st; fe.ino = fe.attr.st_ino; fe.generation = 1; fe.entry_timeout = 1.0; fuse_reply_create(req, &fe, fi); pthread_mutex_unlock(&mutex); } static void ll_release(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) { printf("release: %lu\n", ino); fflush(0); pthread_mutex_lock(&mutex); assert(ino_inodes.count(ino)); Inode *in = ino_inodes[ino]; in->put(); fuse_reply_err(req, 0); pthread_mutex_unlock(&mutex); } static void ll_unlink(fuse_req_t req, fuse_ino_t parent, const char *name) { printf("unlink: parent:%lu name:%s\n", parent, name); fflush(0); pthread_mutex_lock(&mutex); std::string fname(name); if (path_inodes.count(fname)) { path_inodes.erase(fname); fuse_reply_err(req, 0); } else fuse_reply_err(req, ENOENT); pthread_mutex_unlock(&mutex); } static void ll_forget(fuse_req_t req, fuse_ino_t ino, long unsigned nlookup) { printf("forget: ino:%lu nlookup:%lu\n", ino, nlookup); fflush(0); pthread_mutex_lock(&mutex); assert(ino_inodes.count(ino)); Inode *in = ino_inodes[ino]; in->put(nlookup); pthread_mutex_unlock(&mutex); fuse_reply_none(req); } static void hello_ll_getattr(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) { printf("getattr: ino:%lu\n", ino); fflush(0); pthread_mutex_lock(&mutex); if (ino_inodes.count(ino)) { Inode *in = ino_inodes[ino]; fuse_reply_attr(req, &in->i_st, 0); } else fuse_reply_err(req, ENOENT); pthread_mutex_unlock(&mutex); } static void hello_ll_lookup(fuse_req_t req, fuse_ino_t parent, const char *name) { printf("lookup: parent:%lu, name:%s\n", parent, name); fflush(0); pthread_mutex_lock(&mutex); std::string fname(name); if (path_inodes.count(fname)) { Inode *in = path_inodes[fname]; assert(ino_inodes.count(in->ino)); assert(ino_inodes[in->ino] == in); struct fuse_entry_param fe; memset(&fe, 0, sizeof(fe)); fe.attr = in->i_st; fe.ino = in->ino; fe.generation = 1; in->get(); fuse_reply_entry(req, &fe); } else fuse_reply_err(req, ENOENT); pthread_mutex_unlock(&mutex); } struct dirbuf { char *p; size_t size; }; static void dirbuf_add(fuse_req_t req, struct dirbuf *b, const char *name, fuse_ino_t ino) { struct stat stbuf; size_t oldsize = b->size; b->size += fuse_add_direntry(req, NULL, 0, name, NULL, 0); b->p = (char *) realloc(b->p, b->size); memset(&stbuf, 0, sizeof(stbuf)); stbuf.st_ino = ino; fuse_add_direntry(req, b->p + oldsize, b->size - oldsize, name, &stbuf, b->size); } #define min(x, y) ((x) < (y) ? (x) : (y)) static int reply_buf_limited(fuse_req_t req, const char *buf, size_t bufsize, off_t off, size_t maxsize) { if (off < bufsize) return fuse_reply_buf(req, buf + off, min(bufsize - off, maxsize)); else return fuse_reply_buf(req, NULL, 0); } /* * */ static void hello_ll_readdir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, struct fuse_file_info *fi) { assert(ino == FUSE_ROOT_ID); printf("readdir: ino:%lu\n", ino); fflush(0); pthread_mutex_lock(&mutex); struct dirbuf b; memset(&b, 0, sizeof(b)); dirbuf_add(req, &b, ".", 1); dirbuf_add(req, &b, "..", 1); for (std::map<std::string, Inode*>::const_iterator it = path_inodes.begin(); it != path_inodes.end(); it++) { dirbuf_add(req, &b, it->first.c_str(), strlen(it->first.c_str())); } reply_buf_limited(req, b.p, b.size, off, size); free(b.p); pthread_mutex_unlock(&mutex); } static void hello_ll_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) { printf("open: %lu\n", ino); fflush(0); pthread_mutex_lock(&mutex); assert(!(fi->flags & O_CREAT)); if (ino_inodes.count(ino)) { Inode *in = ino_inodes[ino]; in->get(); fuse_reply_open(req, fi); } else fuse_reply_err(req, ENOENT); pthread_mutex_unlock(&mutex); } static void hello_ll_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, struct fuse_file_info *fi) { (void) fi; printf("read: %lu\n", ino); fflush(0); assert(ino == 2); static const char *hello_str = "asdf"; reply_buf_limited(req, hello_str, strlen(hello_str), off, size); } int main(int argc, char *argv[]) { GASNET_SAFE(gasnet_init(&argc, &argv)); size_t segsz = gasnet_getMaxLocalSegmentSize(); GASNET_SAFE(gasnet_attach(NULL, 0, segsz, 0)); if (gasnet_mynode()) { gasnet_barrier_notify(0,GASNET_BARRIERFLAG_ANONYMOUS); gasnet_barrier_wait(0,GASNET_BARRIERFLAG_ANONYMOUS); gasnet_exit(0); exit(0); } assert(gasnet_mynode() == 0); gasnet_seginfo_t segments[gasnet_nodes()]; GASNET_SAFE(gasnet_getSegmentInfo(segments, gasnet_nodes())); struct fuse_args args = FUSE_ARGS_INIT(argc, argv); struct fuse_chan *ch; char *mountpoint; int err = -1; struct fuse_lowlevel_ops hello_ll_oper; memset(&hello_ll_oper, 0, sizeof(hello_ll_oper)); hello_ll_oper.lookup= hello_ll_lookup; hello_ll_oper.getattr= hello_ll_getattr; hello_ll_oper.readdir= hello_ll_readdir; hello_ll_oper.open= hello_ll_open; hello_ll_oper.read= hello_ll_read; hello_ll_oper.create= ll_create; hello_ll_oper.release = ll_release; hello_ll_oper.unlink = ll_unlink; hello_ll_oper.forget = ll_forget; pthread_mutex_init(&mutex, NULL); // add root inode Inode *root = new Inode; root->ino = FUSE_ROOT_ID; root->i_st.st_mode = S_IFDIR | 0755; root->i_st.st_nlink = 2; ino_inodes[root->ino] = root; if (fuse_parse_cmdline(&args, &mountpoint, NULL, NULL) != -1 && (ch = fuse_mount(mountpoint, &args)) != NULL) { struct fuse_session *se; se = fuse_lowlevel_new(&args, &hello_ll_oper, sizeof(hello_ll_oper), NULL); if (se != NULL) { if (fuse_set_signal_handlers(se) != -1) { fuse_session_add_chan(se, ch); err = fuse_session_loop(se); fuse_remove_signal_handlers(se); fuse_session_remove_chan(ch); } fuse_session_destroy(se); } fuse_unmount(mountpoint, ch); } fuse_opt_free_args(&args); return err ? 1 : 0; } <commit_msg>fs: clean-up gasnet exit paths<commit_after>/* FUSE: Filesystem in Userspace Copyright (C) 2001-2007 Miklos Szeredi <miklos@szeredi.hu> This program can be distributed under the terms of the GNU GPL. See the file COPYING. gcc -Wall hello_ll.c `pkg-config fuse --cflags --libs` -o hello_ll */ #define FUSE_USE_VERSION 30 #include <map> #include <string> #include <deque> #include <vector> #include <fuse/fuse.h> #include <fuse/fuse_lowlevel.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <assert.h> #include <gasnet.h> /* * Helpers */ class Mutex { public: Mutex() { pthread_mutex_init(&mutex_, NULL); } void Lock() { pthread_mutex_lock(&mutex_); } void Unlock() { pthread_mutex_unlock(&mutex_); } private: pthread_mutex_t mutex_; }; class MutexLock { public: explicit MutexLock(Mutex *mutex) : mutex_(mutex) { mutex_->Lock(); } ~MutexLock() { mutex_->Unlock(); } private: Mutex *mutex_; }; #define GASNET_SAFE(fncall) do { \ int _retval; \ if ((_retval = fncall) != GASNET_OK) { \ fprintf(stderr, "ERROR calling: %s\n" \ " at: %s:%i\n" \ " error: %s (%s)\n", \ #fncall, __FILE__, __LINE__, \ gasnet_ErrorName(_retval), gasnet_ErrorDesc(_retval)); \ fflush(stderr); \ gasnet_exit(_retval); \ } \ } while(0) /* * Block Allocation * * The entire GASNet address space is divided into fixed size blocks. New * blocks are allocated from a free list, otherwise new blocks are assigned in * round-robin across all GASNet segments. */ #define BLOCK_SIZE 1048576 class BlockAllocator { public: struct Block { gasnet_node_t node; size_t addr; size_t size; }; BlockAllocator(gasnet_seginfo_t *segments, unsigned nsegments) { // FIXME: we don't really fill up the global address space at this point, // but it we need to be making sure that everything is aligned when we // approach the end of a segment. for (unsigned i = 0; i < nsegments; i++) { Node n; n.addr = (size_t)segments[i].addr; n.size = segments[i].size; n.curr = n.addr; nodes_.push_back(n); } curr_node = 0; num_nodes = nsegments; } int GetBlock(Block *bp) { MutexLock l(&mutex_); if (!free_blks_.empty()) { Block b = free_blks_.front(); free_blks_.pop_front(); *bp = b; return 0; } // node we are allocating from Node& n = nodes_[curr_node]; Block bb; bb.node = curr_node; bb.addr = n.curr; bb.size = BLOCK_SIZE; n.curr += BLOCK_SIZE; if (n.curr >= (n.addr + n.size)) return -ENOSPC; // next node to allocate from curr_node = (curr_node + 1) % num_nodes; *bp = bb; return 0; } void ReturnBlock(Block b) { MutexLock l(&mutex_); free_blks_.push_back(b); } private: struct Node { size_t addr; size_t size; size_t curr; }; std::deque<Block> free_blks_; unsigned curr_node, num_nodes; std::vector<Node> nodes_; Mutex mutex_; }; class Inode; static std::map<fuse_ino_t, Inode*> ino_inodes; class Inode { public: Inode() : ref_(1) {} void get() { assert(ref_); ref_++; printf("get: ino:%lu ref:%ld\n", ino, ref_); fflush(0); } void put(long int dec = 1) { assert(ref_); ref_ -= dec; assert(ref_ >= 0); printf("put: ino:%lu ref:%ld\n", ino, ref_); fflush(0); if (ref_ == 0) { assert(ino_inodes.count(ino)); ino_inodes.erase(ino); delete this; } } fuse_ino_t ino; struct stat i_st; private: long int ref_; }; static std::map<std::string, Inode*> path_inodes; static fuse_ino_t next_inode_num = FUSE_ROOT_ID + 1; static pthread_mutex_t mutex; /* * */ static void ll_create(fuse_req_t req, fuse_ino_t parent, const char *name, mode_t mode, struct fuse_file_info *fi) { assert(parent == FUSE_ROOT_ID); printf("create: parent:%lu name:%s\n", parent, name); fflush(0); pthread_mutex_lock(&mutex); Inode *in; std::string fname(name); if (path_inodes.count(fname) == 0) { in = new Inode; memset(&in->i_st, 0, sizeof(in->i_st)); in->ino = next_inode_num++; in->get(); path_inodes[fname] = in; ino_inodes[in->ino] = in; } else assert(0); in->i_st.st_ino = in->ino; in->i_st.st_mode = S_IFREG | 0666; in->i_st.st_nlink = 1; in->i_st.st_blksize = 4096; struct fuse_entry_param fe; memset(&fe, 0, sizeof(fe)); fe.attr = in->i_st; fe.ino = fe.attr.st_ino; fe.generation = 1; fe.entry_timeout = 1.0; fuse_reply_create(req, &fe, fi); pthread_mutex_unlock(&mutex); } static void ll_release(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) { printf("release: %lu\n", ino); fflush(0); pthread_mutex_lock(&mutex); assert(ino_inodes.count(ino)); Inode *in = ino_inodes[ino]; in->put(); fuse_reply_err(req, 0); pthread_mutex_unlock(&mutex); } static void ll_unlink(fuse_req_t req, fuse_ino_t parent, const char *name) { printf("unlink: parent:%lu name:%s\n", parent, name); fflush(0); pthread_mutex_lock(&mutex); std::string fname(name); if (path_inodes.count(fname)) { path_inodes.erase(fname); fuse_reply_err(req, 0); } else fuse_reply_err(req, ENOENT); pthread_mutex_unlock(&mutex); } static void ll_forget(fuse_req_t req, fuse_ino_t ino, long unsigned nlookup) { printf("forget: ino:%lu nlookup:%lu\n", ino, nlookup); fflush(0); pthread_mutex_lock(&mutex); assert(ino_inodes.count(ino)); Inode *in = ino_inodes[ino]; in->put(nlookup); pthread_mutex_unlock(&mutex); fuse_reply_none(req); } static void hello_ll_getattr(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) { printf("getattr: ino:%lu\n", ino); fflush(0); pthread_mutex_lock(&mutex); if (ino_inodes.count(ino)) { Inode *in = ino_inodes[ino]; fuse_reply_attr(req, &in->i_st, 0); } else fuse_reply_err(req, ENOENT); pthread_mutex_unlock(&mutex); } static void hello_ll_lookup(fuse_req_t req, fuse_ino_t parent, const char *name) { printf("lookup: parent:%lu, name:%s\n", parent, name); fflush(0); pthread_mutex_lock(&mutex); std::string fname(name); if (path_inodes.count(fname)) { Inode *in = path_inodes[fname]; assert(ino_inodes.count(in->ino)); assert(ino_inodes[in->ino] == in); struct fuse_entry_param fe; memset(&fe, 0, sizeof(fe)); fe.attr = in->i_st; fe.ino = in->ino; fe.generation = 1; in->get(); fuse_reply_entry(req, &fe); } else fuse_reply_err(req, ENOENT); pthread_mutex_unlock(&mutex); } struct dirbuf { char *p; size_t size; }; static void dirbuf_add(fuse_req_t req, struct dirbuf *b, const char *name, fuse_ino_t ino) { struct stat stbuf; size_t oldsize = b->size; b->size += fuse_add_direntry(req, NULL, 0, name, NULL, 0); b->p = (char *) realloc(b->p, b->size); memset(&stbuf, 0, sizeof(stbuf)); stbuf.st_ino = ino; fuse_add_direntry(req, b->p + oldsize, b->size - oldsize, name, &stbuf, b->size); } #define min(x, y) ((x) < (y) ? (x) : (y)) static int reply_buf_limited(fuse_req_t req, const char *buf, size_t bufsize, off_t off, size_t maxsize) { if (off < bufsize) return fuse_reply_buf(req, buf + off, min(bufsize - off, maxsize)); else return fuse_reply_buf(req, NULL, 0); } /* * */ static void hello_ll_readdir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, struct fuse_file_info *fi) { assert(ino == FUSE_ROOT_ID); printf("readdir: ino:%lu\n", ino); fflush(0); pthread_mutex_lock(&mutex); struct dirbuf b; memset(&b, 0, sizeof(b)); dirbuf_add(req, &b, ".", 1); dirbuf_add(req, &b, "..", 1); for (std::map<std::string, Inode*>::const_iterator it = path_inodes.begin(); it != path_inodes.end(); it++) { dirbuf_add(req, &b, it->first.c_str(), strlen(it->first.c_str())); } reply_buf_limited(req, b.p, b.size, off, size); free(b.p); pthread_mutex_unlock(&mutex); } static void hello_ll_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) { printf("open: %lu\n", ino); fflush(0); pthread_mutex_lock(&mutex); assert(!(fi->flags & O_CREAT)); if (ino_inodes.count(ino)) { Inode *in = ino_inodes[ino]; in->get(); fuse_reply_open(req, fi); } else fuse_reply_err(req, ENOENT); pthread_mutex_unlock(&mutex); } static void hello_ll_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, struct fuse_file_info *fi) { (void) fi; printf("read: %lu\n", ino); fflush(0); assert(ino == 2); static const char *hello_str = "asdf"; reply_buf_limited(req, hello_str, strlen(hello_str), off, size); } int main(int argc, char *argv[]) { GASNET_SAFE(gasnet_init(&argc, &argv)); size_t segsz = gasnet_getMaxLocalSegmentSize(); GASNET_SAFE(gasnet_attach(NULL, 0, segsz, 0)); if (gasnet_mynode()) { gasnet_barrier_notify(0, GASNET_BARRIERFLAG_ANONYMOUS); gasnet_barrier_wait(0, GASNET_BARRIERFLAG_ANONYMOUS); gasnet_exit(0); return 0; } assert(gasnet_mynode() == 0); gasnet_seginfo_t segments[gasnet_nodes()]; GASNET_SAFE(gasnet_getSegmentInfo(segments, gasnet_nodes())); struct fuse_args args = FUSE_ARGS_INIT(argc, argv); struct fuse_chan *ch; char *mountpoint; int err = -1; struct fuse_lowlevel_ops hello_ll_oper; memset(&hello_ll_oper, 0, sizeof(hello_ll_oper)); hello_ll_oper.lookup= hello_ll_lookup; hello_ll_oper.getattr= hello_ll_getattr; hello_ll_oper.readdir= hello_ll_readdir; hello_ll_oper.open= hello_ll_open; hello_ll_oper.read= hello_ll_read; hello_ll_oper.create= ll_create; hello_ll_oper.release = ll_release; hello_ll_oper.unlink = ll_unlink; hello_ll_oper.forget = ll_forget; pthread_mutex_init(&mutex, NULL); // add root inode Inode *root = new Inode; root->ino = FUSE_ROOT_ID; root->i_st.st_mode = S_IFDIR | 0755; root->i_st.st_nlink = 2; ino_inodes[root->ino] = root; if (fuse_parse_cmdline(&args, &mountpoint, NULL, NULL) != -1 && (ch = fuse_mount(mountpoint, &args)) != NULL) { struct fuse_session *se; se = fuse_lowlevel_new(&args, &hello_ll_oper, sizeof(hello_ll_oper), NULL); if (se != NULL) { if (fuse_set_signal_handlers(se) != -1) { fuse_session_add_chan(se, ch); err = fuse_session_loop(se); fuse_remove_signal_handlers(se); fuse_session_remove_chan(ch); } fuse_session_destroy(se); } fuse_unmount(mountpoint, ch); } fuse_opt_free_args(&args); gasnet_barrier_notify(0, GASNET_BARRIERFLAG_ANONYMOUS); gasnet_barrier_wait(0, GASNET_BARRIERFLAG_ANONYMOUS); int rv = err ? 1 : 0; gasnet_exit(rv); return rv; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <ctime> #include "Util/Random.h" #include "Util/Config.h" #include "Util/Singleton.h" #include "World/Generators/Noise.h" #include "Application.h" #include "Display.h" #include "Util/Native.h" #ifdef __WIN32 extern "C" { //Enable dedicated graphics __declspec(dllexport) bool NvOptimusEnablement = true; __declspec(dllexport) bool AmdPowerXpressRequestHighPerformance = true; } #endif // __WIN32 namespace { void noiseTest(int trials) { Random::init(); Noise::Generator m_noiseGen; m_noiseGen.setSeed(Random::intInRange(0, 999999)); m_noiseGen.setNoiseFunction({5, 500, 0.4, 5000}); float total = 0; std::vector<double> test; for (int i = 0 ; i < trials ; i++) { float h = m_noiseGen.getValue(i, i, i, i); test.push_back(h); total += h; } std::cout << "MIN: " << *std::min_element(test.begin(), test.end()) << "\n"; std::cout << "MAX: " << *std::max_element(test.begin(), test.end()) << "\n"; std::cout << "AVG: " << total / trials << std::endl; } void errorMessage(const std::string& message) { #ifdef __WIN32 MessageBox(nullptr, message.c_str(), "Error", MB_OK); #else // __WIN32 std::cerr << message << std::endl; #endif /** @TODO Put correct headers for these bad boys #elif __linux const std::string command = "zenity --error --text \"" + message + "\""; system(command.c_str()); #elif __APPLE__ const std::string command = "osascript -e 'tell app \"System Events\" to display dialog \"" + message + "\" buttons {\"OK\"} default button 1 with icon caution with title \"Error\"'"; system(command.c_str()); #else std::cerr << message << std::endl; std::cin.ignore(); #endif */ } void initilize() { Random ::init(); Display ::init(); for (int i = 0; i < 30; i++) { Random::intInRange(0, 63464); //This is so that the RNG is more random } } void loadConfig() { const std::string fileName = "HopsonCraft.conf"; std::ifstream inFile (fileName); if(inFile.is_open()) { Singleton<Config>::get().loadFromStream(fileName, inFile); } } void runGame() { initilize(); loadConfig(); Application app; app.runMainGameLoop(); } } /* ~ ~ The main function is here guise :^) ~ */ int main() try { runGame(); return 0; } catch(std::exception& e) { errorMessage(std::string(e.what())); } <commit_msg>Improve the message box functions in main<commit_after>#include <iostream> #include <fstream> #include <ctime> #include "Util/Random.h" #include "Util/Config.h" #include "Util/Singleton.h" #include "World/Generators/Noise.h" #include "Application.h" #include "Display.h" #include "Util/Native.h" #ifdef __WIN32 extern "C" { //Enable dedicated graphics __declspec(dllexport) bool NvOptimusEnablement = true; __declspec(dllexport) bool AmdPowerXpressRequestHighPerformance = true; } #endif // __WIN32 namespace { void noiseTest(int trials) { Random::init(); Noise::Generator m_noiseGen; m_noiseGen.setSeed(Random::intInRange(0, 999999)); m_noiseGen.setNoiseFunction({5, 500, 0.4, 5000}); float total = 0; std::vector<double> test; for (int i = 0 ; i < trials ; i++) { float h = m_noiseGen.getValue(i, i, i, i); test.push_back(h); total += h; } std::cout << "MIN: " << *std::min_element(test.begin(), test.end()) << "\n"; std::cout << "MAX: " << *std::max_element(test.begin(), test.end()) << "\n"; std::cout << "AVG: " << total / trials << std::endl; } void errorMessage(const std::string& message) { #ifdef __WIN32 MessageBox(nullptr, message.c_str(), "Error", MB_OK); std::cerr << message << std::endl; #elif __linux__ || __APPLE__ const std::string command = "zenity --error --text \"" + message + "\""; system(command.c_str()); #else std::cerr << message << std::endl; std::cin.ignore(); #endif } void initilize() { Random ::init(); Display ::init(); for (int i = 0; i < 30; i++) { Random::intInRange(0, 6346554); //This is so that the RNG is more random } } void loadConfig() { const std::string fileName = "HopsonCraft.conf"; std::ifstream inFile (fileName); if(inFile.is_open()) { Singleton<Config>::get().loadFromStream(fileName, inFile); } } void runGame() { initilize(); loadConfig(); Application app; app.runMainGameLoop(); } } /* ~ ~ The main function is here guise :^) ~ */ int main() try { runGame(); return 0; } catch(std::exception& e) { errorMessage(std::string(e.what())); } <|endoftext|>
<commit_before>/* * File: DrawShip.cpp * Author: maxence * * Created on 29 novembre 2014, 10:43 */ #include <iostream> #include "shared/ship/Ship.h" #include "client/view/VectorView.h" #include "client/view/ShipView.h" #include "shared/Utils.h" sf::Texture ShipView::g_texture; ShipView::ShipView(const Ship &ship, const sf::Color & color) : m_ship(ship) , m_sailShape({0.5f, 0.05f}) { m_speedView = new VectorView(m_ship.kinematics().position(), m_ship.kinematics().speed(), "Vship", sf::Color::Cyan); m_accView = new VectorView(m_ship.kinematics().position(), m_ship.kinematics().acceleration(), "", sf::Color::White); g_texture.loadFromFile("share/tbs/textures/boat.png"); m_boatSprite.setTexture(g_texture); m_boatSprite.setScale(1.5f / m_boatSprite.getTexture()->getSize().x, 0.5f / m_boatSprite.getTexture()->getSize().y); m_boatSprite.setOrigin(m_boatSprite.getTexture()->getSize().x/2.0f, m_boatSprite.getTexture()->getSize().y/2.0f); // Sail m_sailShape.setOrigin(0.0f, 0.05f); m_sailShape.setFillColor(sf::Color::White); } ShipView::ShipView(const ShipView& other) : m_ship(other.m_ship) , m_speedView(other.m_speedView) , m_accView(other.m_accView) , m_sailShape(other.m_sailShape) { m_speedView = new VectorView(m_ship.kinematics().position(), m_ship.kinematics().speed(), "Vship", sf::Color::Cyan); m_accView = new VectorView(m_ship.kinematics().position(), m_ship.kinematics().acceleration(), "", sf::Color::White); } ShipView::~ShipView() { delete m_speedView; delete m_accView; } void ShipView::draw(sf::RenderTarget& target, sf::RenderStates states) const { sf::RenderStates renderShipShape(states); renderShipShape.transform.translate(m_ship.kinematics().position()); renderShipShape.transform.rotate(m_ship.getAngle()); // Draw ship target.draw(m_boatSprite, renderShipShape); // Draw sail sf::RenderStates renderSailShape(states); renderSailShape.transform.translate(m_ship.kinematics().position()); renderSailShape.transform.rotate(m_ship.getSail().getAngle()); target.draw(m_sailShape, renderSailShape); // Draw speed vector target.draw(*m_speedView, states); // Draw acceleration vector target.draw(*m_accView, states); } const Ship& ShipView::getShip() const { return m_ship; } <commit_msg>fix display other players<commit_after>/* * File: DrawShip.cpp * Author: maxence * * Created on 29 novembre 2014, 10:43 */ #include <iostream> #include "shared/ship/Ship.h" #include "client/view/VectorView.h" #include "client/view/ShipView.h" #include "shared/Utils.h" sf::Texture ShipView::g_texture; ShipView::ShipView(const Ship &ship, const sf::Color & color) : m_ship(ship) , m_sailShape({0.5f, 0.05f}) { m_speedView = new VectorView(m_ship.kinematics().position(), m_ship.kinematics().speed(), "Vship", sf::Color::Cyan); m_accView = new VectorView(m_ship.kinematics().position(), m_ship.kinematics().acceleration(), "", sf::Color::White); g_texture.loadFromFile("share/tbs/textures/boat.png"); m_boatSprite.setTexture(g_texture); m_boatSprite.setScale(1.5f / m_boatSprite.getTexture()->getSize().x, 0.5f / m_boatSprite.getTexture()->getSize().y); m_boatSprite.setOrigin(m_boatSprite.getTexture()->getSize().x/2.0f, m_boatSprite.getTexture()->getSize().y/2.0f); // Sail m_sailShape.setOrigin(0.0f, 0.05f); m_sailShape.setFillColor(sf::Color::White); } ShipView::ShipView(const ShipView& other) : ShipView(other.m_ship, sf::Color::Red){ } ShipView::~ShipView() { delete m_speedView; delete m_accView; } void ShipView::draw(sf::RenderTarget& target, sf::RenderStates states) const { sf::RenderStates renderShipShape(states); renderShipShape.transform.translate(m_ship.kinematics().position()); renderShipShape.transform.rotate(m_ship.getAngle()); // Draw ship target.draw(m_boatSprite, renderShipShape); // Draw sail sf::RenderStates renderSailShape(states); renderSailShape.transform.translate(m_ship.kinematics().position()); renderSailShape.transform.rotate(m_ship.getSail().getAngle()); target.draw(m_sailShape, renderSailShape); // Draw speed vector target.draw(*m_speedView, states); // Draw acceleration vector target.draw(*m_accView, states); } const Ship& ShipView::getShip() const { return m_ship; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: textToPronounce_zh.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: kz $ $Date: 2006-01-31 18:49:00 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // prevent internal compiler error with MSVC6SP3 #include <utility> #include <rtl/string.hxx> #include <rtl/ustrbuf.hxx> #define TRANSLITERATION_ALL #include <textToPronounce_zh.hxx> using namespace com::sun::star::uno; using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { sal_Int16 SAL_CALL TextToPronounce_zh::getType() throw (RuntimeException) { return TransliterationType::ONE_TO_ONE| TransliterationType::IGNORE; } const sal_Unicode* SAL_CALL TextToPronounce_zh::getPronounce(const sal_Unicode ch) { static const sal_Unicode emptyString[]={0}; if (idx) { sal_uInt16 address = idx[0][ch>>8]; if (address != 0xFFFF) return &idx[2][idx[1][address + (ch & 0xFF)]]; } return emptyString; } OUString SAL_CALL TextToPronounce_zh::folding(const OUString & inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 > & offset) throw (RuntimeException) { OUStringBuffer sb; const sal_Unicode * chArr = inStr.getStr() + startPos; sal_Int32 j; if (startPos < 0) throw RuntimeException(); if (startPos + nCount > inStr.getLength()) nCount = inStr.getLength() - startPos; offset[0] = 0; for (sal_Int32 i = 0; i < nCount; i++) { OUString pron(getPronounce(chArr[i])); sb.append(pron); if (useOffset) offset[i + 1] = offset[i] + pron.getLength(); } return sb.makeStringAndClear(); } OUString SAL_CALL TextToPronounce_zh::transliterateChar2String( sal_Unicode inChar) throw(RuntimeException) { return OUString(getPronounce(inChar)); } sal_Unicode SAL_CALL TextToPronounce_zh::transliterateChar2Char( sal_Unicode inChar) throw(RuntimeException, MultipleCharsOutputException) { const sal_Unicode* pron=getPronounce(inChar); if (!pron || !pron[0]) return 0; if (pron[1]) throw MultipleCharsOutputException(); return *pron; } sal_Bool SAL_CALL TextToPronounce_zh::equals( const OUString & str1, sal_Int32 pos1, sal_Int32 nCount1, sal_Int32 & nMatch1, const OUString & str2, sal_Int32 pos2, sal_Int32 nCount2, sal_Int32 & nMatch2) throw (RuntimeException) { sal_Int32 realCount; int i; // loop variable const sal_Unicode * s1, * s2; const sal_Unicode *pron1, *pron2; if (nCount1 + pos1 > str1.getLength()) nCount1 = str1.getLength() - pos1; if (nCount2 + pos2 > str2.getLength()) nCount2 = str2.getLength() - pos2; realCount = ((nCount1 > nCount2) ? nCount2 : nCount1); s1 = str1.getStr() + pos1; s2 = str2.getStr() + pos2; for (i = 0; i < realCount; i++) { pron1=getPronounce(*s1++); pron2=getPronounce(*s2++); if (pron1 != pron2) { nMatch1 = nMatch2 = i; return sal_False; } } nMatch1 = nMatch2 = realCount; return (nCount1 == nCount2); } TextToPinyin_zh_CN::TextToPinyin_zh_CN() : TextToPronounce_zh("get_zh_pinyin") { transliterationName = "ChineseCharacterToPinyin"; implementationName = "com.sun.star.i18n.Transliteration.TextToPinyin_zh_CN"; } TextToChuyin_zh_TW::TextToChuyin_zh_TW() : TextToPronounce_zh("get_zh_zhuyin") { transliterationName = "ChineseCharacterToChuyin"; implementationName = "com.sun.star.i18n.Transliteration.TextToChuyin_zh_TW"; } TextToPronounce_zh::TextToPronounce_zh(const sal_Char* func_name) { #ifdef SAL_DLLPREFIX OUString lib=OUString::createFromAscii(SAL_DLLPREFIX"index_data"SAL_DLLEXTENSION); #else OUString lib=OUString::createFromAscii("index_data"SAL_DLLEXTENSION); #endif hModule = osl_loadModule( lib.pData, SAL_LOADMODULE_DEFAULT ); idx=NULL; if (hModule) { sal_uInt16** (*function)() = (sal_uInt16** (*)()) osl_getSymbol(hModule, OUString::createFromAscii(func_name).pData); if (function) idx=function(); } } TextToPronounce_zh::~TextToPronounce_zh() { if (hModule) osl_unloadModule(hModule); } } } } } <commit_msg>INTEGRATION: CWS warnings01 (1.9.14); FILE MERGED 2006/04/20 15:23:16 sb 1.9.14.1: #i53898# Made code compile and/or warning-free again after resync to SRC680m162.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: textToPronounce_zh.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2006-06-20 04:49:52 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // prevent internal compiler error with MSVC6SP3 #include <utility> #include <rtl/string.hxx> #include <rtl/ustrbuf.hxx> #define TRANSLITERATION_ALL #include <textToPronounce_zh.hxx> using namespace com::sun::star::uno; using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { sal_Int16 SAL_CALL TextToPronounce_zh::getType() throw (RuntimeException) { return TransliterationType::ONE_TO_ONE| TransliterationType::IGNORE; } const sal_Unicode* SAL_CALL TextToPronounce_zh::getPronounce(const sal_Unicode ch) { static const sal_Unicode emptyString[]={0}; if (idx) { sal_uInt16 address = idx[0][ch>>8]; if (address != 0xFFFF) return &idx[2][idx[1][address + (ch & 0xFF)]]; } return emptyString; } OUString SAL_CALL TextToPronounce_zh::folding(const OUString & inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 > & offset) throw (RuntimeException) { OUStringBuffer sb; const sal_Unicode * chArr = inStr.getStr() + startPos; if (startPos < 0) throw RuntimeException(); if (startPos + nCount > inStr.getLength()) nCount = inStr.getLength() - startPos; offset[0] = 0; for (sal_Int32 i = 0; i < nCount; i++) { OUString pron(getPronounce(chArr[i])); sb.append(pron); if (useOffset) offset[i + 1] = offset[i] + pron.getLength(); } return sb.makeStringAndClear(); } OUString SAL_CALL TextToPronounce_zh::transliterateChar2String( sal_Unicode inChar) throw(RuntimeException) { return OUString(getPronounce(inChar)); } sal_Unicode SAL_CALL TextToPronounce_zh::transliterateChar2Char( sal_Unicode inChar) throw(RuntimeException, MultipleCharsOutputException) { const sal_Unicode* pron=getPronounce(inChar); if (!pron || !pron[0]) return 0; if (pron[1]) throw MultipleCharsOutputException(); return *pron; } sal_Bool SAL_CALL TextToPronounce_zh::equals( const OUString & str1, sal_Int32 pos1, sal_Int32 nCount1, sal_Int32 & nMatch1, const OUString & str2, sal_Int32 pos2, sal_Int32 nCount2, sal_Int32 & nMatch2) throw (RuntimeException) { sal_Int32 realCount; int i; // loop variable const sal_Unicode * s1, * s2; const sal_Unicode *pron1, *pron2; if (nCount1 + pos1 > str1.getLength()) nCount1 = str1.getLength() - pos1; if (nCount2 + pos2 > str2.getLength()) nCount2 = str2.getLength() - pos2; realCount = ((nCount1 > nCount2) ? nCount2 : nCount1); s1 = str1.getStr() + pos1; s2 = str2.getStr() + pos2; for (i = 0; i < realCount; i++) { pron1=getPronounce(*s1++); pron2=getPronounce(*s2++); if (pron1 != pron2) { nMatch1 = nMatch2 = i; return sal_False; } } nMatch1 = nMatch2 = realCount; return (nCount1 == nCount2); } TextToPinyin_zh_CN::TextToPinyin_zh_CN() : TextToPronounce_zh("get_zh_pinyin") { transliterationName = "ChineseCharacterToPinyin"; implementationName = "com.sun.star.i18n.Transliteration.TextToPinyin_zh_CN"; } TextToChuyin_zh_TW::TextToChuyin_zh_TW() : TextToPronounce_zh("get_zh_zhuyin") { transliterationName = "ChineseCharacterToChuyin"; implementationName = "com.sun.star.i18n.Transliteration.TextToChuyin_zh_TW"; } TextToPronounce_zh::TextToPronounce_zh(const sal_Char* func_name) { #ifdef SAL_DLLPREFIX OUString lib=OUString::createFromAscii(SAL_DLLPREFIX"index_data"SAL_DLLEXTENSION); #else OUString lib=OUString::createFromAscii("index_data"SAL_DLLEXTENSION); #endif hModule = osl_loadModule( lib.pData, SAL_LOADMODULE_DEFAULT ); idx=NULL; if (hModule) { sal_uInt16** (*function)() = (sal_uInt16** (*)()) osl_getFunctionSymbol(hModule, OUString::createFromAscii(func_name).pData); if (function) idx=function(); } } TextToPronounce_zh::~TextToPronounce_zh() { if (hModule) osl_unloadModule(hModule); } } } } } <|endoftext|>
<commit_before>#include "include/imgui/imgui.h" #include "include/imgui/imgui-SFML.h" #include <SFML/Graphics.hpp> #include <cmath> #include <ctime> //****** //temporary workaround namespace sf{ class KeyboardHacked: public sf::Keyboard{ public: static bool isKeyPressed (Key key){ if(ImGui::GetIO().WantCaptureKeyboard){ return false; } return sf::Keyboard::isKeyPressed(key); } }; } #define Keyboard KeyboardHacked //***** #include "include/SceneManager.hpp" #include "levels/trex.hpp" #include "levels/clicker.hpp" #include "levels/jumper.hpp" #include "levels/synth3d.hpp" #include "levels/mario.hpp" #include "levels/levelselect.hpp" #include "levels/shooter2D.hpp" #include "levels/rpg.hpp" #include "levels/isayparty.hpp" #include <cstdlib> #include <iostream> int main(){ srand(time(NULL)); sf::ContextSettings settings; settings.antialiasingLevel = 8; sf::RenderWindow window(sf::VideoMode(1280, 720), "Tadzik", sf::Style::Default, settings); window.setFramerateLimit(60); window.setKeyRepeatEnabled(false); ImGui::SFML::Init(window); SceneManager sceneManager(&window); //sceneManager.registerScene<TREX>("TREX", &window); //sceneManager.registerScene<CLICKER>("CLICKER", &window); //sceneManager.registerScene<JUMPER>("JUMPER", &window); sceneManager.registerScene<SYNTH3D>("SYNTH3D", &window); //sceneManager.registerScene<MARIO>("MARIO", &window); //sceneManager.registerScene<LEVELSELECT>("LEVELSELECT", &window); //sceneManager.registerScene<RPG>("RPG", &window); //sceneManager.registerScene<SHOOTER2D>("SHOOTER2D", &window); //sceneManager.registerScene<ISAYPARTY>("ISAYPARTY", &window); //sceneManager.setActiveScene("JUMPER"); //sceneManager.setActiveScene("CLICKER"); sceneManager.setActiveScene("SYNTH3D"); //sceneManager.setActiveScene("MARIO"); //sceneManager.setActiveScene("LEVELSELECT"); //sceneManager.setActiveScene("SHOOTER2D"); //sceneManager.setActiveScene("RPG"); sf::Clock deltaClock; while(window.isOpen()){ sf::Event event; while(window.pollEvent(event)){ ImGui::SFML::ProcessEvent(event); if(event.type == sf::Event::Closed ) window.close(); if(event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) { window.close(); } if(event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Tilde) { sceneManager.toogleCMD(); } else{ sceneManager.deliverEvent(event); } } ImGui::SFML::Update(window, deltaClock.getElapsedTime()); sceneManager.runSceneFrame(deltaClock.getElapsedTime().asMilliseconds()); deltaClock.restart(); window.resetGLStates(); ImGui::Render(); window.display(); std::cout << "fps: " << sceneManager.getFPS() << "\n"; } ImGui::SFML::Shutdown(); return 0; } <commit_msg>Postafke napraw<commit_after>#include "include/imgui/imgui.h" #include "include/imgui/imgui-SFML.h" #include <SFML/Graphics.hpp> #include <cmath> #include <ctime> #include <cstdlib> #include <iostream> //****** //temporary workaround namespace sf{ class KeyboardHacked: public sf::Keyboard{ public: static bool isKeyPressed (Key key){ if(ImGui::GetIO().WantCaptureKeyboard){ return false; } return sf::Keyboard::isKeyPressed(key); } }; } #define Keyboard KeyboardHacked //***** #include "include/SceneManager.hpp" #include "levels/trex.hpp" #include "levels/clicker.hpp" #include "levels/jumper.hpp" #include "levels/synth3d.hpp" #include "levels/mario.hpp" #include "levels/levelselect.hpp" #include "levels/shooter2D.hpp" #include "levels/rpg.hpp" #include "levels/isayparty.hpp" int main(){ srand(time(NULL)); sf::ContextSettings settings; settings.antialiasingLevel = 8; sf::RenderWindow window(sf::VideoMode(1280, 720), "Tadzik", sf::Style::Default, settings); sf::Image screenshot; screenshot.create(1280, 720); window.setFramerateLimit(60); window.setKeyRepeatEnabled(false); ImGui::SFML::Init(window); SceneManager sceneManager(&window); //sceneManager.registerScene<TREX>("TREX", &window); //sceneManager.registerScene<CLICKER>("CLICKER", &window); //sceneManager.registerScene<JUMPER>("JUMPER", &window); //sceneManager.registerScene<SYNTH3D>("SYNTH3D", &window); //sceneManager.registerScene<MARIO>("MARIO", &window); //sceneManager.registerScene<LEVELSELECT>("LEVELSELECT", &window); //sceneManager.registerScene<RPG>("RPG", &window); sceneManager.registerScene<SHOOTER2D>("SHOOTER2D", &window); //sceneManager.registerScene<ISAYPARTY>("ISAYPARTY", &window); //sceneManager.setActiveScene("TREX"); //sceneManager.setActiveScene("JUMPER"); //sceneManager.setActiveScene("CLICKER"); sceneManager.setActiveScene("SYNTH3D"); //sceneManager.setActiveScene("MARIO"); //sceneManager.setActiveScene("LEVELSELECT"); sceneManager.setActiveScene("SHOOTER2D"); //sceneManager.setActiveScene("RPG"); //sceneManager.setActiveScene("ISAYPARTY"); sf::Clock deltaClock; while(window.isOpen()){ sf::Event event; while(window.pollEvent(event)){ ImGui::SFML::ProcessEvent(event); if(event.type == sf::Event::Closed ) window.close(); if(event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) { window.close(); } if(event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::F12) { screenshot = window.capture(); screenshot.saveToFile("screenshots/"+Utils::getDate()+".png"); } if(event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Tilde) { sceneManager.toogleCMD(); } else{ sceneManager.deliverEvent(event); } } ImGui::SFML::Update(window, deltaClock.getElapsedTime()); sceneManager.runSceneFrame(deltaClock.getElapsedTime().asMilliseconds()); deltaClock.restart(); window.resetGLStates(); ImGui::Render(); window.display(); std::cout << "fps: " << sceneManager.getFPS() << "\n"; } ImGui::SFML::Shutdown(); return 0; } <|endoftext|>
<commit_before>#include "queryview.h" QueryView::QueryView(QWidget *parent, QSqlQueryModel* model, QString const name, int const time, int const rows, int const cols, Qt::WidgetAttribute f) { tview = new QTableView(this); tview->resizeColumnsToContents(); setCentralWidget(tview); show(); QString timeel = QApplication::translate("QueryView", "Time elapsed:", 0, QApplication::UnicodeUTF8); QString rowsStr = QApplication::translate("QueryView", "Rows:", 0, QApplication::UnicodeUTF8); QString colsStr = QApplication::translate("QueryView", "Columns:", 0, QApplication::UnicodeUTF8); statusBar()->showMessage(timeel + QString::number((double)time/1000) + " s \t " + rowsStr + QString::number(rows) + " \t " + colsStr + QString::number(cols)); tview->setModel(model); setWindowTitle(name); tview->setStyleSheet("QTableView {font-weight: 400;}"); tview->setAlternatingRowColors(true); setGeometry(100,100,640,480); QShortcut* shortcut_ctrl_c = new QShortcut(QKeySequence::Copy, this); connect(shortcut_ctrl_c, SIGNAL(activated()), this, SLOT(copyc())); QShortcut* shortcut_ctrl_shft_c = new QShortcut(QKeySequence("Ctrl+Shift+C"), this); connect(shortcut_ctrl_shft_c, SIGNAL(activated()), this, SLOT(copych())); } QueryView::~QueryView() { delete tview->model(); delete tview; close(); } void QueryView::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) { QMenu menu; QPalette palette; palette.setColor(menu.backgroundRole(), QColor(205,205,205)); menu.setPalette(palette); menu.addAction("Remove"); QAction *a = menu.exec(event->screenPos()); if(a && QString::compare(a->text(),"Remove")==0) { } if(a && QString::compare(a->text(),"Expand")==0) { } if(a && QString::compare(a->text(),"Collapse")==0) { } } void QueryView::closeEvent(QCloseEvent *event) { event->accept(); delete tview->model(); delete tview; close(); } void QueryView::copyc() { QItemSelectionModel* s = tview->selectionModel(); QModelIndexList indices = s->selectedIndexes(); if(indices.isEmpty()) { return; } qSort(indices); QModelIndex prev = indices.first(); QModelIndex last = indices.last(); indices.removeFirst(); QModelIndex current; QString selectedText; foreach(current, indices) { QVariant data = tview->model()->data(prev); selectedText.append(data.toString()); if(current.row() != prev.row()) selectedText.append(QLatin1Char('\n')); else selectedText.append(QLatin1Char('\t')); prev = current; } selectedText.append(tview->model()->data(last).toString()); selectedText.append(QLatin1Char('\n')); qApp->clipboard()->setText(selectedText); } void QueryView::copych() { QAbstractItemModel* atm = tview->model(); QItemSelectionModel* s = tview->selectionModel(); QModelIndexList indices = s->selectedIndexes(); if(indices.isEmpty()) return; qSort(indices); QString headerText; QModelIndex current; foreach(current, indices) if(current.row() == 0) { QVariant data = atm->headerData(current.column(), Qt::Horizontal); headerText.append(data.toString()); headerText.append(QLatin1Char('\t')); } else { headerText.append(QLatin1Char('\n')); break; } QString selectedText; QModelIndex prev = indices.first(); QModelIndex last = indices.last(); indices.removeFirst(); foreach(current, indices) { QVariant data = atm->data(prev); selectedText.append(data.toString()); if(current.row() != prev.row()) selectedText.append(QLatin1Char('\n')); else selectedText.append(QLatin1Char('\t')); prev = current; } selectedText.append(atm->data(last).toString()); selectedText.append(QLatin1Char('\n')); qApp->clipboard()->setText(headerText + selectedText); } <commit_msg>Edited queryview.cpp via GitHub<commit_after>#include "queryview.h" QueryView::QueryView(QWidget *parent, QSqlQueryModel* model, QString const name, int const time, int const rows, int const cols, Qt::WidgetAttribute f) { tview = new QTableView(this); tview->resizeColumnsToContents(); setCentralWidget(tview); show(); QString timeel = QApplication::translate("QueryView", "Time elapsed:", 0, QApplication::UnicodeUTF8); QString rowsStr = QApplication::translate("QueryView", "Rows:", 0, QApplication::UnicodeUTF8); QString colsStr = QApplication::translate("QueryView", "Columns:", 0, QApplication::UnicodeUTF8); statusBar()->showMessage(timeel + QString::number((double)time/1000) + " s \t " + rowsStr + QString::number(rows) + " \t " + colsStr + QString::number(cols)); tview->setModel(model); setWindowTitle(name); tview->setStyleSheet("QTableView {font-weight: 400;}"); tview->setAlternatingRowColors(true); setGeometry(100,100,640,480); QShortcut* shortcut_ctrl_c = new QShortcut(QKeySequence::Copy, this); connect(shortcut_ctrl_c, SIGNAL(activated()), this, SLOT(copyc())); QShortcut* shortcut_ctrl_shft_c = new QShortcut(QKeySequence("Ctrl+Shift+C"), this); connect(shortcut_ctrl_shft_c, SIGNAL(activated()), this, SLOT(copych())); } QueryView::~QueryView() { delete tview->model(); delete tview; close(); } void QueryView::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) { QMenu menu; QPalette palette; palette.setColor(menu.backgroundRole(), QColor(205,205,205)); menu.setPalette(palette); menu.addAction("Remove"); QAction *a = menu.exec(event->screenPos()); if(a && QString::compare(a->text(),"Remove")==0) { } if(a && QString::compare(a->text(),"Expand")==0) { } if(a && QString::compare(a->text(),"Collapse")==0) { } } void QueryView::closeEvent(QCloseEvent *event) { event->accept(); delete tview->model(); delete tview; close(); } void QueryView::copyc() { QItemSelectionModel* s = tview->selectionModel(); QModelIndexList indices = s->selectedIndexes(); if(indices.isEmpty()) { return; } qSort(indices); QModelIndex prev = indices.first(); QModelIndex last = indices.last(); indices.removeFirst(); QModelIndex current; QString selectedText; foreach(current, indices) { QVariant data = tview->model()->data(prev); selectedText.append(data.toString()); if(current.row() != prev.row()) selectedText.append(QLatin1Char('\n')); else selectedText.append(QLatin1Char('\t')); prev = current; } selectedText.append(tview->model()->data(last).toString()); selectedText.append(QLatin1Char('\n')); qApp->clipboard()->setText(selectedText); } void QueryView::copych() { QAbstractItemModel* atm = tview->model(); QItemSelectionModel* s = tview->selectionModel(); QModelIndexList indices = s->selectedIndexes(); if(indices.isEmpty()) return; qSort(indices); QString headerText; QModelIndex current; int prevRow = indices.at(0).row(); foreach(current, indices) { if(current.row() == prevRow) { QVariant data = atm->headerData(current.column(), Qt::Horizontal); headerText.append(data.toString()); headerText.append(QLatin1Char('\t')); } else { headerText.append(QLatin1Char('\n')); break; } prevRow = current.row(); } if(!headerText.endsWith("\n")) headerText.append(QLatin1Char('\n')); QString selectedText; QModelIndex prev = indices.first(); QModelIndex last = indices.last(); indices.removeFirst(); foreach(current, indices) { QVariant data = atm->data(prev); selectedText.append(data.toString()); if(current.row() != prev.row()) selectedText.append(QLatin1Char('\n')); else selectedText.append(QLatin1Char('\t')); prev = current; } selectedText.append(atm->data(last).toString()); selectedText.append(QLatin1Char('\n')); qApp->clipboard()->setText(headerText + selectedText); }<|endoftext|>
<commit_before>/// Device memory manager /// /// (c) Koheron #ifndef __DRIVERS_CORE_DEV_MEM_HPP__ #define __DRIVERS_CORE_DEV_MEM_HPP__ #include <map> #include <vector> #include <array> #include <cstdint> #include <string> #include <assert.h> extern "C" { #include <fcntl.h> } #include "memory_map.hpp" /// @namespace Klib /// @brief Namespace of the Koheron library namespace Klib { struct MemoryRegion { intptr_t phys_addr; uint32_t range; }; /// ID of a memory map typedef uint32_t MemMapID; class MemMapIdPool { public: MemMapIdPool() : reusable_ids(0) {}; MemMapID get_id(unsigned int num_maps); void release_id(MemMapID id); private: std::vector<MemMapID> reusable_ids; }; /// Device memory manager /// A memory maps factory class DevMem { public: DevMem(intptr_t addr_limit_down_=0x0, intptr_t addr_limit_up_=0x0); ~DevMem(); /// Open the /dev/mem driver int Open(); /// Close all the memory maps /// @return 0 if succeed, -1 else int Close(); /// Current number of memory maps static unsigned int num_maps; template<size_t N> std::array<MemMapID, N> RequestMemoryMaps(std::array<MemoryRegion, N> regions); /// Create a new memory map /// @addr Base address of the map /// @size Size of the map /// @return An ID to the created map, /// or -1 if an error occured MemMapID AddMemoryMap(intptr_t addr, uint32_t size); /// Remove a memory map /// @id ID of the memory map to be removed void RmMemoryMap(MemMapID id); /// Remove all the memory maps void RemoveAll(); /// Get a memory map /// @id ID of the memory map MemoryMap& GetMemMap(MemMapID id); /// Return the base address of a map /// @id ID of the map uint32_t GetBaseAddr(MemMapID id); /// Return the status of a map /// @id ID of the map int GetStatus(MemMapID id); /// Return 1 if a memory map failed int IsFailed(); /// True if the /dev/mem device is open inline bool IsOpen() const {return is_open;} private: int fd; ///< /dev/mem file ID bool is_open; ///< True if /dev/mem open /// Limit addresses intptr_t addr_limit_down; intptr_t addr_limit_up; bool __is_forbidden_address(intptr_t addr); std::map<MemMapID, MemoryMap*> mem_maps; MemMapIdPool id_pool; }; template<size_t N> std::array<MemMapID, N> DevMem::RequestMemoryMaps(std::array<MemoryRegion, N> regions) { auto map_ids = std::array<MemMapID, N>(); map_ids.fill(static_cast<MemMapID>(-1)); uint32_t i = 0; for (auto& region : regions) { for (auto& mem_map : mem_maps) { // TODO Reallocate also if new range is larger if (region.phys_addr == mem_map.second->PhysAddr()) { map_ids[i] = mem_map.first; break; } } if (map_ids[i] < 0) // The required region is not mapped map_ids[i] = AddMemoryMap(region.phys_addr, region.range); i++; } return map_ids; } }; // namespace Klib #endif // __DRIVERS_CORE_DEV_MEM_HPP__ <commit_msg>Add CheckMapIDs<commit_after>/// Device memory manager /// /// (c) Koheron #ifndef __DRIVERS_CORE_DEV_MEM_HPP__ #define __DRIVERS_CORE_DEV_MEM_HPP__ #include <map> #include <vector> #include <array> #include <cstdint> #include <string> #include <assert.h> extern "C" { #include <fcntl.h> } #include "memory_map.hpp" /// @namespace Klib /// @brief Namespace of the Koheron library namespace Klib { struct MemoryRegion { intptr_t phys_addr; uint32_t range; }; /// ID of a memory map typedef uint32_t MemMapID; class MemMapIdPool { public: MemMapIdPool() : reusable_ids(0) {}; MemMapID get_id(unsigned int num_maps); void release_id(MemMapID id); private: std::vector<MemMapID> reusable_ids; }; /// Device memory manager /// A memory maps factory class DevMem { public: DevMem(intptr_t addr_limit_down_=0x0, intptr_t addr_limit_up_=0x0); ~DevMem(); /// Open the /dev/mem driver int Open(); /// Close all the memory maps /// @return 0 if succeed, -1 else int Close(); /// Current number of memory maps static unsigned int num_maps; template<size_t N> std::array<MemMapID, N> RequestMemoryMaps(std::array<MemoryRegion, N> regions); // Helper function to check the IDs returned by RequestMemoryMaps template<size_t N> int CheckMapIDs(std::array<MemMapID, N> ids); /// Create a new memory map /// @addr Base address of the map /// @size Size of the map /// @return An ID to the created map, /// or -1 if an error occured MemMapID AddMemoryMap(intptr_t addr, uint32_t size); /// Remove a memory map /// @id ID of the memory map to be removed void RmMemoryMap(MemMapID id); /// Remove all the memory maps void RemoveAll(); /// Get a memory map /// @id ID of the memory map MemoryMap& GetMemMap(MemMapID id); /// Return the base address of a map /// @id ID of the map uint32_t GetBaseAddr(MemMapID id); /// Return the status of a map /// @id ID of the map int GetStatus(MemMapID id); /// Return 1 if a memory map failed int IsFailed(); /// True if the /dev/mem device is open inline bool IsOpen() const {return is_open;} private: int fd; ///< /dev/mem file ID bool is_open; ///< True if /dev/mem open /// Limit addresses intptr_t addr_limit_down; intptr_t addr_limit_up; bool __is_forbidden_address(intptr_t addr); std::map<MemMapID, MemoryMap*> mem_maps; MemMapIdPool id_pool; }; template<size_t N> std::array<MemMapID, N> DevMem::RequestMemoryMaps(std::array<MemoryRegion, N> regions) { auto map_ids = std::array<MemMapID, N>(); map_ids.fill(static_cast<MemMapID>(-1)); uint32_t i = 0; for (auto& region : regions) { for (auto& mem_map : mem_maps) { // TODO Reallocate also if new range is larger if (region.phys_addr == mem_map.second->PhysAddr()) { map_ids[i] = mem_map.first; break; } } if (map_ids[i] < 0) // The required region is not mapped map_ids[i] = AddMemoryMap(region.phys_addr, region.range); i++; } return map_ids; } template<size_t N> int DevMem::CheckMapIDs(std::array<MemMapID, N> ids) { for (auto& id : ids) if (id < 0) return -1; return 0; } }; // namespace Klib #endif // __DRIVERS_CORE_DEV_MEM_HPP__ <|endoftext|>
<commit_before>/* * Copyright (c) 2001 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #if !defined(WINNT) #ident "$Id: resolv.cc,v 1.4 2001/05/31 04:12:43 steve Exp $" #endif # include "resolv.h" # include "schedule.h" /* * A signal value is unambiguous if the top 4 bits and the bottom 4 * bits are identical. This means that the VSSSvsss bits of the 8bit * value have V==v and SSS==sss. */ # define UNAMBIG(v) (((v) & 0x0f) == (((v) >> 4) & 0x0f)) # define STREN1(v) ( ((v)&0x80)? ((v)&0xf0) : (0x70 - ((v)&0xf0)) ) # define STREN0(v) ( ((v)&0x08)? ((v)&0x0f) : (0x07 - ((v)&0x0f)) ) static unsigned blend(unsigned a, unsigned b) { if (a == HiZ) return b; if (b == HiZ) return a; unsigned res = a; if (UNAMBIG(a) && UNAMBIG(b)) { /* If both signals are unambiguous, simply choose the stronger. If they have the same strength but different values, then this becomes ambiguous. */ if (a == b) { /* values are equal. do nothing. */ } else if ((b&0x07) > (res&0x07)) { /* New value is stronger. Take it. */ res = b; } else if ((b&0x77) == (res&0x77)) { /* Strengths are the same. Make value ambiguous. */ res = (res&0x70) | (b&0x07) | 0x80; } else { /* Must be res is the stronger one. */ } } else if (UNAMBIG(res) || UNAMBIG(b)) { /* If one of the signals is unambiguous, then it will sweep up the weaker parts of the ambiguous signal. The result may be ambiguous, or maybe not. */ unsigned tmp = 0; if ((res&0x70) > (b&0x70)) tmp |= res&0xf0; else tmp |= b&0xf0; if ((res&0x07) > (b&0x07)) tmp |= res&0x0f; else tmp |= b&0x0f; res = tmp; } else { /* If both signals are ambiguous, then the result has an even wider ambiguity. */ unsigned tmp = 0; if (STREN1(b) > STREN1(res)) tmp |= b&0xf0; else tmp |= res&0xf0; if (STREN0(b) < STREN0(res)) tmp |= b&0x0f; else tmp |= res&0x0f; res = tmp; } /* Cannonicalize the HiZ value. */ if ((res&0x77) == 0) res = HiZ; return res; } /* * Resolve the strength values of the inputs, two at a time. Pairs of * inputs are resolved with the blend function, and the final value is * reduced to a 4-value result for propagation. */ void vvp_resolv_s::set(vvp_ipoint_t ptr, functor_t fp, bool push) { unsigned val = fp->istr[0]; val = blend(val, fp->istr[1]); val = blend(val, fp->istr[2]); val = blend(val, fp->istr[3]); unsigned oval; if (val == HiZ) { oval = 3; } else switch (val & 0x88) { case 0x00: oval = 0; break; case 0x88: oval = 1; break; default: oval = 2; break; } fp->ostr = val; /* If the output changes, then create a propagation event. */ if (oval != fp->oval) { fp->oval = oval; if (push) functor_propagate(ptr); else schedule_functor(ptr, 0); } } /* * $Log: resolv.cc,v $ * Revision 1.4 2001/05/31 04:12:43 steve * Make the bufif0 and bufif1 gates strength aware, * and accurately propagate strengths of outputs. * * Revision 1.3 2001/05/30 03:02:35 steve * Propagate strength-values instead of drive strengths. * * Revision 1.2 2001/05/12 20:38:06 steve * A resolver that understands some simple strengths. * * Revision 1.1 2001/05/09 02:53:53 steve * Implement the .resolv syntax. * */ <commit_msg> Fix blending of ambiguous pairs.<commit_after>/* * Copyright (c) 2001 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #if !defined(WINNT) #ident "$Id: resolv.cc,v 1.5 2001/07/21 02:34:39 steve Exp $" #endif # include "resolv.h" # include "schedule.h" /* * A signal value is unambiguous if the top 4 bits and the bottom 4 * bits are identical. This means that the VSSSvsss bits of the 8bit * value have V==v and SSS==sss. */ # define UNAMBIG(v) (((v) & 0x0f) == (((v) >> 4) & 0x0f)) # define STREN1(v) ( ((v)&0x80)? ((v)&0xf0) : (0x70 - ((v)&0xf0)) ) # define STREN0(v) ( ((v)&0x08)? ((v)&0x0f) : (0x07 - ((v)&0x0f)) ) static unsigned blend(unsigned a, unsigned b) { if (a == HiZ) return b; if (b == HiZ) return a; unsigned res = a; if (UNAMBIG(a) && UNAMBIG(b)) { /* If both signals are unambiguous, simply choose the stronger. If they have the same strength but different values, then this becomes ambiguous. */ if (a == b) { /* values are equal. do nothing. */ } else if ((b&0x07) > (res&0x07)) { /* New value is stronger. Take it. */ res = b; } else if ((b&0x77) == (res&0x77)) { /* Strengths are the same. Make value ambiguous. */ res = (res&0x70) | (b&0x07) | 0x80; } else { /* Must be res is the stronger one. */ } } else if (UNAMBIG(res)) { unsigned tmp = 0; if ((res&0x70) > (b&0x70)) tmp |= res&0xf0; else tmp |= b&0xf0; if ((res&0x07) > (b&0x07)) tmp |= res&0x0f; else tmp |= b&0x0f; res = tmp; } else if (UNAMBIG(b)) { /* If one of the signals is unambiguous, then it will sweep up the weaker parts of the ambiguous signal. The result may be ambiguous, or maybe not. */ unsigned tmp = 0; if ((b&0x70) > (res&0x70)) tmp |= b&0xf0; else tmp |= res&0xf0; if ((b&0x07) > (res&0x07)) tmp |= b&0x0f; else tmp |= res&0x0f; res = tmp; } else { /* If both signals are ambiguous, then the result has an even wider ambiguity. */ unsigned tmp = 0; if (STREN1(b) > STREN1(res)) tmp |= b&0xf0; else tmp |= res&0xf0; if (STREN0(b) < STREN0(res)) tmp |= b&0x0f; else tmp |= res&0x0f; res = tmp; } /* Cannonicalize the HiZ value. */ if ((res&0x77) == 0) res = HiZ; return res; } /* * Resolve the strength values of the inputs, two at a time. Pairs of * inputs are resolved with the blend function, and the final value is * reduced to a 4-value result for propagation. */ void vvp_resolv_s::set(vvp_ipoint_t ptr, functor_t fp, bool push) { unsigned val = fp->istr[0]; val = blend(val, fp->istr[1]); val = blend(val, fp->istr[2]); val = blend(val, fp->istr[3]); unsigned oval; if (val == HiZ) { oval = 3; } else switch (val & 0x88) { case 0x00: oval = 0; break; case 0x88: oval = 1; break; default: oval = 2; break; } fp->ostr = val; /* If the output changes, then create a propagation event. */ if (oval != fp->oval) { fp->oval = oval; if (push) functor_propagate(ptr); else schedule_functor(ptr, 0); } } /* * $Log: resolv.cc,v $ * Revision 1.5 2001/07/21 02:34:39 steve * Fix blending of ambiguous pairs. * * Revision 1.4 2001/05/31 04:12:43 steve * Make the bufif0 and bufif1 gates strength aware, * and accurately propagate strengths of outputs. * * Revision 1.3 2001/05/30 03:02:35 steve * Propagate strength-values instead of drive strengths. * * Revision 1.2 2001/05/12 20:38:06 steve * A resolver that understands some simple strengths. * * Revision 1.1 2001/05/09 02:53:53 steve * Implement the .resolv syntax. * */ <|endoftext|>
<commit_before>#include <iomanip> #include "hack.hpp" void Radar(remote::Handle* csgo, remote::MapModuleMemoryRegion* client, void* ent) { unsigned char spotted = 1; csgo->Write((void*)((unsigned long) ent + 0x929), &spotted, sizeof(unsigned char)); } void hack::Glow(remote::Handle* csgo, remote::MapModuleMemoryRegion* client) { if(!csgo || !client) return; void* glowClassAddress = (void*) (client->start + 0x054612C0); hack::CGlowObjectManager manager; if(!csgo->Read(glowClassAddress, &manager, sizeof(hack::CGlowObjectManager))) { std::cout << "Failed to read glowClassAddress" << std::endl; return; } hack::GlowObjectDefinition_t* glowArray = new hack::GlowObjectDefinition_t[manager.m_GlowObjectDefinitions.Count]; if(!csgo->Read(manager.m_GlowObjectDefinitions.DataPtr, glowArray, sizeof(hack::GlowObjectDefinition_t) * manager.m_GlowObjectDefinitions.Count)) { std::cout << "Failed to read m_GlowObjectDefinitions" << std::endl; delete[] glowArray; return; } for(unsigned int i = 0; i < manager.m_GlowObjectDefinitions.Count; i++) { if(glowArray[i].m_pEntity == NULL) continue; hack::Entity ent; if(csgo->Read(glowArray[i].m_pEntity, &ent, sizeof(hack::Entity))) { if(ent.m_iTeamNum != 2 && ent.m_iTeamNum != 3) { glowArray[i].m_bRenderWhenOccluded = 0; glowArray[i].m_bRenderWhenUnoccluded = 0; continue; } // Radar Hack Radar(csgo, client, glowArray[i].m_pEntity); glowArray[i].m_bRenderWhenOccluded = 1; glowArray[i].m_bRenderWhenUnoccluded = 0; if(ent.m_iTeamNum == 2) { glowArray[i].m_flGlowRed = 1.0f; glowArray[i].m_flGlowGreen = 0.0f; glowArray[i].m_flGlowBlue = 0.0f; glowArray[i].m_flGlowAlpha = 0.6f; } else if(ent.m_iTeamNum == 3) { glowArray[i].m_flGlowRed = 0.0f; glowArray[i].m_flGlowGreen = 0.0f; glowArray[i].m_flGlowBlue = 1.0f; glowArray[i].m_flGlowAlpha = 0.6f; } } else { std::cout << "Unable to read entity..." << std::endl; } } csgo->Write(manager.m_GlowObjectDefinitions.DataPtr, glowArray, sizeof(hack::GlowObjectDefinition_t) * manager.m_GlowObjectDefinitions.Count); delete[] glowArray; }<commit_msg>Overwriting entity pointers is bad, this fixes an instability issue<commit_after>#include <iomanip> #include "hack.hpp" void Radar(remote::Handle* csgo, remote::MapModuleMemoryRegion* client, void* ent) { unsigned char spotted = 1; csgo->Write((void*)((unsigned long) ent + 0x929), &spotted, sizeof(unsigned char)); } void hack::Glow(remote::Handle* csgo, remote::MapModuleMemoryRegion* client) { if(!csgo || !client) return; void* glowClassAddress = (void*) (client->start + 0x054612C0); hack::CGlowObjectManager manager; if(!csgo->Read(glowClassAddress, &manager, sizeof(hack::CGlowObjectManager))) { std::cout << "Failed to read glowClassAddress" << std::endl; return; } hack::GlowObjectDefinition_t* glowArray = new hack::GlowObjectDefinition_t[manager.m_GlowObjectDefinitions.Count]; if(!csgo->Read(manager.m_GlowObjectDefinitions.DataPtr, glowArray, sizeof(hack::GlowObjectDefinition_t) * manager.m_GlowObjectDefinitions.Count)) { std::cout << "Failed to read m_GlowObjectDefinitions" << std::endl; delete[] glowArray; return; } for(unsigned int i = 0; i < manager.m_GlowObjectDefinitions.Count; i++) { if(glowArray[i].m_pEntity == NULL) continue; hack::Entity ent; if(csgo->Read(glowArray[i].m_pEntity, &ent, sizeof(hack::Entity))) { if(ent.m_iTeamNum != 2 && ent.m_iTeamNum != 3) { glowArray[i].m_bRenderWhenOccluded = 0; glowArray[i].m_bRenderWhenUnoccluded = 0; continue; } // Radar Hack Radar(csgo, client, glowArray[i].m_pEntity); glowArray[i].m_bRenderWhenOccluded = 1; glowArray[i].m_bRenderWhenUnoccluded = 0; if(ent.m_iTeamNum == 2) { glowArray[i].m_flGlowRed = 1.0f; glowArray[i].m_flGlowGreen = 0.0f; glowArray[i].m_flGlowBlue = 0.0f; glowArray[i].m_flGlowAlpha = 0.6f; } else if(ent.m_iTeamNum == 3) { glowArray[i].m_flGlowRed = 0.0f; glowArray[i].m_flGlowGreen = 0.0f; glowArray[i].m_flGlowBlue = 1.0f; glowArray[i].m_flGlowAlpha = 0.6f; } } else { std::cout << "Unable to read entity..." << std::endl; } // We're going to try to avoid overwriting the entity pointer // This causes problems when entity pointers change and we overwrite the new one with the old! csgo->Write( ((uint8_t*) manager.m_GlowObjectDefinitions.DataPtr + (sizeof(hack::GlowObjectDefinition_t) * i)) + sizeof(void*), ((uint8_t*) &glowArray[i]) + sizeof(void*), sizeof(hack::GlowObjectDefinition_t) - sizeof(void*)); } delete[] glowArray; }<|endoftext|>
<commit_before>#include "Limiter.h" #include "Testing.h" #include <iostream> static auto CurrentTime() { return std::chrono::high_resolution_clock::now(); } static constexpr auto oneSecond = std::chrono::seconds(1); std::ostream& operator<<(std::ostream& os, HttpResult::Code code) { const auto str = code == HttpResult::Code::Ok ? "Ok (200)" : code == HttpResult::Code::TooManyRequests ? "Too many requests (429)" : "Unknown code"; os << str; return os; } template <typename Clock, typename Duration> std::string millisecondsSinceStart(std::chrono::time_point<Clock, Duration> timepoint) { const static auto start = timepoint.time_since_epoch().count(); return std::to_string((timepoint.time_since_epoch().count() - start) / 1'000'000); } static auto TestAllRequestsBelowMaxAreAccepted(int maxAllowedRps) { Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10)); const auto startTime = std::chrono::high_resolution_clock::now(); for (int i = 0; i < maxAllowedRps; ++i) if (CurrentTime() < startTime + oneSecond) ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } static auto TestAllRequestsAboveMaxAreDeclined(int maxAllowedRps) { Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10)); const auto startTime = std::chrono::high_resolution_clock::now(); for (int i = 0; i < maxAllowedRps; ++i) if (CurrentTime() < startTime + oneSecond) limiter.ValidateRequest(); while (CurrentTime() < startTime + oneSecond) ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); } struct TimeStamps { const std::chrono::time_point<std::chrono::high_resolution_clock> firstAcceptedRequest; const std::chrono::time_point<std::chrono::high_resolution_clock> lastAcceptedRequest; }; static auto TestWithPeakLoadInTheBeginning(Limiter& limiter) { // Accepting the requests until we hit the limit. const auto firstAcceptedRequestTime = CurrentTime(); for (int i = 0; i < limiter.maxRPS(); ++i) { ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } const auto lastAcceptedRequestTime = CurrentTime(); // Not accepting more requests within current second. while (CurrentTime() < firstAcceptedRequestTime + oneSecond) { ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); } // Still not accepting requests if less than one second has elapsed after the first request. if (CurrentTime() < firstAcceptedRequestTime + oneSecond) ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); std::this_thread::sleep_until(firstAcceptedRequestTime + std::chrono::milliseconds(900)); if (CurrentTime() < firstAcceptedRequestTime + oneSecond) ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); return TimeStamps{ firstAcceptedRequestTime, lastAcceptedRequestTime }; } static auto TestWithPeakLoadInTheBeginning_SingleIteration(int maxAllowedRps) { Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10)); const auto timeStamps = TestWithPeakLoadInTheBeginning(limiter); // Herewith we ensure that NOT MORE than maxAllowedRps requests are allowed per second. // It is possible that the limiter will allow a bit LESS, though, hence this "delta" allowance // in the assertion below. constexpr auto delayDueToTimerIssueObtainedEmpirically = std::chrono::milliseconds(42); std::this_thread::sleep_until(timeStamps.firstAcceptedRequest + oneSecond + delayDueToTimerIssueObtainedEmpirically); ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } static auto TestWithPeakLoadInTheBeginning_MultipleIterations(int maxAllowedRps, int iterations) { Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10)); for (int i = 0; i < iterations; ++i) { const auto timeStamps = TestWithPeakLoadInTheBeginning(limiter); std::this_thread::sleep_until(timeStamps.lastAcceptedRequest + oneSecond); } } static auto TestWithEvenLoad(int maxAllowedRps) { Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10)); const auto intervalBetweenRequests = oneSecond / (2 * maxAllowedRps); for (int iterations = 0; iterations < 5; ++iterations) { int requestsSent = 0; const auto startTime = CurrentTime(); while (requestsSent < maxAllowedRps && CurrentTime() < startTime + oneSecond) { ++requestsSent; const auto result = limiter.ValidateRequest(); if (result != HttpResult::Code::Ok) std::cout << "iterations = " << iterations << "; requestsSent = " << requestsSent << '\n'; ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); std::this_thread::sleep_for(intervalBetweenRequests); } const auto lastValidRequestTime = CurrentTime(); while (CurrentTime() < startTime + oneSecond) { ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); std::this_thread::sleep_for(intervalBetweenRequests); } std::this_thread::sleep_until(lastValidRequestTime + oneSecond); ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } } static auto TestWithAdjacentPeaks(int maxAllowedRps) { const auto startTime = CurrentTime(); Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10)); std::this_thread::sleep_until(startTime + std::chrono::milliseconds(900)); int requestsSent = 0; while (requestsSent < maxAllowedRps * 0.8) { requestsSent++; ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } std::this_thread::sleep_until(startTime + std::chrono::milliseconds(1500)); while (requestsSent < maxAllowedRps) { requestsSent++; ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } std::cout << "requestsSent == " << requestsSent << '\n'; while (CurrentTime() < startTime + std::chrono::milliseconds(1900)) { requestsSent++; const auto result = limiter.ValidateRequest(); if (result != HttpResult::Code::TooManyRequests) std::cout << "requestsSent == " << requestsSent << '\n'; ASSERT_EQUAL(result, HttpResult::Code::TooManyRequests); } std::this_thread::sleep_until(startTime + std::chrono::milliseconds(2000)); ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } namespace LimiterSpecs { static constexpr int minRPS = 1; static constexpr int maxRPS = 100'000; }; int main() { try { //TestAllRequestsBelowMaxAreAccepted(LimiterSpecs::maxRPS); //TestAllRequestsAboveMaxAreDeclined(LimiterSpecs::maxRPS); //TestWithPeakLoadInTheBeginning(LimiterSpecs::maxRPS); //TestWithAdjacentPeaks(LimiterSpecs::maxRPS); TestWithEvenLoad(LimiterSpecs::maxRPS); std::cout << "All Tests passed successfully\n"; } catch (AssertionException& e) { std::cout << "One or more of tests failed: " << e.what() << '\n'; } system("pause"); return 0; } <commit_msg>Tests - uncomment working tests<commit_after>#include "Limiter.h" #include "Testing.h" #include <iostream> static auto CurrentTime() { return std::chrono::high_resolution_clock::now(); } static constexpr auto oneSecond = std::chrono::seconds(1); std::ostream& operator<<(std::ostream& os, HttpResult::Code code) { const auto str = code == HttpResult::Code::Ok ? "Ok (200)" : code == HttpResult::Code::TooManyRequests ? "Too many requests (429)" : "Unknown code"; os << str; return os; } template <typename Clock, typename Duration> std::string millisecondsSinceStart(std::chrono::time_point<Clock, Duration> timepoint) { const static auto start = timepoint.time_since_epoch().count(); return std::to_string((timepoint.time_since_epoch().count() - start) / 1'000'000); } static auto TestAllRequestsBelowMaxAreAccepted(int maxAllowedRps) { Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10)); const auto startTime = std::chrono::high_resolution_clock::now(); for (int i = 0; i < maxAllowedRps; ++i) if (CurrentTime() < startTime + oneSecond) ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } static auto TestAllRequestsAboveMaxAreDeclined(int maxAllowedRps) { Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10)); const auto startTime = std::chrono::high_resolution_clock::now(); for (int i = 0; i < maxAllowedRps; ++i) if (CurrentTime() < startTime + oneSecond) limiter.ValidateRequest(); while (CurrentTime() < startTime + oneSecond) ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); } struct TimeStamps { const std::chrono::time_point<std::chrono::high_resolution_clock> firstAcceptedRequest; const std::chrono::time_point<std::chrono::high_resolution_clock> lastAcceptedRequest; }; static auto TestWithPeakLoadInTheBeginning(Limiter& limiter) { // Accepting the requests until we hit the limit. const auto firstAcceptedRequestTime = CurrentTime(); for (int i = 0; i < limiter.maxRPS(); ++i) { ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } const auto lastAcceptedRequestTime = CurrentTime(); // Not accepting more requests within current second. while (CurrentTime() < firstAcceptedRequestTime + oneSecond) { ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); } // Still not accepting requests if less than one second has elapsed after the first request. if (CurrentTime() < firstAcceptedRequestTime + oneSecond) ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); std::this_thread::sleep_until(firstAcceptedRequestTime + std::chrono::milliseconds(900)); if (CurrentTime() < firstAcceptedRequestTime + oneSecond) ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); return TimeStamps{ firstAcceptedRequestTime, lastAcceptedRequestTime }; } static auto TestWithPeakLoadInTheBeginning_SingleIteration(int maxAllowedRps) { Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10)); const auto timeStamps = TestWithPeakLoadInTheBeginning(limiter); // Herewith we ensure that NOT MORE than maxAllowedRps requests are allowed per second. // It is possible that the limiter will allow a bit LESS, though, hence this "delta" allowance // in the assertion below. constexpr auto delayDueToTimerIssueObtainedEmpirically = std::chrono::milliseconds(42); std::this_thread::sleep_until(timeStamps.firstAcceptedRequest + oneSecond + delayDueToTimerIssueObtainedEmpirically); ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } static auto TestWithPeakLoadInTheBeginning_MultipleIterations(int maxAllowedRps, int iterations) { Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10)); for (int i = 0; i < iterations; ++i) { const auto timeStamps = TestWithPeakLoadInTheBeginning(limiter); std::this_thread::sleep_until(timeStamps.lastAcceptedRequest + oneSecond); } } static auto TestWithEvenLoad(int maxAllowedRps) { Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10)); const auto intervalBetweenRequests = oneSecond / (2 * maxAllowedRps); for (int iterations = 0; iterations < 5; ++iterations) { int requestsSent = 0; const auto startTime = CurrentTime(); while (requestsSent < maxAllowedRps && CurrentTime() < startTime + oneSecond) { ++requestsSent; const auto result = limiter.ValidateRequest(); if (result != HttpResult::Code::Ok) std::cout << "iterations = " << iterations << "; requestsSent = " << requestsSent << '\n'; ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); std::this_thread::sleep_for(intervalBetweenRequests); } const auto lastValidRequestTime = CurrentTime(); while (CurrentTime() < startTime + oneSecond) { ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); std::this_thread::sleep_for(intervalBetweenRequests); } std::this_thread::sleep_until(lastValidRequestTime + oneSecond); ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } } static auto TestWithAdjacentPeaks(int maxAllowedRps) { const auto startTime = CurrentTime(); Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10)); std::this_thread::sleep_until(startTime + std::chrono::milliseconds(900)); int requestsSent = 0; while (requestsSent < maxAllowedRps * 0.8) { requestsSent++; ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } std::this_thread::sleep_until(startTime + std::chrono::milliseconds(1500)); while (requestsSent < maxAllowedRps) { requestsSent++; ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } std::cout << "requestsSent == " << requestsSent << '\n'; while (CurrentTime() < startTime + std::chrono::milliseconds(1900)) { requestsSent++; const auto result = limiter.ValidateRequest(); if (result != HttpResult::Code::TooManyRequests) std::cout << "requestsSent == " << requestsSent << '\n'; ASSERT_EQUAL(result, HttpResult::Code::TooManyRequests); } std::this_thread::sleep_until(startTime + std::chrono::milliseconds(2000)); ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } namespace LimiterSpecs { static constexpr int minRPS = 1; static constexpr int maxRPS = 100'000; }; int main() { // Failing tests are commented out. try { TestAllRequestsBelowMaxAreAccepted(LimiterSpecs::maxRPS); TestAllRequestsAboveMaxAreDeclined(LimiterSpecs::maxRPS); TestWithPeakLoadInTheBeginning_SingleIteration(LimiterSpecs::maxRPS); //TestWithPeakLoadInTheBeginning_MultipleIterations(LimiterSpecs::maxRPS, 10); TestWithAdjacentPeaks(LimiterSpecs::maxRPS); //TestWithEvenLoad(LimiterSpecs::maxRPS); std::cout << "All Tests passed successfully\n"; } catch (AssertionException& e) { std::cout << "One or more of tests failed: " << e.what() << '\n'; } system("pause"); return 0; } <|endoftext|>
<commit_before>#include "TestScene.h" CTestScene::CTestScene(void) { m_LogoLabelEnglish = NNLabel::Create( L"JuGums", L"Something Strange", 75.f ); m_LogoLabelEnglish->SetColor( 255, 0, 0 ); m_LogoLabelEnglish->SetPosition( 90.f, 30.f ); AddChild( m_LogoLabelEnglish ); m_LogoLabelKorean = NNLabel::Create( L"ְ˵", L"üü", 50.f ); m_LogoLabelKorean->SetPosition( 170.f, 105.f ); AddChild( m_LogoLabelKorean ); m_PlayMenuLabel = NNLabel::Create( L"Play", L"üü", 40.f ); m_PlayMenuLabel->SetPosition( 160.f, 300.f ); AddChild( m_PlayMenuLabel ); m_TestMenuLabel = NNLabel::Create( L"test", L"üü", 40.f ); m_TestMenuLabel->SetPosition( 160.f, 360.f ); AddChild( m_TestMenuLabel ); m_QuitMenuLabel = NNLabel::Create( L"Quit", L"üü", 40.f ); m_QuitMenuLabel->SetPosition( 160.f, 420.f ); AddChild( m_QuitMenuLabel ); m_KeyOn = 0; m_MenuLabel[0] = m_PlayMenuLabel; m_MenuLabel[1] = m_TestMenuLabel; m_MenuLabel[2] = m_QuitMenuLabel; } CTestScene::~CTestScene(void) { } void CTestScene::Render() { NNScene::Render(); } void CTestScene::Update( float dTime ) { m_MenuLabel[m_KeyOn]->SetColor( 0, 0, 0 ); if ( NNInputSystem::GetInstance()->GetKeyState( VK_UP ) == KEY_DOWN || NNInputSystem::GetInstance()->GetKeyState( VK_LEFT ) == KEY_DOWN ) { m_KeyOn = --m_KeyOn % 3; } if ( NNInputSystem::GetInstance()->GetKeyState( VK_DOWN ) == KEY_DOWN || NNInputSystem::GetInstance()->GetKeyState( VK_RIGHT ) == KEY_DOWN ) { m_KeyOn = ++m_KeyOn % 3; } m_MenuLabel[m_KeyOn]->SetColor( 255, 0, 0 ); }<commit_msg>디버깅용 콘솔창 출력 예시 - printf_s<commit_after>#include "TestScene.h" CTestScene::CTestScene(void) { m_LogoLabelEnglish = NNLabel::Create( L"JuGums", L"Something Strange", 75.f ); m_LogoLabelEnglish->SetColor( 255, 0, 0 ); m_LogoLabelEnglish->SetPosition( 90.f, 30.f ); AddChild( m_LogoLabelEnglish ); m_LogoLabelKorean = NNLabel::Create( L"ְ˵", L"üü", 50.f ); m_LogoLabelKorean->SetPosition( 170.f, 105.f ); AddChild( m_LogoLabelKorean ); m_PlayMenuLabel = NNLabel::Create( L"Play", L"üü", 40.f ); m_PlayMenuLabel->SetPosition( 160.f, 300.f ); AddChild( m_PlayMenuLabel ); m_TestMenuLabel = NNLabel::Create( L"test", L"üü", 40.f ); m_TestMenuLabel->SetPosition( 160.f, 360.f ); AddChild( m_TestMenuLabel ); m_QuitMenuLabel = NNLabel::Create( L"Quit", L"üü", 40.f ); m_QuitMenuLabel->SetPosition( 160.f, 420.f ); AddChild( m_QuitMenuLabel ); m_KeyOn = 0; m_MenuLabel[0] = m_PlayMenuLabel; m_MenuLabel[1] = m_TestMenuLabel; m_MenuLabel[2] = m_QuitMenuLabel; } CTestScene::~CTestScene(void) { } void CTestScene::Render() { NNScene::Render(); } void CTestScene::Update( float dTime ) { m_MenuLabel[m_KeyOn]->SetColor( 0, 0, 0 ); if ( NNInputSystem::GetInstance()->GetKeyState( VK_UP ) == KEY_DOWN || NNInputSystem::GetInstance()->GetKeyState( VK_LEFT ) == KEY_DOWN ) { m_KeyOn = --m_KeyOn % 3; } if ( NNInputSystem::GetInstance()->GetKeyState( VK_DOWN ) == KEY_DOWN || NNInputSystem::GetInstance()->GetKeyState( VK_RIGHT ) == KEY_DOWN ) { m_KeyOn = ++m_KeyOn % 3; } printf_s("point : %d\n", m_KeyOn); // ܼ â . m_MenuLabel[m_KeyOn]->SetColor( 255, 0, 0 ); }<|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // FILE: Rapp.cpp // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: Rapp UGA40 adapter // COPYRIGHT: University of California, San Francisco, 2012 // All rights reserved // // LICENSE: 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. // // You should have received a copy of the GNU Lesser General Public // License along with the source distribution; if not, write to // the Free Software Foundation, Inc., 59 Temple Place, Suite 330, // Boston, MA 02111-1307 USA // // This file 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. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // // AUTHOR: Arthur Edelstein, 2012 // Special thanks to Andre Ratz #ifdef WIN32 #define snprintf _snprintf #pragma warning(disable: 4355) #endif #include "Rapp.h" #include <cstdio> #include <string> #include <math.h> #include "../../MMDevice/ModuleInterface.h" #include "../../MMDevice/DeviceUtils.h" #include <sstream> #include <iostream> const char* g_RappScannerName = "RappScanner"; #define ERR_PORT_CHANGE_FORBIDDEN 10004 #define GALVO_RANGE 4096 /////////////////////////////////////////////////////////////////////////////// // Exported MMDevice API /////////////////////////////////////////////////////////////////////////////// MODULE_API void InitializeModuleData() { AddAvailableDeviceName(g_RappScannerName, "RappScanner"); } MODULE_API MM::Device* CreateDevice(const char* deviceName) { if (deviceName == 0) return 0; if (strcmp(deviceName, g_RappScannerName) == 0) { RappScanner* s = new RappScanner(); return s; } return 0; } MODULE_API void DeleteDevice(MM::Device* pDevice) { delete pDevice; } MM::DeviceDetectionStatus RappScannerDetect(MM::Device& /*device*/, MM::Core& /*core*/, std::string portToCheck, double /*answerTimeoutMs*/) { // all conditions must be satisfied... MM::DeviceDetectionStatus result = MM::Misconfigured; return result; } /////////////////////////////////////////////////////////////////////////////// // RappScanner // RappScanner::RappScanner() : initialized_(false), port_(""), calibrationMode_(0), polygonAccuracy_(10), polygonMinRectSize_(10), ttlTriggered_("Rising Edge"), rasterFrequency_(500), spotSize_(10), laser2_(false) { InitializeDefaultErrorMessages(); // create pre-initialization properties // ------------------------------------ // Name CreateProperty(MM::g_Keyword_Name, g_RappScannerName, MM::String, true); // Description CreateProperty(MM::g_Keyword_Description, "Rapp UGA-40 galvo phototargeting adapter", MM::String, true); // Port CPropertyAction* pAct = new CPropertyAction (this, &RappScanner::OnPort); obsROE_Device* dev = new obsROE_Device(); std::vector<std::string> s = dev->SearchDevices(); if (s.size() <= 0) { s.push_back(std::string("Undefined")); } // The following line crashes hardware wizard if compiled in a Debug configuration: CreateProperty("VirtualComPort", s.at(0).c_str(), MM::String, false, pAct, true); for (unsigned int i = 0; i < s.size(); i++) { AddAllowedValue("VirtualComPort", s.at(i).c_str()); } } RappScanner::~RappScanner() { Shutdown(); } void RappScanner::GetName(char* Name) const { CDeviceUtils::CopyLimitedString(Name, g_RappScannerName); } MM::DeviceDetectionStatus RappScanner::DetectDevice(void) { return MM::Misconfigured; } int RappScanner::Initialize() { UGA_ = new obsROE_Device(); UGA_->Connect(port_.c_str()); if (UGA_->IsConnected()) { UGA_->UseMaxCalibration(false); UGA_->SetCalibrationMode(false, laser2_); RunDummyCalibration(); UGA_->CenterSpot(); currentX_ = 0; currentY_ = 0; initialized_ = true; } else { initialized_ = false; return DEVICE_NOT_CONNECTED; } CPropertyAction* pAct = new CPropertyAction(this, &RappScanner::OnCalibrationMode); CreateProperty("CalibrationMode", "0", MM::Integer, false, pAct); AddAllowedValue("CalibrationMode", "1"); AddAllowedValue("CalibrationMode", "0"); pAct = new CPropertyAction(this, &RappScanner::OnSequence); CreateProperty("Sequence", "", MM::String, false, pAct); pAct = new CPropertyAction(this, &RappScanner::OnTTLTriggered); CreateProperty("TTLTriggered", "Rising Edge", MM::String, false, pAct); AddAllowedValue("TTLTriggered", "Rising Edge"); AddAllowedValue("TTLTriggered", "Falling Edge"); pAct = new CPropertyAction(this, &RappScanner::OnSpotSize); CreateProperty("SpotSize", "0", MM::Float, false, pAct); pAct = new CPropertyAction(this, &RappScanner::OnRasterFrequency); CreateProperty("RasterFrequency_Hz", "500", MM::Integer, false, pAct); pAct = new CPropertyAction(this, &RappScanner::OnAccuracy); CreateProperty("AccuracyPercent", "10", MM::Integer, false, pAct); pAct = new CPropertyAction(this, &RappScanner::OnMinimumRectSize); CreateProperty("MinimumRectSize", "250", MM::Integer, false, pAct); return DEVICE_OK; } int RappScanner::Shutdown() { int result = DEVICE_NOT_CONNECTED; if (initialized_) { if (UGA_->IsConnected()) { if (UGA_->Disconnect()) { initialized_ = false; result = DEVICE_OK; } } delete UGA_; } return result; } bool RappScanner::Busy() { return false; } ///////////////////////////// // Galvo API ///////////////////////////// int RappScanner::PointAndFire(double x, double y, double pulseTime_us) { pointf xy((float) x,(float) y); bool success = UGA_->ClickAndFire(xy, (int) pulseTime_us, laser2_); return success ? DEVICE_OK : DEVICE_ERR; } int RappScanner::SetPosition(double x, double y) { bool success = UGA_->SetDevicePosition((int) x,(int) y); return success ? DEVICE_OK : DEVICE_ERR; } int RappScanner::GetPosition(double& x, double& y) { pointf p = UGA_->CurrentPosition(); x = p.x; y = p.y; return DEVICE_OK; } double RappScanner::GetXRange() { return (double) GALVO_RANGE; } double RappScanner::GetYRange() { return (double) GALVO_RANGE; } int RappScanner::AddPolygonVertex(int polygonIndex, double x, double y) { if (polygons_.size() < (unsigned) (1+polygonIndex)) { polygons_.resize(1+polygonIndex); } polygons_.at(polygonIndex).push_back(pointf((float) x, (float) y)); return DEVICE_OK; } int RappScanner::DeletePolygons() { polygons_.clear(); UGA_->DeletePolygons(); return DEVICE_OK; } int RappScanner::LoadPolygons(int repeats) { tRectList rectangles; pointf minRectDimensions((float) polygonMinRectSize_, (float) polygonMinRectSize_); for (unsigned polygonIndex=0;polygonIndex<polygons_.size();++polygonIndex) { UGA_->CreateA(polygons_.at(polygonIndex), polygonAccuracy_, minRectDimensions, &rectangles, laser2_); } tStringList sequenceList; int n = polygons_.size(); sequenceList.push_back(std::string("on")); for (int i=0; i<n; ++i) { stringstream poly; poly << "poly," << i; sequenceList.push_back(poly.str()); } stringstream repeat; repeat << "repeat," << min(1,repeats); sequenceList.push_back(repeat.str()); sequenceList.push_back(std::string("off")); if (!UGA_->StoreSequence(sequenceList)) { return DEVICE_ERR; } return DEVICE_OK; } int RappScanner::RunPolygons() { return UGA_->RunSequence(false) ? DEVICE_OK : DEVICE_ERR; } int RappScanner::RunSequence() { if (sequence_.size() > 0) { std::string sequence2 = replaceChar(sequence_, ':', ','); tStringList sequenceList = split(sequence2, ' '); if (!UGA_->StoreSequence(sequenceList)) { return DEVICE_ERR; } } return UGA_->RunSequence(false) ? DEVICE_OK : DEVICE_ERR; } int RappScanner::StopSequence() { if (UGA_->AbortSequence()) { return DEVICE_OK; } else { return DEVICE_ERR; } } ///////////////////////////// // Property Action Handlers ///////////////////////////// int RappScanner::OnCalibrationMode(MM::PropertyBase* pProp, MM::ActionType eAct) { int result = DEVICE_OK; if (eAct == MM::BeforeGet) { pProp->Set(calibrationMode_); } else if (eAct == MM::AfterSet) { pProp->Get(calibrationMode_); if (UGA_->SetCalibrationMode(calibrationMode_ == 1, laser2_)) { result = DEVICE_OK; } else { result = DEVICE_NOT_CONNECTED; } } return result; } int RappScanner::OnPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(port_.c_str()); } else if (eAct == MM::AfterSet) { if (initialized_) { // revert pProp->Set(port_.c_str()); return ERR_PORT_CHANGE_FORBIDDEN; } pProp->Get(port_); } return DEVICE_OK; } int RappScanner::OnSequence(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(sequence_.c_str()); } else if (eAct == MM::AfterSet) { pProp->Get(sequence_); } return DEVICE_OK; } int RappScanner::OnTTLTriggered(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(ttlTriggered_.c_str()); } else if (eAct == MM::AfterSet) { pProp->Get(ttlTriggered_); if (0 == ttlTriggered_.compare("Rising Edge")) { UGA_->SetTriggerBehavior(RisingEdge); } else { UGA_->SetTriggerBehavior(FallingEdge); } } return DEVICE_OK; } int RappScanner::OnSpotSize(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(spotSize_); } else if (eAct == MM::AfterSet) { pProp->Get(spotSize_); UGA_->DefineSpotSize((float) spotSize_, laser2_); } return DEVICE_OK; } int RappScanner::OnRasterFrequency(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(rasterFrequency_); } else if (eAct == MM::AfterSet) { pProp->Get(rasterFrequency_); UGA_->SetROIFrequence(rasterFrequency_, laser2_); // [sic] } return DEVICE_OK; } int RappScanner::OnAccuracy(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(polygonAccuracy_); } else if (eAct == MM::AfterSet) { pProp->Get(polygonAccuracy_); } return DEVICE_OK; } int RappScanner::OnMinimumRectSize(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(polygonMinRectSize_); } else if (eAct == MM::AfterSet) { pProp->Get(polygonMinRectSize_); } return DEVICE_OK; } ///////////////////////////// // Helper Functions ///////////////////////////// void RappScanner::RunDummyCalibration() { int side = 4096; UGA_->SetCalibrationMode(true, laser2_); UGA_->SetAOIEdge(Up, 0, laser2_); UGA_->SetAOIEdge(Down, side-1, laser2_); UGA_->SetAOIEdge(Left, 0, laser2_); UGA_->SetAOIEdge(Right, side-1, laser2_); pointf p0(0, 0); pointf p1((float) side-1, 0); pointf p2(0, (float) side-1); pointf p3((float) side-1, (float) side-1); UGA_->UseMaxCalibration(false); UGA_->InitializeCalibration(4, laser2_); UGA_->CenterSpot(); UGA_->MoveLaser(Up, side/2 - 1); UGA_->MoveLaser(Left, side/2 - 1); UGA_->SetCalibrationPoint(false, 0, p0, laser2_); UGA_->MoveLaser(Right, side); UGA_->SetCalibrationPoint(false, 1, p1, laser2_); UGA_->MoveLaser(Down, side); UGA_->SetCalibrationPoint(false, 3, p3, laser2_); //Point-ID 2->3 UGA_->MoveLaser(Left, side); UGA_->SetCalibrationPoint(false, 2, p2, laser2_); //Point-ID 3->2 UGA_->SetCalibrationMode(calibrationMode_ == 1, laser2_); } std::vector<std::string> & split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } std::string replaceChar(std::string str, char ch1, char ch2) { std::string str2(str); for (unsigned i = 0; i < str2.length(); ++i) { if (str2[i] == ch1) str2[i] = ch2; } return str2; }<commit_msg>Start using executorservice to make control of galvo thread safe.<commit_after>/////////////////////////////////////////////////////////////////////////////// // FILE: Rapp.cpp // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: Rapp UGA40 adapter // COPYRIGHT: University of California, San Francisco, 2012 // All rights reserved // // LICENSE: 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. // // You should have received a copy of the GNU Lesser General Public // License along with the source distribution; if not, write to // the Free Software Foundation, Inc., 59 Temple Place, Suite 330, // Boston, MA 02111-1307 USA // // This file 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. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // // AUTHOR: Arthur Edelstein, 2012 // Special thanks to Andre Ratz #ifdef WIN32 #define snprintf _snprintf #pragma warning(disable: 4355) #endif #include "Rapp.h" #include <cstdio> #include <string> #include <math.h> #include "../../MMDevice/ModuleInterface.h" #include "../../MMDevice/DeviceUtils.h" #include <sstream> #include <iostream> const char* g_RappScannerName = "RappScanner"; #define ERR_PORT_CHANGE_FORBIDDEN 10004 #define GALVO_RANGE 4096 /////////////////////////////////////////////////////////////////////////////// // Exported MMDevice API /////////////////////////////////////////////////////////////////////////////// MODULE_API void InitializeModuleData() { AddAvailableDeviceName(g_RappScannerName, "RappScanner"); } MODULE_API MM::Device* CreateDevice(const char* deviceName) { if (deviceName == 0) return 0; if (strcmp(deviceName, g_RappScannerName) == 0) { RappScanner* s = new RappScanner(); return s; } return 0; } MODULE_API void DeleteDevice(MM::Device* pDevice) { delete pDevice; } MM::DeviceDetectionStatus RappScannerDetect(MM::Device& /*device*/, MM::Core& /*core*/, std::string portToCheck, double /*answerTimeoutMs*/) { // all conditions must be satisfied... MM::DeviceDetectionStatus result = MM::Misconfigured; return result; } /////////////////////////////////////////////////////////////////////////////// // RappScanner // RappScanner::RappScanner() : initialized_(false), port_(""), calibrationMode_(0), polygonAccuracy_(10), polygonMinRectSize_(10), ttlTriggered_("Rising Edge"), rasterFrequency_(500), spotSize_(10), laser2_(false) { InitializeDefaultErrorMessages(); // create pre-initialization properties // ------------------------------------ // Name CreateProperty(MM::g_Keyword_Name, g_RappScannerName, MM::String, true); // Description CreateProperty(MM::g_Keyword_Description, "Rapp UGA-40 galvo phototargeting adapter", MM::String, true); // Port CPropertyAction* pAct = new CPropertyAction (this, &RappScanner::OnPort); obsROE_Device* dev = new obsROE_Device(); std::vector<std::string> s = dev->SearchDevices(); if (s.size() <= 0) { s.push_back(std::string("Undefined")); } // The following line crashes hardware wizard if compiled in a Debug configuration: CreateProperty("VirtualComPort", s.at(0).c_str(), MM::String, false, pAct, true); for (unsigned int i = 0; i < s.size(); i++) { AddAllowedValue("VirtualComPort", s.at(i).c_str()); } } RappScanner::~RappScanner() { Shutdown(); } void RappScanner::GetName(char* Name) const { CDeviceUtils::CopyLimitedString(Name, g_RappScannerName); } MM::DeviceDetectionStatus RappScanner::DetectDevice(void) { return MM::Misconfigured; } int RappScanner::Initialize() { UGA_ = new obsROE_Device(); UGA_->Connect(port_.c_str()); if (UGA_->IsConnected()) { UGA_->UseMaxCalibration(false); UGA_->SetCalibrationMode(false, laser2_); RunDummyCalibration(); UGA_->CenterSpot(); currentX_ = 0; currentY_ = 0; initialized_ = true; } else { initialized_ = false; return DEVICE_NOT_CONNECTED; } CPropertyAction* pAct = new CPropertyAction(this, &RappScanner::OnCalibrationMode); CreateProperty("CalibrationMode", "0", MM::Integer, false, pAct); AddAllowedValue("CalibrationMode", "1"); AddAllowedValue("CalibrationMode", "0"); pAct = new CPropertyAction(this, &RappScanner::OnSequence); CreateProperty("Sequence", "", MM::String, false, pAct); pAct = new CPropertyAction(this, &RappScanner::OnTTLTriggered); CreateProperty("TTLTriggered", "Rising Edge", MM::String, false, pAct); AddAllowedValue("TTLTriggered", "Rising Edge"); AddAllowedValue("TTLTriggered", "Falling Edge"); pAct = new CPropertyAction(this, &RappScanner::OnSpotSize); CreateProperty("SpotSize", "0", MM::Float, false, pAct); pAct = new CPropertyAction(this, &RappScanner::OnRasterFrequency); CreateProperty("RasterFrequency_Hz", "500", MM::Integer, false, pAct); pAct = new CPropertyAction(this, &RappScanner::OnAccuracy); CreateProperty("AccuracyPercent", "10", MM::Integer, false, pAct); pAct = new CPropertyAction(this, &RappScanner::OnMinimumRectSize); CreateProperty("MinimumRectSize", "250", MM::Integer, false, pAct); return DEVICE_OK; } int RappScanner::Shutdown() { int result = DEVICE_NOT_CONNECTED; if (initialized_) { if (UGA_->IsConnected()) { if (UGA_->Disconnect()) { initialized_ = false; result = DEVICE_OK; } } delete UGA_; } return result; } bool RappScanner::Busy() { return false; } ///////////////////////////// // Galvo API ///////////////////////////// int RappScanner::PointAndFire(double x, double y, double pulseTime_us) { pointf xy((float) x,(float) y); bool success = UGA_->ClickAndFire(xy, (int) pulseTime_us, laser2_); return success ? DEVICE_OK : DEVICE_ERR; } int RappScanner::SetPosition(double x, double y) { bool success = UGA_->SetDevicePosition((int) x,(int) y); return success ? DEVICE_OK : DEVICE_ERR; } int RappScanner::GetPosition(double& x, double& y) { pointf p = UGA_->CurrentPosition(); x = p.x; y = p.y; return DEVICE_OK; } double RappScanner::GetXRange() { return (double) GALVO_RANGE; } double RappScanner::GetYRange() { return (double) GALVO_RANGE; } int RappScanner::AddPolygonVertex(int polygonIndex, double x, double y) { if (polygons_.size() < (unsigned) (1+polygonIndex)) { polygons_.resize(1+polygonIndex); } polygons_.at(polygonIndex).push_back(pointf((float) x, (float) y)); return DEVICE_OK; } int RappScanner::DeletePolygons() { polygons_.clear(); UGA_->DeletePolygons(); return DEVICE_OK; } int RappScanner::LoadPolygons(int repeats) { tRectList rectangles; pointf minRectDimensions((float) polygonMinRectSize_, (float) polygonMinRectSize_); for (unsigned polygonIndex=0;polygonIndex<polygons_.size();++polygonIndex) { UGA_->CreateA(polygons_.at(polygonIndex), polygonAccuracy_, minRectDimensions, &rectangles, laser2_); } tStringList sequenceList; int n = polygons_.size(); sequenceList.push_back(std::string("on")); for (int i=0; i<n; ++i) { stringstream poly; poly << "poly," << i; sequenceList.push_back(poly.str()); } if (repeats > 0) { stringstream repeat; repeat << "repeat," << max(0,repeats); sequenceList.push_back(repeat.str()); } sequenceList.push_back(std::string("off")); if (!UGA_->StoreSequence(sequenceList)) { return DEVICE_ERR; } return DEVICE_OK; } int RappScanner::RunPolygons() { return UGA_->RunSequence(false) ? DEVICE_OK : DEVICE_ERR; } int RappScanner::RunSequence() { if (sequence_.size() > 0) { std::string sequence2 = replaceChar(sequence_, ':', ','); tStringList sequenceList = split(sequence2, ' '); if (!UGA_->StoreSequence(sequenceList)) { return DEVICE_ERR; } } return UGA_->RunSequence(false) ? DEVICE_OK : DEVICE_ERR; } int RappScanner::StopSequence() { if (UGA_->AbortSequence()) { return DEVICE_OK; } else { return DEVICE_ERR; } } ///////////////////////////// // Property Action Handlers ///////////////////////////// int RappScanner::OnCalibrationMode(MM::PropertyBase* pProp, MM::ActionType eAct) { int result = DEVICE_OK; if (eAct == MM::BeforeGet) { pProp->Set(calibrationMode_); } else if (eAct == MM::AfterSet) { pProp->Get(calibrationMode_); if (UGA_->SetCalibrationMode(calibrationMode_ == 1, laser2_)) { result = DEVICE_OK; } else { result = DEVICE_NOT_CONNECTED; } } return result; } int RappScanner::OnPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(port_.c_str()); } else if (eAct == MM::AfterSet) { if (initialized_) { // revert pProp->Set(port_.c_str()); return ERR_PORT_CHANGE_FORBIDDEN; } pProp->Get(port_); } return DEVICE_OK; } int RappScanner::OnSequence(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(sequence_.c_str()); } else if (eAct == MM::AfterSet) { pProp->Get(sequence_); } return DEVICE_OK; } int RappScanner::OnTTLTriggered(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(ttlTriggered_.c_str()); } else if (eAct == MM::AfterSet) { pProp->Get(ttlTriggered_); if (0 == ttlTriggered_.compare("Rising Edge")) { UGA_->SetTriggerBehavior(RisingEdge); } else { UGA_->SetTriggerBehavior(FallingEdge); } } return DEVICE_OK; } int RappScanner::OnSpotSize(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(spotSize_); } else if (eAct == MM::AfterSet) { pProp->Get(spotSize_); UGA_->DefineSpotSize((float) spotSize_, laser2_); } return DEVICE_OK; } int RappScanner::OnRasterFrequency(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(rasterFrequency_); } else if (eAct == MM::AfterSet) { pProp->Get(rasterFrequency_); UGA_->SetROIFrequence(rasterFrequency_, laser2_); // [sic] } return DEVICE_OK; } int RappScanner::OnAccuracy(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(polygonAccuracy_); } else if (eAct == MM::AfterSet) { pProp->Get(polygonAccuracy_); } return DEVICE_OK; } int RappScanner::OnMinimumRectSize(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(polygonMinRectSize_); } else if (eAct == MM::AfterSet) { pProp->Get(polygonMinRectSize_); } return DEVICE_OK; } ///////////////////////////// // Helper Functions ///////////////////////////// void RappScanner::RunDummyCalibration() { int side = 4096; UGA_->SetCalibrationMode(true, laser2_); UGA_->SetAOIEdge(Up, 0, laser2_); UGA_->SetAOIEdge(Down, side-1, laser2_); UGA_->SetAOIEdge(Left, 0, laser2_); UGA_->SetAOIEdge(Right, side-1, laser2_); pointf p0(0, 0); pointf p1((float) side-1, 0); pointf p2(0, (float) side-1); pointf p3((float) side-1, (float) side-1); UGA_->UseMaxCalibration(false); UGA_->InitializeCalibration(4, laser2_); UGA_->CenterSpot(); UGA_->MoveLaser(Up, side/2 - 1); UGA_->MoveLaser(Left, side/2 - 1); UGA_->SetCalibrationPoint(false, 0, p0, laser2_); UGA_->MoveLaser(Right, side); UGA_->SetCalibrationPoint(false, 1, p1, laser2_); UGA_->MoveLaser(Down, side); UGA_->SetCalibrationPoint(false, 3, p3, laser2_); //Point-ID 2->3 UGA_->MoveLaser(Left, side); UGA_->SetCalibrationPoint(false, 2, p2, laser2_); //Point-ID 3->2 UGA_->SetCalibrationMode(calibrationMode_ == 1, laser2_); } std::vector<std::string> & split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } std::string replaceChar(std::string str, char ch1, char ch2) { std::string str2(str); for (unsigned i = 0; i < str2.length(); ++i) { if (str2[i] == ch1) str2[i] = ch2; } return str2; }<|endoftext|>
<commit_before>#define UNICODE #include <windows.h> #include <ole2.h> #include <oaidl.h> #include <objbase.h> #include <AtlBase.h> #include <AtlConv.h> #include <iostream> #include <sstream> #include <string> #include <vector> #include <stdlib.h> #include "FSAPI.h" #include "dictationbridge-core/master/master.h" #pragma comment(lib, "ole32.lib") #pragma comment(lib, "oleacc.lib") #define ERR(x, msg) do { \ if(x != S_OK) {\ MessageBox(NULL, msg L"\n", NULL, NULL);\ exit(1);\ }\ } while(0) std::string wideToString(wchar_t const * text, unsigned int length) { auto tmp = new char[length*2+1]; auto resultingLen = WideCharToMultiByte(CP_UTF8, NULL, text, length, tmp, length*2, NULL, NULL); tmp[resultingLen] = '\0'; std::string ret(tmp); delete[] tmp; return ret; } std::string BSTRToString(BSTR text) { unsigned int len = SysStringLen(text); return wideToString(text, len); } CComPtr<IJawsApi> pJfw =nullptr; void initSpeak() { CLSID JFWClass; auto res = CLSIDFromProgID(L"FreedomSci.JawsApi", &JFWClass); ERR(res, L"Couldn't get Jaws interface ID"); res =pJfw.CoCreateInstance(JFWClass); ERR(res, L"Couldn't create Jaws interface"); } void speak(wchar_t const * text) { auto s = SysAllocString(text); VARIANT_BOOL silence =VARIANT_FALSE; VARIANT_BOOL *jfwSuccess =VARIANT_FALSE; pJfw->SayString(s, silence , jfwSuccess); SysFreeString(s); } void WINAPI textCallback(HWND hwnd, DWORD startPosition, LPCWSTR textUnprocessed) { //We need to replace \r with nothing. int len = wcslen(textUnprocessed); wchar_t* text = new wchar_t[len+1]; int copied = 0; for(int i = 0; i < len; i++) { if(textUnprocessed[i] != L'\r') { text[copied] = textUnprocessed[i]; copied += 1; } } text[copied] = 0; if(wcscmp(text, L"\n\n") == 0 || wcscmp(text, L"") == 0 //new paragraph in word. ) { speak(L"New paragraph."); } else if(wcscmp(text, L"\n") == 0) { speak(L"New line."); } else { speak(text); } delete[] text; } void WINAPI textDeletedCallback(HWND hwnd, DWORD startPosition, LPCWSTR text) { std::wstringstream deletedText; deletedText << "Deleted "; deletedText << text; speak(deletedText.str().c_str()); } //These are string constants for the microphone status, as well as the status itself: //The pointer below is set to the last one we saw. const char* MICROPHONE_OFF = "Dragon's microphone is off;"; const char* MICROPHONE_ON = "Normal mode: You can dictate and use voice"; const char* MICROPHONE_SLEEPING = "The microphone is asleep;"; const char* microphoneState = nullptr; void announceMicrophoneState(const char* state) { if(state == MICROPHONE_ON) speak(L"Microphone on."); else if(state == MICROPHONE_OFF) speak(L"Microphone off."); else if(state == MICROPHONE_SLEEPING) speak(L"Microphone sleeping."); else speak(L"Microphone in unknown state."); } wchar_t processNameBuffer[1024] = {0}; void CALLBACK nameChanged(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime) { //First, is it coming from natspeak.exe? DWORD procId; GetWindowThreadProcessId(hwnd, &procId); auto procHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, procId); //We can't recover from this failing, so abort. if(procHandle == NULL) return; DWORD len = 1024; auto res = QueryFullProcessImageName(procHandle, 0, processNameBuffer, &len); CloseHandle(procHandle); if(res == 0) return; auto processName = wideToString(processNameBuffer, (unsigned int) len); if(processName.find("dragonbar.exe") == std::string::npos && processName.find("natspeak.exe") == std::string::npos) return; //Attempt to get the new text. IAccessible* acc = nullptr; VARIANT child; HRESULT hres = AccessibleObjectFromEvent(hwnd, idObject, idChild, &acc, &child); if(hres != S_OK || acc == nullptr) return; BSTR nameBSTR; hres = acc->get_accName(child, &nameBSTR); acc->Release(); if(hres != S_OK) return; auto name = BSTRToString(nameBSTR); SysFreeString(nameBSTR); const char* possibles[] = {MICROPHONE_ON, MICROPHONE_OFF, MICROPHONE_SLEEPING}; const char* newState = microphoneState; for(int i = 0; i < 3; i++) { if(name.find(possibles[i]) != std::string::npos) { newState = possibles[i]; break; } } if(newState != microphoneState) { announceMicrophoneState(newState); microphoneState = newState; } } int keepRunning = 1; // Goes to 0 on WM_CLOSE. LPCTSTR msgWindowClassName = L"DictationBridgeJFWHelper"; LRESULT CALLBACK exitProc(_In_ HWND hwnd, _In_ UINT msg, _In_ WPARAM wparam, _In_ LPARAM lparam) { if(msg == WM_CLOSE) keepRunning = 0; return DefWindowProc(hwnd, msg, wparam, lparam); } int CALLBACK WinMain(_In_ HINSTANCE hInstance, _In_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow) { // First, is a core running? if(FindWindow(msgWindowClassName, NULL)) { MessageBox(NULL, L"Core already running.", NULL, NULL); return 0; } WNDCLASS windowClass = {0}; windowClass.lpfnWndProc = exitProc; windowClass.hInstance = hInstance; windowClass.lpszClassName = msgWindowClassName; auto msgWindowClass = RegisterClass(&windowClass); if(msgWindowClass == 0) { MessageBox(NULL, L"Failed to register window class.", NULL, NULL); return 0; } auto msgWindowHandle = CreateWindow(msgWindowClassName, NULL, NULL, NULL, NULL, NULL, NULL, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL); if(msgWindowHandle == 0) { MessageBox(NULL, L"Failed to create message-only window.", NULL, NULL); return 0; } HRESULT res; res = OleInitialize(NULL); ERR(res, L"Couldn't initialize OLE"); initSpeak(); auto started = DBMaster_Start(); if(!started) { printf("Couldn't start DictationBridge-core\n"); return 1; } DBMaster_SetTextInsertedCallback(textCallback); DBMaster_SetTextDeletedCallback(textDeletedCallback); if(SetWinEventHook(EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, NULL, nameChanged, 0, 0, WINEVENT_OUTOFCONTEXT) == 0) { printf("Couldn't register to receive events\n"); return 1; } MSG msg; while(GetMessage(&msg, NULL, NULL, NULL) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); if(keepRunning == 0) break; } DBMaster_Stop(); OleUninitialize(); DestroyWindow(msgWindowHandle); return 0; } <commit_msg>Update the text callback to use c++ functions and classes rather than the win32 api.<commit_after>#define UNICODE #include <windows.h> #include <ole2.h> #include <oaidl.h> #include <objbase.h> #include <AtlBase.h> #include <AtlConv.h> #include <algorithm> #include <iostream> #include <sstream> #include <string> #include <vector> #include <stdlib.h> #include "FSAPI.h" #include "dictationbridge-core/master/master.h" #include <cmath> #pragma comment(lib, "ole32.lib") #pragma comment(lib, "oleacc.lib") #define ERR(x, msg) do { \ if(x != S_OK) {\ MessageBox(NULL, msg L"\n", NULL, NULL);\ exit(1);\ }\ } while(0) std::string wideToString(wchar_t const * text, unsigned int length) { auto tmp = new char[length*2+1]; auto resultingLen = WideCharToMultiByte(CP_UTF8, NULL, text, length, tmp, length*2, NULL, NULL); tmp[resultingLen] = '\0'; std::string ret(tmp); delete[] tmp; return ret; } std::string BSTRToString(BSTR text) { unsigned int len = SysStringLen(text); return wideToString(text, len); } CComPtr<IJawsApi> pJfw =nullptr; void initSpeak() { CLSID JFWClass; auto res = CLSIDFromProgID(L"FreedomSci.JawsApi", &JFWClass); ERR(res, L"Couldn't get Jaws interface ID"); res =pJfw.CoCreateInstance(JFWClass); ERR(res, L"Couldn't create Jaws interface"); } void speak(wchar_t const * text) { auto s = SysAllocString(text); VARIANT_BOOL silence =VARIANT_FALSE; VARIANT_BOOL *jfwSuccess =VARIANT_FALSE; pJfw->SayString(s, silence , jfwSuccess); SysFreeString(s); } void WINAPI textCallback(HWND hwnd, DWORD startPosition, LPCWSTR textUnprocessed) { //We need to replace \r with nothing. std::wstring text =textUnprocessed; text.erase(std::remove_if(begin(text), end(text), [] (wchar_t checkingCharacter) { return checkingCharacter == '\r'; }), end(text)); if(text.compare(L"\n\n") ==0 || text.compare(L"") ==0 //new paragraph in word. ) { speak(L"New paragraph."); } else if(text.compare(L"\n") ==0) { speak(L"New line."); } else { speak(text.c_str()); } } void WINAPI textDeletedCallback(HWND hwnd, DWORD startPosition, LPCWSTR text) { std::wstringstream deletedText; deletedText << "Deleted "; deletedText << text; speak(deletedText.str().c_str()); } //These are string constants for the microphone status, as well as the status itself: //The pointer below is set to the last one we saw. const char* MICROPHONE_OFF = "Dragon's microphone is off;"; const char* MICROPHONE_ON = "Normal mode: You can dictate and use voice"; const char* MICROPHONE_SLEEPING = "The microphone is asleep;"; const char* microphoneState = nullptr; void announceMicrophoneState(const char* state) { if(state == MICROPHONE_ON) speak(L"Microphone on."); else if(state == MICROPHONE_OFF) speak(L"Microphone off."); else if(state == MICROPHONE_SLEEPING) speak(L"Microphone sleeping."); else speak(L"Microphone in unknown state."); } wchar_t processNameBuffer[1024] = {0}; void CALLBACK nameChanged(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime) { //First, is it coming from natspeak.exe? DWORD procId; GetWindowThreadProcessId(hwnd, &procId); auto procHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, procId); //We can't recover from this failing, so abort. if(procHandle == NULL) return; DWORD len = 1024; auto res = QueryFullProcessImageName(procHandle, 0, processNameBuffer, &len); CloseHandle(procHandle); if(res == 0) return; auto processName = wideToString(processNameBuffer, (unsigned int) len); if(processName.find("dragonbar.exe") == std::string::npos && processName.find("natspeak.exe") == std::string::npos) return; //Attempt to get the new text. IAccessible* acc = nullptr; VARIANT child; HRESULT hres = AccessibleObjectFromEvent(hwnd, idObject, idChild, &acc, &child); if(hres != S_OK || acc == nullptr) return; BSTR nameBSTR; hres = acc->get_accName(child, &nameBSTR); acc->Release(); if(hres != S_OK) return; auto name = BSTRToString(nameBSTR); SysFreeString(nameBSTR); const char* possibles[] = {MICROPHONE_ON, MICROPHONE_OFF, MICROPHONE_SLEEPING}; const char* newState = microphoneState; for(int i = 0; i < 3; i++) { if(name.find(possibles[i]) != std::string::npos) { newState = possibles[i]; break; } } if(newState != microphoneState) { announceMicrophoneState(newState); microphoneState = newState; } } int keepRunning = 1; // Goes to 0 on WM_CLOSE. LPCTSTR msgWindowClassName = L"DictationBridgeJFWHelper"; LRESULT CALLBACK exitProc(_In_ HWND hwnd, _In_ UINT msg, _In_ WPARAM wparam, _In_ LPARAM lparam) { if(msg == WM_CLOSE) keepRunning = 0; return DefWindowProc(hwnd, msg, wparam, lparam); } int CALLBACK WinMain(_In_ HINSTANCE hInstance, _In_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow) { // First, is a core running? if(FindWindow(msgWindowClassName, NULL)) { MessageBox(NULL, L"Core already running.", NULL, NULL); return 0; } WNDCLASS windowClass = {0}; windowClass.lpfnWndProc = exitProc; windowClass.hInstance = hInstance; windowClass.lpszClassName = msgWindowClassName; auto msgWindowClass = RegisterClass(&windowClass); if(msgWindowClass == 0) { MessageBox(NULL, L"Failed to register window class.", NULL, NULL); return 0; } auto msgWindowHandle = CreateWindow(msgWindowClassName, NULL, NULL, NULL, NULL, NULL, NULL, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL); if(msgWindowHandle == 0) { MessageBox(NULL, L"Failed to create message-only window.", NULL, NULL); return 0; } HRESULT res; res = OleInitialize(NULL); ERR(res, L"Couldn't initialize OLE"); initSpeak(); auto started = DBMaster_Start(); if(!started) { printf("Couldn't start DictationBridge-core\n"); return 1; } DBMaster_SetTextInsertedCallback(textCallback); DBMaster_SetTextDeletedCallback(textDeletedCallback); if(SetWinEventHook(EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, NULL, nameChanged, 0, 0, WINEVENT_OUTOFCONTEXT) == 0) { printf("Couldn't register to receive events\n"); return 1; } MSG msg; while(GetMessage(&msg, NULL, NULL, NULL) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); if(keepRunning == 0) break; } DBMaster_Stop(); OleUninitialize(); DestroyWindow(msgWindowHandle); return 0; } <|endoftext|>
<commit_before>/* || || @file zilch.cpp || @version 0.2 || @author Colin Duffy || @contact cmduffy@engr.psu.edu || @author Warren Gay || @contact ve3wwg@gmail.com || || @description || Light weight task scheduler library, based off the awesome fibers || library by Warren Gay. https://github.com/ve3wwg/teensy3_fibers || || @license || | Copyright (c) 2014 Colin Duffy, (C) Warren Gay VE3WWG || | 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; version || | 2.1 of the License. || | || | This library is distributed in the hope that it will be useful, || | but WITHOUT ANY WARRANTY; without even the implied warranty of || | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU || | Lesser General Public License for more details. || | || | You should have received a copy of the GNU Lesser General Public || | License along with this library; if not, write to the Free Software || | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA || # || */ #include "zilch.h" #include "Arduino.h" #ifdef __cplusplus extern "C" { #endif void init_stack ( uint32_t main_stack, uint32_t pattern_override ); void task_create ( task_func_t func, uint32_t stack_size, volatile void *arg ); TaskState task_state ( task_func_t func ); TaskState main_state ( loop_func_t func ); TaskState task_sync ( task_func_t func ); TaskState task_restart ( task_func_t func ); TaskState task_pause ( task_func_t func ); TaskState task_resume ( task_func_t func ); uint32_t* task_size ( task_func_t func ); uint32_t* main_size ( loop_func_t func ); #ifdef __cplusplus } #endif Zilch::Zilch( uint16_t main_stack_size, const uint32_t pattern ) { NVIC_SET_PRIORITY(IRQ_SOFTWARE, 0xFF); // 0xFF = lowest priority NVIC_ENABLE_IRQ(IRQ_SOFTWARE); init_stack( main_stack_size, pattern ); pinMode(LED_BUILTIN, OUTPUT); } TaskState Zilch::create( task_func_t task, size_t stack_size, volatile void *arg ) { int s_size = stack_size; // Round stack size to a word multiple s_size = ( stack_size + sizeof (uint32_t) ) / sizeof (uint32_t) * sizeof (uint32_t); task_create( task, s_size, arg ); } TaskState Zilch::state( task_func_t task ) { TaskState p = task_state( task ); return p; } TaskState Zilch::resume( task_func_t task ) { TaskState p = task_resume( task ); return p; } TaskState Zilch::pause( task_func_t task ) { TaskState p = task_pause( task ); return p; } TaskState Zilch::state( loop_func_t task ) { TaskState p = main_state( task ); return p; } TaskState Zilch::sync( task_func_t task) { TaskState p = task_sync( task ); return p; } TaskState Zilch::restart( task_func_t task ) { TaskState p = task_restart( task ); return p; } uint32_t *Zilch::size( task_func_t task ) { return task_size(task); } uint32_t *Zilch::size( loop_func_t task ) { uint32_t* tmp = main_size(task); return tmp; } <commit_msg>update<commit_after>/* || || @file zilch.cpp || @version 0.2 || @author Colin Duffy || @contact cmduffy@engr.psu.edu || @author Warren Gay || @contact ve3wwg@gmail.com || || @description || Light weight task scheduler library, based off the awesome fibers || library by Warren Gay. https://github.com/ve3wwg/teensy3_fibers || || @license || | Copyright (c) 2014 Colin Duffy, (C) Warren Gay VE3WWG || | 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; version || | 2.1 of the License. || | || | This library is distributed in the hope that it will be useful, || | but WITHOUT ANY WARRANTY; without even the implied warranty of || | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU || | Lesser General Public License for more details. || | || | You should have received a copy of the GNU Lesser General Public || | License along with this library; if not, write to the Free Software || | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA || # || */ #include "zilch.h" #include "Arduino.h" #ifdef __cplusplus extern "C" { #endif void init_stack ( uint32_t main_stack, uint32_t pattern_override ); void task_create ( task_func_t func, uint32_t stack_size, volatile void *arg ); TaskState task_state ( task_func_t func ); TaskState main_state ( loop_func_t func ); TaskState task_sync ( task_func_t func ); TaskState task_restart ( task_func_t func ); TaskState task_pause ( task_func_t func ); TaskState task_resume ( task_func_t func ); uint32_t* task_size ( task_func_t func ); uint32_t* main_size ( loop_func_t func ); #ifdef __cplusplus } #endif Zilch::Zilch( uint16_t main_stack_size, const uint32_t pattern ) { NVIC_SET_PRIORITY(IRQ_SOFTWARE, 0xFF); // 0xFF = lowest priority NVIC_ENABLE_IRQ(IRQ_SOFTWARE); init_stack( main_stack_size, pattern ); } TaskState Zilch::create( task_func_t task, size_t stack_size, volatile void *arg ) { int s_size = stack_size; // Round stack size to a word multiple s_size = ( stack_size + sizeof (uint32_t) ) / sizeof (uint32_t) * sizeof (uint32_t); task_create( task, s_size, arg ); } TaskState Zilch::state( task_func_t task ) { TaskState p = task_state( task ); return p; } TaskState Zilch::resume( task_func_t task ) { TaskState p = task_resume( task ); return p; } TaskState Zilch::pause( task_func_t task ) { TaskState p = task_pause( task ); return p; } TaskState Zilch::state( loop_func_t task ) { TaskState p = main_state( task ); return p; } TaskState Zilch::sync( task_func_t task) { TaskState p = task_sync( task ); return p; } TaskState Zilch::restart( task_func_t task ) { TaskState p = task_restart( task ); return p; } uint32_t *Zilch::size( task_func_t task ) { return task_size(task); } uint32_t *Zilch::size( loop_func_t task ) { uint32_t* tmp = main_size(task); return tmp; } <|endoftext|>
<commit_before>#include "Game.h" float Game::BLOCK_SIDE_LENGTH = 0.09f; Vec2f Game::BLOCK_SIZE = { BLOCK_SIDE_LENGTH, BLOCK_SIDE_LENGTH }; Vec2f Game::FIELD_BOT_LEFT = { -0.55f, -0.45f }; Vec2i Game::FIELD_SIZE = { 10 + SENTINELS_COUNT, 20 + SENTINELS_COUNT }; Game::Game() //:mExists{} { for (size_t i = 0; i < FIELD_HEIGHT; i++) { for (size_t j = 0; j < FIELD_WIDTH; j++) { if (j >= FIELD_WIDTH - SENTINELS_COUNT * 2 || j < SENTINELS_COUNT || i < SENTINELS_COUNT) { mExists[i][j] = true; } else { mExists[i][j] = false; } } } } Game::~Game() { } void Game::Process() { ++mDropCount; if (mDropCount % DROP_INTERVAL == 0) { mToBeDropped = true; } } bool Game::IsMovable(const Mino & mino, int horizontal, int vertical) { return !mExists[mino.mPosition.y + vertical][mino.mPosition.x + horizontal]; } bool Game::IsMovable(const TetriMino & mino, int horizontal, int vertical) { for (size_t i = 0; i < TetriMino::MINO_MAX; i++) { if (mExists[mino.mMinos[i]->mPosition.y + vertical][mino.mMinos[i]->mPosition.x + horizontal]) { return false; } } return true; } void Game::PlaceCurrent(const Mino& mino) { mExists[mino.mPosition.y][mino.mPosition.x] = true; } void Game::PlaceCurrent(const TetriMino & mino) { for (size_t i = 0; i < TetriMino::MINO_MAX; i++) { mExists[mino.mMinos[i]->mPosition.y][mino.mMinos[i]->mPosition.x] = true; } } void Game::DropLines() { int targetLine = SENTINELS_COUNT; for (size_t i = SENTINELS_COUNT; i < FIELD_HEIGHT; i++) { MoveLine(i, targetLine); if (!IsLineFilled(i)) { ++targetLine; } } } bool Game::IsLineFilled(int y) { for (size_t i = SENTINELS_COUNT; i < FIELD_WIDTH - SENTINELS_COUNT; i++) { if (!mExists[y][i]) { return false; } } return true; } void Game::MoveLine(int from, int to) { for (size_t i = SENTINELS_COUNT; i < FIELD_WIDTH - SENTINELS_COUNT; i++) { mExists[to][i] = mExists[from][i]; } } <commit_msg>フィールドを調整<commit_after>#include "Game.h" float Game::BLOCK_SIDE_LENGTH = 0.09f; Vec2f Game::BLOCK_SIZE = { BLOCK_SIDE_LENGTH, BLOCK_SIDE_LENGTH }; Vec2f Game::FIELD_BOT_LEFT = { -0.55f, -0.50f }; Vec2i Game::FIELD_SIZE = { FIELD_WIDTH, FIELD_HEIGHT }; Game::Game() //:mExists{} { for (size_t i = 0; i < FIELD_HEIGHT; i++) { for (size_t j = 0; j < FIELD_WIDTH; j++) { if (j >= FIELD_WIDTH - SENTINELS_COUNT || j < SENTINELS_COUNT || i < SENTINELS_COUNT) { mExists[i][j] = true; } else { mExists[i][j] = false; } } } } Game::~Game() { } void Game::Process() { ++mDropCount; if (mDropCount % DROP_INTERVAL == 0) { mToBeDropped = true; } } bool Game::IsMovable(const Mino & mino, int horizontal, int vertical) { return !mExists[mino.mPosition.y + vertical][mino.mPosition.x + horizontal]; } bool Game::IsMovable(const TetriMino & mino, int horizontal, int vertical) { for (size_t i = 0; i < TetriMino::MINO_MAX; i++) { if (mExists[mino.mMinos[i]->mPosition.y + vertical][mino.mMinos[i]->mPosition.x + horizontal]) { return false; } } return true; } void Game::PlaceCurrent(const Mino& mino) { mExists[mino.mPosition.y][mino.mPosition.x] = true; } void Game::PlaceCurrent(const TetriMino & mino) { for (size_t i = 0; i < TetriMino::MINO_MAX; i++) { mExists[mino.mMinos[i]->mPosition.y][mino.mMinos[i]->mPosition.x] = true; } } void Game::DropLines() { int targetLine = SENTINELS_COUNT; for (size_t i = SENTINELS_COUNT; i < FIELD_HEIGHT; i++) { MoveLine(i, targetLine); if (!IsLineFilled(i)) { ++targetLine; } } } bool Game::IsLineFilled(int y) { for (size_t i = SENTINELS_COUNT; i < FIELD_WIDTH - SENTINELS_COUNT; i++) { if (!mExists[y][i]) { return false; } } return true; } void Game::MoveLine(int from, int to) { for (size_t i = SENTINELS_COUNT; i < FIELD_WIDTH - SENTINELS_COUNT; i++) { mExists[to][i] = mExists[from][i]; } } <|endoftext|>
<commit_before>#include <iostream> #include <string.h> #include <math.h> #include "Problem.h" int puzzle[TILE_CNT] = {8, 7, 6, 5, 4, 3, 2, 1, 0}; int puzzle_dimension = (int)sqrt((int)TILE_CNT); bool isInteger(char *num) { if(num[0] == '-') { if(num[1] == '\0') { return false; } for(int i = 1; num[i] != '\0'; i++) { if(!isdigit(num[i])) { return false; } } return true; } else { for(int i = 0; num[i] != '\0'; i++) { if(!isdigit(num[i])) { return false; } } return true; } } void customPuzzleMaker() { std::string input; printf("Enter your puzzle, use a zero to represent the blank\n"); int i = 0; bool valid_num; while(i < puzzle_dimension) { printf("Enter %d numbers for row %d, use space or tabs between numbers:\t", puzzle_dimension, i+1); std::getline(std::cin, input); char *input_numbers = new char[input.length()+1]; std::strcpy(input_numbers, input.c_str()); char *number = std::strtok(input_numbers, " \t"); //Check to see if enough numbers were entered and if the correct numbers were entered valid_num = true; int num_cnt = 0; while(number != 0) { //If not a number, error if(!isInteger(number)) { valid_num = false; printf("ERROR: Number %s is not a number\n", number); } //If a negative number, error else if(number[0] == '-') { valid_num = false; printf("ERROR: Number %s is negative\n", number); } //If too big a number, error else if((int)strtol(number, NULL, 10) > TILE_CNT-1) { valid_num = false; printf("ERROR: Number %s is too big\n", number); } number = std::strtok(NULL, " \t"); num_cnt++; } if(!valid_num) { printf(" Valid inputs are whole numbers from 0 - %d\n", TILE_CNT-1); delete[] input_numbers; continue; } //Check for correct number of numbers if(num_cnt != puzzle_dimension) { printf("ERROR: %d number(s) were entered for row %d\n", num_cnt, i+1); delete[] input_numbers; continue; } //Errors: duplicate numbers in the array delete[] input_numbers; i++; } } int main(int argc, char **argv) { printf("Welcome to %s's %d-puzzle solver.\n", "amacp001", TILE_CNT-1); printf("Type \"1\" to use a default puzzle, or \"2\" to enter your own puzzle\n"); std::string choice; std::cin >> choice; std::cin.clear(); std::cin.ignore(100, '\n'); for(; choice != "1" && choice != "2"; std::cin >> choice) { printf("Invalid Response!\n"); printf("Type \"1\" to use a default puzzle, or \"2\" to enter your own puzzle\n"); } if(choice == "2") { customPuzzleMaker(); } return 0; } <commit_msg>Completed the custom puzzle maker<commit_after>#include <iostream> #include <string.h> #include <math.h> #include "Problem.h" int puzzle[TILE_CNT] = {}; int valid_numbers[TILE_CNT] = {}; int puzzle_dimension = (int)sqrt((int)TILE_CNT); bool isInteger(char *num) { if(num[0] == '-') { if(num[1] == '\0') { return false; } for(int i = 1; num[i] != '\0'; i++) { if(!isdigit(num[i])) { return false; } } return true; } else { for(int i = 0; num[i] != '\0'; i++) { if(!isdigit(num[i])) { return false; } } return true; } } void customPuzzleMaker() { std::string input; printf("Enter your puzzle, use a zero to represent the blank\n"); bool valid_num; bool duplicate_num; int row; do { row = 0; while(row < puzzle_dimension) { printf("Enter %d numbers for row %d, use space or tabs between numbers:\t", puzzle_dimension, row+1); std::getline(std::cin, input); char *input_chars= new char[input.length()+1]; std::strcpy(input_chars, input.c_str()); char *number = std::strtok(input_chars, " \t"); int *row_vals = new int[puzzle_dimension]; //Check to see if enough numbers were entered and if the correct numbers were entered valid_num = true; duplicate_num = false; int num_cnt = 0; for(;number != 0; num_cnt++, number = std::strtok(NULL, " \t")) { int num_val = 0; //If not a number, error if(!isInteger(number)) { valid_num = false; printf("ERROR: Number %s is not a number\n", number); } //If a negative number, error else if(number[0] == '-') { valid_num = false; printf("ERROR: Number %s is negative\n", number); } //If too big a number, error else if((num_val = (int)strtol(number, NULL, 10)) > TILE_CNT-1) { valid_num = false; printf("ERROR: Number %s is too big\n", number); } //Add number to row_vals else { if(num_cnt < puzzle_dimension) { row_vals[num_cnt] = num_val; } } } if(!valid_num) { printf(" Valid inputs are whole numbers from 0 - %d\n", TILE_CNT-1); delete[] input_chars; delete[] row_vals; continue; } //Check for correct number of numbers if(num_cnt != puzzle_dimension) { printf("ERROR: %d number(s) were entered for row %d\n", num_cnt, row+1); delete[] input_chars; delete[] row_vals; continue; } //add input to puzzle for(int col = 0; col < puzzle_dimension; col++) { puzzle[(puzzle_dimension*row)+col] = row_vals[col]; } delete[] input_chars; delete[] row_vals; row++; } //Check for duplicate numbers printf("The puzzle you entered is\n"); for(int i = 0; i < puzzle_dimension; i++) { for(int j = 0; j < puzzle_dimension; j++) { printf("%d ", puzzle[(puzzle_dimension*i)+j]); if(valid_numbers[puzzle[(puzzle_dimension*i)+j]] < 0) { duplicate_num = true; } else { valid_numbers[puzzle[(puzzle_dimension*i)+j]] = -1; } } printf("\n"); } if(duplicate_num) { printf("ERROR: You have entered duplicate numbers into your puzzle\n"); printf(" Please enter a new puzzle with no duplicate numbers\n"); //Reinitialize the valid_numbers for(int i = 0; i < TILE_CNT; i++) { valid_numbers[i] = i; } } }while(duplicate_num); } int main(int argc, char **argv) { //initialize default puzzle and valid_numbers for(int i = 0; i < TILE_CNT; i++) { puzzle[i] = TILE_CNT-i-1; valid_numbers[i] = i; } printf("Welcome to %s's %d-puzzle solver.\n", "amacp001", TILE_CNT-1); printf("Type \"1\" to use a default puzzle, or \"2\" to enter your own puzzle\n"); std::string choice; std::cin >> choice; std::cin.clear(); std::cin.ignore(100, '\n'); for(; choice != "1" && choice != "2"; std::cin >> choice) { printf("Invalid Response!\n"); printf("Type \"1\" to use a default puzzle, or \"2\" to enter your own puzzle\n"); } if(choice == "2") { customPuzzleMaker(); } return 0; } <|endoftext|>
<commit_before>#include "Buffer.h" namespace gui { Buffer::Buffer(GLsizei width, GLsizei height, GLint format, GLenum type) : _format(format), _type(type), _width(width), _height(height), _buf(0), _mapped(0) { // create a pixel buffer object for the buffer glCheck(glGenBuffersARB(1, &_buf)); // resize buffer resize(_width, _height); } Buffer::~Buffer() { // delete buffer glCheck(glDeleteBuffersARB(1, &_buf)); } void Buffer::resize(GLsizei width, GLsizei height) { _width = width; _height = height; // bind buffer glCheck(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, _buf)); // create new buffer unsigned int size = _width*_height; if (_format == GL_RGB) size *= 3; else if (_format == GL_RGBA || _format == GL_BGRA) size *= 4; glCheck(glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, size, 0, GL_DYNAMIC_DRAW)); // unbind buffer glCheck(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0)); } void Buffer::bind() const { // bind buffer glCheck(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, _buf)); } void Buffer::unbind() const { // unbind buffer glCheck(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0)); } void Buffer::unmap() { if (_mapped) { _mapped = 0; // unmap the pixel buffer object glCheck(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB)); } // unbind buffer glCheck(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0)); } } // namespace gui <commit_msg>throw exception in Buffer when glGenBuffers doesn't succeed<commit_after>#include "Buffer.h" namespace gui { Buffer::Buffer(GLsizei width, GLsizei height, GLint format, GLenum type) : _format(format), _type(type), _width(width), _height(height), _buf(0), _mapped(0) { // create a pixel buffer object for the buffer glCheck(glGenBuffersARB(1, &_buf)); if (_buf == 0) BOOST_THROW_EXCEPTION(GuiError() << error_message("buffer id is zero") << STACK_TRACE); // resize buffer resize(_width, _height); } Buffer::~Buffer() { // delete buffer glCheck(glDeleteBuffersARB(1, &_buf)); } void Buffer::resize(GLsizei width, GLsizei height) { _width = width; _height = height; // bind buffer glCheck(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, _buf)); // create new buffer unsigned int size = _width*_height; if (_format == GL_RGB) size *= 3; else if (_format == GL_RGBA || _format == GL_BGRA) size *= 4; glCheck(glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, size, 0, GL_DYNAMIC_DRAW)); // unbind buffer glCheck(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0)); } void Buffer::bind() const { // bind buffer glCheck(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, _buf)); } void Buffer::unbind() const { // unbind buffer glCheck(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0)); } void Buffer::unmap() { if (_mapped) { _mapped = 0; // unmap the pixel buffer object glCheck(glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB)); } // unbind buffer glCheck(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0)); } } // namespace gui <|endoftext|>
<commit_before>/* Copyright (C) 2003-2006 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __WIN__ #include "angel.h" #include <sys/wait.h> /* sys/wait.h is needed for waitpid(). Unfortunately, there is no MySQL include file, that can serve for this. Include it before MySQL system headers so that we can change system defines if needed. */ #include "my_global.h" #include "my_alarm.h" #include "my_dir.h" #include "my_sys.h" /* Include other IM files. */ #include "log.h" #include "manager.h" #include "options.h" #include "priv.h" /************************************************************************/ enum { CHILD_OK= 0, CHILD_NEED_RESPAWN, CHILD_EXIT_ANGEL }; static int log_fd; static volatile sig_atomic_t child_status= CHILD_OK; static volatile sig_atomic_t child_exit_code= 0; static volatile sig_atomic_t shutdown_request_signo= 0; /************************************************************************/ /** Open log file. @return TRUE on error; FALSE on success. *************************************************************************/ static bool open_log_file() { log_info("Angel: opening log file '%s'...", (const char *) Options::Daemon::log_file_name); log_fd= open(Options::Daemon::log_file_name, O_WRONLY | O_CREAT | O_APPEND | O_NOCTTY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); if (log_fd < 0) { log_error("Can not open log file '%s': %s.", (const char *) Options::Daemon::log_file_name, (const char *) strerror(errno)); return TRUE; } return FALSE; } /************************************************************************/ /** Detach the process from controlling tty. @return TRUE on error; FALSE on success. *************************************************************************/ static bool detach_process() { /* Become a session leader (the goal is not to have a controlling tty). setsid() must succeed because child is guaranteed not to be a process group leader (it belongs to the process group of the parent). NOTE: if we now don't have a controlling tty we will not receive tty-related signals - no need to ignore them. */ if (setsid() < 0) { log_error("setsid() failed: %s.", (const char *) strerror(errno)); return -1; } /* Close STDIN. */ log_info("Angel: preparing standard streams."); if (close(STDIN_FILENO) < 0) { log_error("Warning: can not close stdin (%s)." "Trying to continue...", (const char *) strerror(errno)); } /* Dup STDOUT and STDERR to the log file. */ if (dup2(log_fd, STDOUT_FILENO) < 0 || dup2(log_fd, STDERR_FILENO) < 0) { log_error("Can not redirect stdout and stderr to the log file: %s.", (const char *) strerror(errno)); return TRUE; } if (log_fd != STDOUT_FILENO && log_fd != STDERR_FILENO) { if (close(log_fd) < 0) { log_error("Can not close original log file handler (%d): %s. " "Trying to continue...", (int) log_fd, (const char *) strerror(errno)); } } return FALSE; } /************************************************************************/ /** Create PID file. @return TRUE on error; FALSE on success. *************************************************************************/ static bool create_pid_file() { if (create_pid_file(Options::Daemon::angel_pid_file_name, getpid())) { log_error("Angel: can not create pid file (%s).", (const char *) Options::Daemon::angel_pid_file_name); return TRUE; } log_info("Angel: pid file (%s) created.", (const char *) Options::Daemon::angel_pid_file_name); return FALSE; } /************************************************************************/ /** SIGCHLD handler. Reap child, analyze child exit code, and set child_status appropriately. *************************************************************************/ void reap_child(int __attribute__((unused)) signo) { /* NOTE: As we have only one child, no need to cycle waitpid(). */ int exit_code; if (waitpid(0, &exit_code, WNOHANG) > 0) { child_exit_code= exit_code; child_status= exit_code ? CHILD_NEED_RESPAWN : CHILD_EXIT_ANGEL; } } /************************************************************************/ /** SIGTERM, SIGHUP, SIGINT handler. Set termination status and return. *************************************************************************/ void terminate(int signo) { shutdown_request_signo= signo; } /************************************************************************/ /** Angel main loop. @return The function returns exit status for global main(): 0 -- program completed successfully; !0 -- error occurred. *************************************************************************/ static int angel_main_loop() { /* Install signal handlers. NOTE: Although signal handlers are needed only for parent process (IM-angel), we should install them before fork() in order to avoid race condition (i.e. to be sure, that IM-angel will receive SIGCHLD in any case). */ sigset_t wait_for_signals_mask; struct sigaction sa_chld; struct sigaction sa_term; struct sigaction sa_chld_orig; struct sigaction sa_term_orig; struct sigaction sa_int_orig; struct sigaction sa_hup_orig; log_info("Angel: setting necessary signal actions..."); sigemptyset(&wait_for_signals_mask); sigemptyset(&sa_chld.sa_mask); sa_chld.sa_handler= reap_child; sa_chld.sa_flags= SA_NOCLDSTOP; sigemptyset(&sa_term.sa_mask); sa_term.sa_handler= terminate; sa_term.sa_flags= 0; /* NOTE: sigaction() fails only if arguments are wrong. */ DBUG_ASSERT(!sigaction(SIGCHLD, &sa_chld, &sa_chld_orig)); DBUG_ASSERT(!sigaction(SIGTERM, &sa_term, &sa_term_orig)); DBUG_ASSERT(!sigaction(SIGINT, &sa_term, &sa_int_orig)); DBUG_ASSERT(!sigaction(SIGHUP, &sa_term, &sa_hup_orig)); /* The main Angel loop. */ while (true) { /* Spawn a new Manager. */ log_info("Angel: forking Manager process..."); switch (fork()) { case -1: log_error("Angel: can not fork IM-main: %s.", (const char *) strerror(errno)); return -1; case 0: /* We are in child process, which will be IM-main: - Restore default signal actions to let the IM-main work with signals as he wishes; - Call Manager::main(); */ log_info("Angel: Manager process created successfully."); /* NOTE: sigaction() fails only if arguments are wrong. */ DBUG_ASSERT(!sigaction(SIGCHLD, &sa_chld_orig, NULL)); DBUG_ASSERT(!sigaction(SIGTERM, &sa_term_orig, NULL)); DBUG_ASSERT(!sigaction(SIGINT, &sa_int_orig, NULL)); DBUG_ASSERT(!sigaction(SIGHUP, &sa_hup_orig, NULL)); log_info("Angel: executing Manager..."); return Manager::main(); } /* Wait for signals. */ log_info("Angel: waiting for signals..."); while (child_status == CHILD_OK && shutdown_request_signo == 0) sigsuspend(&wait_for_signals_mask); /* Exit if one of shutdown signals has been caught. */ if (shutdown_request_signo) { log_info("Angel: received shutdown signal (%d). Exiting...", (int) shutdown_request_signo); return 0; } /* Manager process died. Respawn it if it was a failure. */ if (child_status == CHILD_NEED_RESPAWN) { child_status= CHILD_OK; log_error("Angel: Manager exited abnormally (exit code: %d).", (int) child_exit_code); log_info("Angel: sleeping 1 second..."); sleep(1); /* don't respawn too fast */ log_info("Angel: respawning Manager..."); continue; } log_info("Angel: Manager exited normally. Exiting..."); return 0; } } /************************************************************************/ /** Angel main function. @return The function returns exit status for global main(): 0 -- program completed successfully; !0 -- error occurred. *************************************************************************/ int Angel::main() { int ret_status; log_info("Angel: started."); /* Open log file. */ if (open_log_file()) return -1; /* Fork a new process. */ log_info("Angel: daemonizing..."); switch (fork()) { case -1: /* This is the main Instance Manager process, fork() failed. Log an error and bail out with error code. */ log_error("fork() failed: %s.", (const char *) strerror(errno)); return -1; case 0: /* We are in child process. Continue Angel::main() execution. */ break; default: /* We are in the parent process. Return 0 so that parent exits successfully. */ log_info("Angel: exiting from the original process..."); return 0; } /* Detach child from controlling tty. */ if (detach_process()) return -1; /* Create PID file. */ if (create_pid_file()) return -1; /* Start Angel main loop. */ return angel_main_loop(); } #endif // __WIN__ <commit_msg>Fix merge.<commit_after>/* Copyright (C) 2003-2006 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __WIN__ #include "angel.h" #include <sys/wait.h> /* sys/wait.h is needed for waitpid(). Unfortunately, there is no MySQL include file, that can serve for this. Include it before MySQL system headers so that we can change system defines if needed. */ #include "my_global.h" #include "my_alarm.h" #include "my_dir.h" #include "my_sys.h" /* Include other IM files. */ #include "log.h" #include "manager.h" #include "options.h" #include "priv.h" /************************************************************************/ enum { CHILD_OK= 0, CHILD_NEED_RESPAWN, CHILD_EXIT_ANGEL }; static int log_fd; static volatile sig_atomic_t child_status= CHILD_OK; static volatile sig_atomic_t child_exit_code= 0; static volatile sig_atomic_t shutdown_request_signo= 0; /************************************************************************/ /** Open log file. @return TRUE on error; FALSE on success. *************************************************************************/ static bool open_log_file() { log_info("Angel: opening log file '%s'...", (const char *) Options::Daemon::log_file_name); log_fd= open(Options::Daemon::log_file_name, O_WRONLY | O_CREAT | O_APPEND | O_NOCTTY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); if (log_fd < 0) { log_error("Can not open log file '%s': %s.", (const char *) Options::Daemon::log_file_name, (const char *) strerror(errno)); return TRUE; } return FALSE; } /************************************************************************/ /** Detach the process from controlling tty. @return TRUE on error; FALSE on success. *************************************************************************/ static bool detach_process() { /* Become a session leader (the goal is not to have a controlling tty). setsid() must succeed because child is guaranteed not to be a process group leader (it belongs to the process group of the parent). NOTE: if we now don't have a controlling tty we will not receive tty-related signals - no need to ignore them. */ if (setsid() < 0) { log_error("setsid() failed: %s.", (const char *) strerror(errno)); return -1; } /* Close STDIN. */ log_info("Angel: preparing standard streams."); if (close(STDIN_FILENO) < 0) { log_error("Warning: can not close stdin (%s)." "Trying to continue...", (const char *) strerror(errno)); } /* Dup STDOUT and STDERR to the log file. */ if (dup2(log_fd, STDOUT_FILENO) < 0 || dup2(log_fd, STDERR_FILENO) < 0) { log_error("Can not redirect stdout and stderr to the log file: %s.", (const char *) strerror(errno)); return TRUE; } if (log_fd != STDOUT_FILENO && log_fd != STDERR_FILENO) { if (close(log_fd) < 0) { log_error("Can not close original log file handler (%d): %s. " "Trying to continue...", (int) log_fd, (const char *) strerror(errno)); } } return FALSE; } /************************************************************************/ /** Create PID file. @return TRUE on error; FALSE on success. *************************************************************************/ static bool create_pid_file() { if (create_pid_file(Options::Daemon::angel_pid_file_name, getpid())) { log_error("Angel: can not create pid file (%s).", (const char *) Options::Daemon::angel_pid_file_name); return TRUE; } log_info("Angel: pid file (%s) created.", (const char *) Options::Daemon::angel_pid_file_name); return FALSE; } /************************************************************************/ /** SIGCHLD handler. Reap child, analyze child exit code, and set child_status appropriately. *************************************************************************/ void reap_child(int __attribute__((unused)) signo) { /* NOTE: As we have only one child, no need to cycle waitpid(). */ int exit_code; if (waitpid(0, &exit_code, WNOHANG) > 0) { child_exit_code= exit_code; child_status= exit_code ? CHILD_NEED_RESPAWN : CHILD_EXIT_ANGEL; } } /************************************************************************/ /** SIGTERM, SIGHUP, SIGINT handler. Set termination status and return. *************************************************************************/ void terminate(int signo) { shutdown_request_signo= signo; } /************************************************************************/ /** Angel main loop. @return The function returns exit status for global main(): 0 -- program completed successfully; !0 -- error occurred. *************************************************************************/ static int angel_main_loop() { /* Install signal handlers. NOTE: Although signal handlers are needed only for parent process (IM-angel), we should install them before fork() in order to avoid race condition (i.e. to be sure, that IM-angel will receive SIGCHLD in any case). */ sigset_t wait_for_signals_mask; struct sigaction sa_chld; struct sigaction sa_term; struct sigaction sa_chld_orig; struct sigaction sa_term_orig; struct sigaction sa_int_orig; struct sigaction sa_hup_orig; log_info("Angel: setting necessary signal actions..."); sigemptyset(&wait_for_signals_mask); sigemptyset(&sa_chld.sa_mask); sa_chld.sa_handler= reap_child; sa_chld.sa_flags= SA_NOCLDSTOP; sigemptyset(&sa_term.sa_mask); sa_term.sa_handler= terminate; sa_term.sa_flags= 0; /* NOTE: sigaction() fails only if arguments are wrong. */ DBUG_ASSERT(!sigaction(SIGCHLD, &sa_chld, &sa_chld_orig)); DBUG_ASSERT(!sigaction(SIGTERM, &sa_term, &sa_term_orig)); DBUG_ASSERT(!sigaction(SIGINT, &sa_term, &sa_int_orig)); DBUG_ASSERT(!sigaction(SIGHUP, &sa_term, &sa_hup_orig)); /* The main Angel loop. */ while (true) { /* Spawn a new Manager. */ log_info("Angel: forking Manager process..."); switch (fork()) { case -1: log_error("Angel: can not fork IM-main: %s.", (const char *) strerror(errno)); return -1; case 0: /* We are in child process, which will be IM-main: - Restore default signal actions to let the IM-main work with signals as he wishes; - Call Manager::main(); */ log_info("Angel: Manager process created successfully."); /* NOTE: sigaction() fails only if arguments are wrong. */ DBUG_ASSERT(!sigaction(SIGCHLD, &sa_chld_orig, NULL)); DBUG_ASSERT(!sigaction(SIGTERM, &sa_term_orig, NULL)); DBUG_ASSERT(!sigaction(SIGINT, &sa_int_orig, NULL)); DBUG_ASSERT(!sigaction(SIGHUP, &sa_hup_orig, NULL)); log_info("Angel: executing Manager..."); return Manager::main(); } /* Wait for signals. */ log_info("Angel: waiting for signals..."); while (child_status == CHILD_OK && shutdown_request_signo == 0) sigsuspend(&wait_for_signals_mask); /* Exit if one of shutdown signals has been caught. */ if (shutdown_request_signo) { log_info("Angel: received shutdown signal (%d). Exiting...", (int) shutdown_request_signo); return 0; } /* Manager process died. Respawn it if it was a failure. */ if (child_status == CHILD_NEED_RESPAWN) { child_status= CHILD_OK; log_error("Angel: Manager exited abnormally (exit code: %d).", (int) child_exit_code); log_info("Angel: sleeping 1 second..."); sleep(1); /* don't respawn too fast */ log_info("Angel: respawning Manager..."); continue; } /* Delete IM-angel PID file. */ my_delete(Options::Daemon::angel_pid_file_name, MYF(0)); /* IM-angel finished. */ log_info("Angel: Manager exited normally. Exiting..."); return 0; } } /************************************************************************/ /** Angel main function. @return The function returns exit status for global main(): 0 -- program completed successfully; !0 -- error occurred. *************************************************************************/ int Angel::main() { int ret_status; log_info("Angel: started."); /* Open log file. */ if (open_log_file()) return -1; /* Fork a new process. */ log_info("Angel: daemonizing..."); switch (fork()) { case -1: /* This is the main Instance Manager process, fork() failed. Log an error and bail out with error code. */ log_error("fork() failed: %s.", (const char *) strerror(errno)); return -1; case 0: /* We are in child process. Continue Angel::main() execution. */ break; default: /* We are in the parent process. Return 0 so that parent exits successfully. */ log_info("Angel: exiting from the original process..."); return 0; } /* Detach child from controlling tty. */ if (detach_process()) return -1; /* Create PID file. */ if (create_pid_file()) return -1; /* Start Angel main loop. */ return angel_main_loop(); } #endif // __WIN__ <|endoftext|>
<commit_before>//===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===// // // This file implements the TDDataStructures class, which represents the // Top-down Interprocedural closure of the data structure graph over the // program. This is useful (but not strictly necessary?) for applications // like pointer analysis. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/DataStructure.h" #include "llvm/Module.h" #include "llvm/DerivedTypes.h" #include "Support/Statistic.h" #include "DSCallSiteIterator.h" namespace { RegisterAnalysis<TDDataStructures> // Register the pass Y("tddatastructure", "Top-down Data Structure Analysis"); } // run - Calculate the top down data structure graphs for each function in the // program. // bool TDDataStructures::run(Module &M) { BUDataStructures &BU = getAnalysis<BUDataStructures>(); GlobalsGraph = new DSGraph(BU.getGlobalsGraph()); // Calculate top-down from main... if (Function *F = M.getMainFunction()) calculateGraphFrom(*F); // Next calculate the graphs for each function unreachable function... for (Module::reverse_iterator I = M.rbegin(), E = M.rend(); I != E; ++I) if (!I->isExternal() && !DSInfo.count(&*I)) calculateGraphFrom(*I); return false; } // releaseMemory - If the pass pipeline is done with this pass, we can release // our memory... here... // // FIXME: This should be releaseMemory and will work fine, except that LoadVN // has no way to extend the lifetime of the pass, which screws up ds-aa. // void TDDataStructures::releaseMyMemory() { for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(), E = DSInfo.end(); I != E; ++I) { I->second->getReturnNodes().erase(I->first); if (I->second->getReturnNodes().empty()) delete I->second; } // Empty map so next time memory is released, data structures are not // re-deleted. DSInfo.clear(); delete GlobalsGraph; GlobalsGraph = 0; } DSGraph &TDDataStructures::getOrCreateDSGraph(Function &F) { DSGraph *&G = DSInfo[&F]; if (G == 0) { // Not created yet? Clone BU graph... G = new DSGraph(getAnalysis<BUDataStructures>().getDSGraph(F)); G->getAuxFunctionCalls().clear(); G->setPrintAuxCalls(); G->setGlobalsGraph(GlobalsGraph); } return *G; } /// FunctionHasCompleteArguments - This function returns true if it is safe not /// to mark arguments to the function complete. /// /// FIXME: Need to check if all callers have been found, or rather if a /// funcpointer escapes! /// static bool FunctionHasCompleteArguments(Function &F) { return F.hasInternalLinkage(); } void TDDataStructures::ComputePostOrder(Function &F,hash_set<DSGraph*> &Visited, std::vector<DSGraph*> &PostOrder, const BUDataStructures::ActualCalleesTy &ActualCallees) { if (F.isExternal()) return; DSGraph &G = getOrCreateDSGraph(F); if (Visited.count(&G)) return; Visited.insert(&G); // Recursively traverse all of the callee graphs. const std::vector<DSCallSite> &FunctionCalls = G.getFunctionCalls(); for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) { std::pair<BUDataStructures::ActualCalleesTy::const_iterator, BUDataStructures::ActualCalleesTy::const_iterator> IP = ActualCallees.equal_range(&FunctionCalls[i].getCallInst()); for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first; I != IP.second; ++I) ComputePostOrder(*I->second, Visited, PostOrder, ActualCallees); } PostOrder.push_back(&G); } void TDDataStructures::calculateGraphFrom(Function &F) { // We want to traverse the call graph in reverse post-order. To do this, we // calculate a post-order traversal, then reverse it. hash_set<DSGraph*> VisitedGraph; std::vector<DSGraph*> PostOrder; ComputePostOrder(F, VisitedGraph, PostOrder, getAnalysis<BUDataStructures>().getActualCallees()); VisitedGraph.clear(); // Release memory! // Visit each of the graphs in reverse post-order now! while (!PostOrder.empty()) { inlineGraphIntoCallees(*PostOrder.back()); PostOrder.pop_back(); } } void TDDataStructures::inlineGraphIntoCallees(DSGraph &Graph) { // Recompute the Incomplete markers and eliminate unreachable nodes. Graph.maskIncompleteMarkers(); unsigned Flags = true /* FIXME!! FunctionHasCompleteArguments(F)*/ ? DSGraph::IgnoreFormalArgs : DSGraph::MarkFormalArgs; Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals); Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals); DSCallSiteIterator CalleeI = DSCallSiteIterator::begin_std(Graph); DSCallSiteIterator CalleeE = DSCallSiteIterator::end_std(Graph); if (CalleeI == CalleeE) { DEBUG(std::cerr << " [TD] No callees for: " << Graph.getFunctionNames() << "\n"); return; } // Loop over all of the call sites, building a multi-map from Callees to // DSCallSite*'s. With this map we can then loop over each callee, cloning // this graph once into it, then resolving arguments. // std::multimap<std::pair<DSGraph*,Function*>, const DSCallSite*> CalleeSites; for (; CalleeI != CalleeE; ++CalleeI) if (!(*CalleeI)->isExternal()) { // We should have already created the graph here... if (!DSInfo.count(*CalleeI)) std::cerr << "WARNING: TD pass, did not know about callee: '" << (*CalleeI)->getName() << "'\n"; DSGraph &IG = getOrCreateDSGraph(**CalleeI); if (&IG != &Graph) CalleeSites.insert(std::make_pair(std::make_pair(&IG, *CalleeI), &CalleeI.getCallSite())); } // Now that we have information about all of the callees, propagate the // current graph into the callees. // DEBUG(std::cerr << " [TD] Inlining '" << Graph.getFunctionNames() <<"' into " << CalleeSites.size() << " callees.\n"); // Loop over all the callees... for (std::multimap<std::pair<DSGraph*, Function*>, const DSCallSite*>::iterator I = CalleeSites.begin(), E = CalleeSites.end(); I != E; ) { DSGraph &CG = *I->first.first; DEBUG(std::cerr << " [TD] Inlining graph into callee graph '" << CG.getFunctionNames() << "'\n"); // Clone our current graph into the callee... DSGraph::ScalarMapTy OldValMap; DSGraph::NodeMapTy OldNodeMap; DSGraph::ReturnNodesTy ReturnNodes; CG.cloneInto(Graph, OldValMap, ReturnNodes, OldNodeMap, DSGraph::StripModRefBits | DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes | DSGraph::DontCloneAuxCallNodes); OldValMap.clear(); // We don't care about the ValMap ReturnNodes.clear(); // We don't care about return values either // Loop over all of the invocation sites of the callee, resolving // arguments to our graph. This loop may iterate multiple times if the // current function calls this callee multiple times with different // signatures. // for (; I != E && I->first.first == &CG; ++I) { Function &Callee = *I->first.second; DEBUG(std::cerr << "\t [TD] Merging args for callee '" << Callee.getName() << "'\n"); // Map call site into callee graph DSCallSite NewCS(*I->second, OldNodeMap); // Resolve the return values... NewCS.getRetVal().mergeWith(CG.getReturnNodeFor(Callee)); // Resolve all of the arguments... Function::aiterator AI = Callee.abegin(); for (unsigned i = 0, e = NewCS.getNumPtrArgs(); i != e && AI != Callee.aend(); ++i, ++AI) { // Advance the argument iterator to the first pointer argument... while (AI != Callee.aend() && !DS::isPointerType(AI->getType())) ++AI; if (AI == Callee.aend()) break; // Add the link from the argument scalar to the provided value DSNodeHandle &NH = CG.getNodeForValue(AI); assert(NH.getNode() && "Pointer argument without scalarmap entry?"); NH.mergeWith(NewCS.getPtrArg(i)); } } // Done with the nodemap... OldNodeMap.clear(); // Recompute the Incomplete markers and eliminate unreachable nodes. CG.removeTriviallyDeadNodes(); //CG.maskIncompleteMarkers(); //CG.markIncompleteNodes(DSGraph::MarkFormalArgs | DSGraph::IgnoreGlobals); //CG.removeDeadNodes(DSGraph::RemoveUnreachableGlobals); } DEBUG(std::cerr << " [TD] Done inlining into callees for: " << Graph.getFunctionNames() << " [" << Graph.getGraphSize() << "+" << Graph.getFunctionCalls().size() << "]\n"); #if 0 // Loop over all the callees... making sure they are all resolved now... Function *LastFunc = 0; for (std::multimap<Function*, const DSCallSite*>::iterator I = CalleeSites.begin(), E = CalleeSites.end(); I != E; ++I) if (I->first != LastFunc) { // Only visit each callee once... LastFunc = I->first; calculateGraph(*I->first); } #endif } <commit_msg>Complete rewrite of td pass<commit_after>//===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===// // // This file implements the TDDataStructures class, which represents the // Top-down Interprocedural closure of the data structure graph over the // program. This is useful (but not strictly necessary?) for applications // like pointer analysis. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/DataStructure.h" #include "llvm/Module.h" #include "llvm/DerivedTypes.h" #include "Support/Statistic.h" #include "DSCallSiteIterator.h" namespace { RegisterAnalysis<TDDataStructures> // Register the pass Y("tddatastructure", "Top-down Data Structure Analysis"); Statistic<> NumTDInlines("tddatastructures", "Number of graphs inlined"); } /// FunctionHasCompleteArguments - This function returns true if it is safe not /// to mark arguments to the function complete. /// /// FIXME: Need to check if all callers have been found, or rather if a /// funcpointer escapes! /// static bool FunctionHasCompleteArguments(Function &F) { return F.hasInternalLinkage(); } // run - Calculate the top down data structure graphs for each function in the // program. // bool TDDataStructures::run(Module &M) { BUDataStructures &BU = getAnalysis<BUDataStructures>(); GlobalsGraph = new DSGraph(BU.getGlobalsGraph()); // Figure out which functions must not mark their arguments complete because // they are accessible outside this compilation unit. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!FunctionHasCompleteArguments(*I)) ArgsRemainIncomplete.insert(I); // Calculate top-down from main... if (Function *F = M.getMainFunction()) calculateGraphFrom(*F); // Next calculate the graphs for each function unreachable function... for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!I->isExternal() && !DSInfo.count(I)) calculateGraphFrom(*I); ArgsRemainIncomplete.clear(); return false; } // releaseMemory - If the pass pipeline is done with this pass, we can release // our memory... here... // // FIXME: This should be releaseMemory and will work fine, except that LoadVN // has no way to extend the lifetime of the pass, which screws up ds-aa. // void TDDataStructures::releaseMyMemory() { for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(), E = DSInfo.end(); I != E; ++I) { I->second->getReturnNodes().erase(I->first); if (I->second->getReturnNodes().empty()) delete I->second; } // Empty map so next time memory is released, data structures are not // re-deleted. DSInfo.clear(); delete GlobalsGraph; GlobalsGraph = 0; } DSGraph &TDDataStructures::getOrCreateDSGraph(Function &F) { DSGraph *&G = DSInfo[&F]; if (G == 0) { // Not created yet? Clone BU graph... G = new DSGraph(getAnalysis<BUDataStructures>().getDSGraph(F)); G->getAuxFunctionCalls().clear(); G->setPrintAuxCalls(); G->setGlobalsGraph(GlobalsGraph); } return *G; } void TDDataStructures::ComputePostOrder(Function &F,hash_set<DSGraph*> &Visited, std::vector<DSGraph*> &PostOrder, const BUDataStructures::ActualCalleesTy &ActualCallees) { if (F.isExternal()) return; DSGraph &G = getOrCreateDSGraph(F); if (Visited.count(&G)) return; Visited.insert(&G); // Recursively traverse all of the callee graphs. const std::vector<DSCallSite> &FunctionCalls = G.getFunctionCalls(); for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) { std::pair<BUDataStructures::ActualCalleesTy::const_iterator, BUDataStructures::ActualCalleesTy::const_iterator> IP = ActualCallees.equal_range(&FunctionCalls[i].getCallInst()); for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first; I != IP.second; ++I) ComputePostOrder(*I->second, Visited, PostOrder, ActualCallees); } PostOrder.push_back(&G); } void TDDataStructures::calculateGraphFrom(Function &F) { // We want to traverse the call graph in reverse post-order. To do this, we // calculate a post-order traversal, then reverse it. hash_set<DSGraph*> VisitedGraph; std::vector<DSGraph*> PostOrder; ComputePostOrder(F, VisitedGraph, PostOrder, getAnalysis<BUDataStructures>().getActualCallees()); VisitedGraph.clear(); // Release memory! // Visit each of the graphs in reverse post-order now! while (!PostOrder.empty()) { inlineGraphIntoCallees(*PostOrder.back()); PostOrder.pop_back(); } } void TDDataStructures::inlineGraphIntoCallees(DSGraph &Graph) { // Recompute the Incomplete markers and eliminate unreachable nodes. Graph.maskIncompleteMarkers(); // If any of the functions has incomplete incoming arguments, don't mark any // of them as complete. bool HasIncompleteArgs = false; const DSGraph::ReturnNodesTy &GraphReturnNodes = Graph.getReturnNodes(); for (DSGraph::ReturnNodesTy::const_iterator I = GraphReturnNodes.begin(), E = GraphReturnNodes.end(); I != E; ++I) if (ArgsRemainIncomplete.count(I->first)) { HasIncompleteArgs = true; break; } unsigned Flags = HasIncompleteArgs ? DSGraph::MarkFormalArgs : DSGraph::IgnoreFormalArgs; Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals); Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals); const std::vector<DSCallSite> &FunctionCalls = Graph.getFunctionCalls(); if (FunctionCalls.empty()) { DEBUG(std::cerr << " [TD] No callees for: " << Graph.getFunctionNames() << "\n"); return; } // Now that we have information about all of the callees, propagate the // current graph into the callees. // DEBUG(std::cerr << " [TD] Inlining '" << Graph.getFunctionNames() <<"' into " << FunctionCalls.size() << " call nodes.\n"); const BUDataStructures::ActualCalleesTy &ActualCallees = getAnalysis<BUDataStructures>().getActualCallees(); // Only inline this function into each real callee once. After that, just // merge information into arguments... hash_map<DSGraph*, DSGraph::NodeMapTy> InlinedSites; // Loop over all the callees... cloning this graph into each one exactly once, // keeping track of the node mapping information... for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) { // Inline this graph into each function in the invoked function list. std::pair<BUDataStructures::ActualCalleesTy::const_iterator, BUDataStructures::ActualCalleesTy::const_iterator> IP = ActualCallees.equal_range(&FunctionCalls[i].getCallInst()); int NumArgs = 0; if (IP.first != IP.second) { NumArgs = IP.first->second->getFunctionType()->getNumParams(); for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first; I != IP.second; ++I) if (NumArgs != (int)I->second->getFunctionType()->getNumParams()) { NumArgs = -1; break; } } if (NumArgs == -1) { std::cerr << "ERROR: NONSAME NUMBER OF ARGUMENTS TO CALLEES\n"; } for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first; I != IP.second; ++I) { DSGraph &CG = getDSGraph(*I->second); assert(&CG != &Graph && "TD need not inline graph into self!"); if (!InlinedSites.count(&CG)) { // If we haven't already inlined into CG DEBUG(std::cerr << " [TD] Inlining graph into callee graph '" << CG.getFunctionNames() << "': " << I->second->getFunctionType()->getNumParams() << " args\n"); DSGraph::ScalarMapTy OldScalarMap; DSGraph::ReturnNodesTy ReturnNodes; CG.cloneInto(Graph, OldScalarMap, ReturnNodes, InlinedSites[&CG], DSGraph::StripModRefBits | DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes | DSGraph::DontCloneAuxCallNodes); ++NumTDInlines; } } } // Loop over all the callees... for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) { // Inline this graph into each function in the invoked function list. std::pair<BUDataStructures::ActualCalleesTy::const_iterator, BUDataStructures::ActualCalleesTy::const_iterator> IP = ActualCallees.equal_range(&FunctionCalls[i].getCallInst()); for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first; I != IP.second; ++I) { DSGraph &CG = getDSGraph(*I->second); DEBUG(std::cerr << " [TD] Resolving arguments for callee graph '" << CG.getFunctionNames() << "'\n"); // Transform our call site information into the cloned version for CG DSCallSite CS(FunctionCalls[i], InlinedSites[&CG]); // Get the arguments bindings for the called function in CG... and merge // them with the cloned graph. CG.getCallSiteForArguments(*I->second).mergeWith(CS); } } DEBUG(std::cerr << " [TD] Done inlining into callees for: " << Graph.getFunctionNames() << " [" << Graph.getGraphSize() << "+" << Graph.getFunctionCalls().size() << "]\n"); } <|endoftext|>
<commit_before>//===- DbiStreamBuilder.cpp - PDB Dbi Stream Creation -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h" #include "llvm/DebugInfo/CodeView/RecordName.h" #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h" #include "llvm/DebugInfo/CodeView/SymbolRecord.h" #include "llvm/DebugInfo/CodeView/SymbolSerializer.h" #include "llvm/DebugInfo/MSF/MSFBuilder.h" #include "llvm/DebugInfo/MSF/MSFCommon.h" #include "llvm/DebugInfo/MSF/MappedBlockStream.h" #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h" #include "llvm/DebugInfo/PDB/Native/Hash.h" #include "llvm/Support/BinaryItemStream.h" #include "llvm/Support/BinaryStreamWriter.h" #include <algorithm> #include <vector> using namespace llvm; using namespace llvm::msf; using namespace llvm::pdb; using namespace llvm::codeview; struct llvm::pdb::GSIHashStreamBuilder { std::vector<CVSymbol> Records; uint32_t StreamIndex; std::vector<PSHashRecord> HashRecords; std::array<support::ulittle32_t, (IPHR_HASH + 32) / 32> HashBitmap; std::vector<support::ulittle32_t> HashBuckets; uint32_t calculateSerializedLength() const; uint32_t calculateRecordByteSize() const; Error commit(BinaryStreamWriter &Writer); void finalizeBuckets(uint32_t RecordZeroOffset); template <typename T> void addSymbol(const T &Symbol, MSFBuilder &Msf) { T Copy(Symbol); Records.push_back(SymbolSerializer::writeOneSymbol(Copy, Msf.getAllocator(), CodeViewContainer::Pdb)); } void addSymbol(const CVSymbol &Symbol) { Records.push_back(Symbol); } }; uint32_t GSIHashStreamBuilder::calculateSerializedLength() const { uint32_t Size = sizeof(GSIHashHeader); Size += HashRecords.size() * sizeof(PSHashRecord); Size += HashBitmap.size() * sizeof(uint32_t); Size += HashBuckets.size() * sizeof(uint32_t); return Size; } uint32_t GSIHashStreamBuilder::calculateRecordByteSize() const { uint32_t Size = 0; for (const auto &Sym : Records) Size += Sym.length(); return Size; } Error GSIHashStreamBuilder::commit(BinaryStreamWriter &Writer) { GSIHashHeader Header; Header.VerSignature = GSIHashHeader::HdrSignature; Header.VerHdr = GSIHashHeader::HdrVersion; Header.HrSize = HashRecords.size() * sizeof(PSHashRecord); Header.NumBuckets = HashBitmap.size() * 4 + HashBuckets.size() * 4; if (auto EC = Writer.writeObject(Header)) return EC; if (auto EC = Writer.writeArray(makeArrayRef(HashRecords))) return EC; if (auto EC = Writer.writeArray(makeArrayRef(HashBitmap))) return EC; if (auto EC = Writer.writeArray(makeArrayRef(HashBuckets))) return EC; return Error::success(); } static bool isAsciiString(StringRef S) { return llvm::all_of(S, [](char C) { return unsigned(C) < 0x80; }); } // See `caseInsensitiveComparePchPchCchCch` in gsi.cpp static bool gsiRecordLess(StringRef S1, StringRef S2) { size_t LS = S1.size(); size_t RS = S2.size(); // Shorter strings always compare less than longer strings. if (LS != RS) return LS < RS; // If either string contains non ascii characters, memcmp them. if (LLVM_UNLIKELY(!isAsciiString(S1) || !isAsciiString(S2))) return memcmp(S1.data(), S2.data(), LS) < 0; // Both strings are ascii, perform a case-insenstive comparison. return S1.compare_lower(S2.data()) < 0; } void GSIHashStreamBuilder::finalizeBuckets(uint32_t RecordZeroOffset) { std::array<std::vector<std::pair<StringRef, PSHashRecord>>, IPHR_HASH + 1> TmpBuckets; uint32_t SymOffset = RecordZeroOffset; for (const CVSymbol &Sym : Records) { PSHashRecord HR; // Add one when writing symbol offsets to disk. See GSI1::fixSymRecs. HR.Off = SymOffset + 1; HR.CRef = 1; // Always use a refcount of 1. // Hash the name to figure out which bucket this goes into. StringRef Name = getSymbolName(Sym); size_t BucketIdx = hashStringV1(Name) % IPHR_HASH; TmpBuckets[BucketIdx].push_back(std::make_pair(Name, HR)); SymOffset += Sym.length(); } // Compute the three tables: the hash records in bucket and chain order, the // bucket presence bitmap, and the bucket chain start offsets. HashRecords.reserve(Records.size()); for (ulittle32_t &Word : HashBitmap) Word = 0; for (size_t BucketIdx = 0; BucketIdx < IPHR_HASH + 1; ++BucketIdx) { auto &Bucket = TmpBuckets[BucketIdx]; if (Bucket.empty()) continue; HashBitmap[BucketIdx / 32] |= 1U << (BucketIdx % 32); // Calculate what the offset of the first hash record in the chain would // be if it were inflated to contain 32-bit pointers. On a 32-bit system, // each record would be 12 bytes. See HROffsetCalc in gsi.h. const int SizeOfHROffsetCalc = 12; ulittle32_t ChainStartOff = ulittle32_t(HashRecords.size() * SizeOfHROffsetCalc); HashBuckets.push_back(ChainStartOff); // Sort each bucket by memcmp of the symbol's name. It's important that // we use the same sorting algorithm as is used by the reference // implementation to ensure that the search for a record within a bucket // can properly early-out when it detects the record won't be found. The // algorithm used here corredsponds to the function // caseInsensitiveComparePchPchCchCch in the reference implementation. llvm::sort(Bucket.begin(), Bucket.end(), [](const std::pair<StringRef, PSHashRecord> &Left, const std::pair<StringRef, PSHashRecord> &Right) { return gsiRecordLess(Left.first, Right.first); }); for (const auto &Entry : Bucket) HashRecords.push_back(Entry.second); } } GSIStreamBuilder::GSIStreamBuilder(msf::MSFBuilder &Msf) : Msf(Msf), PSH(llvm::make_unique<GSIHashStreamBuilder>()), GSH(llvm::make_unique<GSIHashStreamBuilder>()) {} GSIStreamBuilder::~GSIStreamBuilder() {} uint32_t GSIStreamBuilder::calculatePublicsHashStreamSize() const { uint32_t Size = 0; Size += sizeof(PublicsStreamHeader); Size += PSH->calculateSerializedLength(); Size += PSH->Records.size() * sizeof(uint32_t); // AddrMap // FIXME: Add thunk map and section offsets for incremental linking. return Size; } uint32_t GSIStreamBuilder::calculateGlobalsHashStreamSize() const { return GSH->calculateSerializedLength(); } Error GSIStreamBuilder::finalizeMsfLayout() { // First we write public symbol records, then we write global symbol records. uint32_t PSHZero = 0; uint32_t GSHZero = PSH->calculateRecordByteSize(); PSH->finalizeBuckets(PSHZero); GSH->finalizeBuckets(GSHZero); Expected<uint32_t> Idx = Msf.addStream(calculateGlobalsHashStreamSize()); if (!Idx) return Idx.takeError(); GSH->StreamIndex = *Idx; Idx = Msf.addStream(calculatePublicsHashStreamSize()); if (!Idx) return Idx.takeError(); PSH->StreamIndex = *Idx; uint32_t RecordBytes = GSH->calculateRecordByteSize() + PSH->calculateRecordByteSize(); Idx = Msf.addStream(RecordBytes); if (!Idx) return Idx.takeError(); RecordStreamIdx = *Idx; return Error::success(); } static bool comparePubSymByAddrAndName( const std::pair<const CVSymbol *, const PublicSym32 *> &LS, const std::pair<const CVSymbol *, const PublicSym32 *> &RS) { if (LS.second->Segment != RS.second->Segment) return LS.second->Segment < RS.second->Segment; if (LS.second->Offset != RS.second->Offset) return LS.second->Offset < RS.second->Offset; return LS.second->Name < RS.second->Name; } /// Compute the address map. The address map is an array of symbol offsets /// sorted so that it can be binary searched by address. static std::vector<ulittle32_t> computeAddrMap(ArrayRef<CVSymbol> Records) { // Make a vector of pointers to the symbols so we can sort it by address. // Also gather the symbol offsets while we're at it. std::vector<PublicSym32> DeserializedPublics; std::vector<std::pair<const CVSymbol *, const PublicSym32 *>> PublicsByAddr; std::vector<uint32_t> SymOffsets; DeserializedPublics.reserve(Records.size()); PublicsByAddr.reserve(Records.size()); SymOffsets.reserve(Records.size()); uint32_t SymOffset = 0; for (const CVSymbol &Sym : Records) { assert(Sym.kind() == SymbolKind::S_PUB32); DeserializedPublics.push_back( cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(Sym))); PublicsByAddr.emplace_back(&Sym, &DeserializedPublics.back()); SymOffsets.push_back(SymOffset); SymOffset += Sym.length(); } std::stable_sort(PublicsByAddr.begin(), PublicsByAddr.end(), comparePubSymByAddrAndName); // Fill in the symbol offsets in the appropriate order. std::vector<ulittle32_t> AddrMap; AddrMap.reserve(Records.size()); for (auto &Sym : PublicsByAddr) { ptrdiff_t Idx = std::distance(Records.data(), Sym.first); assert(Idx >= 0 && size_t(Idx) < Records.size()); AddrMap.push_back(ulittle32_t(SymOffsets[Idx])); } return AddrMap; } uint32_t GSIStreamBuilder::getPublicsStreamIndex() const { return PSH->StreamIndex; } uint32_t GSIStreamBuilder::getGlobalsStreamIndex() const { return GSH->StreamIndex; } void GSIStreamBuilder::addPublicSymbol(const PublicSym32 &Pub) { PSH->addSymbol(Pub, Msf); } void GSIStreamBuilder::addGlobalSymbol(const ProcRefSym &Sym) { GSH->addSymbol(Sym, Msf); } void GSIStreamBuilder::addGlobalSymbol(const DataSym &Sym) { GSH->addSymbol(Sym, Msf); } void GSIStreamBuilder::addGlobalSymbol(const ConstantSym &Sym) { GSH->addSymbol(Sym, Msf); } void GSIStreamBuilder::addGlobalSymbol(const UDTSym &Sym) { GSH->addSymbol(Sym, Msf); } void GSIStreamBuilder::addGlobalSymbol(const codeview::CVSymbol &Sym) { GSH->addSymbol(Sym); } static Error writeRecords(BinaryStreamWriter &Writer, ArrayRef<CVSymbol> Records) { BinaryItemStream<CVSymbol> ItemStream(support::endianness::little); ItemStream.setItems(Records); BinaryStreamRef RecordsRef(ItemStream); return Writer.writeStreamRef(RecordsRef); } Error GSIStreamBuilder::commitSymbolRecordStream( WritableBinaryStreamRef Stream) { BinaryStreamWriter Writer(Stream); // Write public symbol records first, followed by global symbol records. This // must match the order that we assume in finalizeMsfLayout when computing // PSHZero and GSHZero. if (auto EC = writeRecords(Writer, PSH->Records)) return EC; if (auto EC = writeRecords(Writer, GSH->Records)) return EC; return Error::success(); } Error GSIStreamBuilder::commitPublicsHashStream( WritableBinaryStreamRef Stream) { BinaryStreamWriter Writer(Stream); PublicsStreamHeader Header; // FIXME: Fill these in. They are for incremental linking. Header.NumThunks = 0; Header.SizeOfThunk = 0; Header.ISectThunkTable = 0; Header.OffThunkTable = 0; Header.NumSections = 0; Header.SymHash = PSH->calculateSerializedLength(); Header.AddrMap = PSH->Records.size() * 4; if (auto EC = Writer.writeObject(Header)) return EC; if (auto EC = PSH->commit(Writer)) return EC; std::vector<ulittle32_t> AddrMap = computeAddrMap(PSH->Records); if (auto EC = Writer.writeArray(makeArrayRef(AddrMap))) return EC; return Error::success(); } Error GSIStreamBuilder::commitGlobalsHashStream( WritableBinaryStreamRef Stream) { BinaryStreamWriter Writer(Stream); return GSH->commit(Writer); } Error GSIStreamBuilder::commit(const msf::MSFLayout &Layout, WritableBinaryStreamRef Buffer) { auto GS = WritableMappedBlockStream::createIndexedStream( Layout, Buffer, getGlobalsStreamIndex(), Msf.getAllocator()); auto PS = WritableMappedBlockStream::createIndexedStream( Layout, Buffer, getPublicsStreamIndex(), Msf.getAllocator()); auto PRS = WritableMappedBlockStream::createIndexedStream( Layout, Buffer, getRecordStreamIdx(), Msf.getAllocator()); if (auto EC = commitSymbolRecordStream(*PRS)) return EC; if (auto EC = commitGlobalsHashStream(*GS)) return EC; if (auto EC = commitPublicsHashStream(*PS)) return EC; return Error::success(); } <commit_msg>pdb output: Initialize padding in PublicsStreamHeader.<commit_after>//===- DbiStreamBuilder.cpp - PDB Dbi Stream Creation -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h" #include "llvm/DebugInfo/CodeView/RecordName.h" #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h" #include "llvm/DebugInfo/CodeView/SymbolRecord.h" #include "llvm/DebugInfo/CodeView/SymbolSerializer.h" #include "llvm/DebugInfo/MSF/MSFBuilder.h" #include "llvm/DebugInfo/MSF/MSFCommon.h" #include "llvm/DebugInfo/MSF/MappedBlockStream.h" #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h" #include "llvm/DebugInfo/PDB/Native/Hash.h" #include "llvm/Support/BinaryItemStream.h" #include "llvm/Support/BinaryStreamWriter.h" #include <algorithm> #include <vector> using namespace llvm; using namespace llvm::msf; using namespace llvm::pdb; using namespace llvm::codeview; struct llvm::pdb::GSIHashStreamBuilder { std::vector<CVSymbol> Records; uint32_t StreamIndex; std::vector<PSHashRecord> HashRecords; std::array<support::ulittle32_t, (IPHR_HASH + 32) / 32> HashBitmap; std::vector<support::ulittle32_t> HashBuckets; uint32_t calculateSerializedLength() const; uint32_t calculateRecordByteSize() const; Error commit(BinaryStreamWriter &Writer); void finalizeBuckets(uint32_t RecordZeroOffset); template <typename T> void addSymbol(const T &Symbol, MSFBuilder &Msf) { T Copy(Symbol); Records.push_back(SymbolSerializer::writeOneSymbol(Copy, Msf.getAllocator(), CodeViewContainer::Pdb)); } void addSymbol(const CVSymbol &Symbol) { Records.push_back(Symbol); } }; uint32_t GSIHashStreamBuilder::calculateSerializedLength() const { uint32_t Size = sizeof(GSIHashHeader); Size += HashRecords.size() * sizeof(PSHashRecord); Size += HashBitmap.size() * sizeof(uint32_t); Size += HashBuckets.size() * sizeof(uint32_t); return Size; } uint32_t GSIHashStreamBuilder::calculateRecordByteSize() const { uint32_t Size = 0; for (const auto &Sym : Records) Size += Sym.length(); return Size; } Error GSIHashStreamBuilder::commit(BinaryStreamWriter &Writer) { GSIHashHeader Header; Header.VerSignature = GSIHashHeader::HdrSignature; Header.VerHdr = GSIHashHeader::HdrVersion; Header.HrSize = HashRecords.size() * sizeof(PSHashRecord); Header.NumBuckets = HashBitmap.size() * 4 + HashBuckets.size() * 4; if (auto EC = Writer.writeObject(Header)) return EC; if (auto EC = Writer.writeArray(makeArrayRef(HashRecords))) return EC; if (auto EC = Writer.writeArray(makeArrayRef(HashBitmap))) return EC; if (auto EC = Writer.writeArray(makeArrayRef(HashBuckets))) return EC; return Error::success(); } static bool isAsciiString(StringRef S) { return llvm::all_of(S, [](char C) { return unsigned(C) < 0x80; }); } // See `caseInsensitiveComparePchPchCchCch` in gsi.cpp static bool gsiRecordLess(StringRef S1, StringRef S2) { size_t LS = S1.size(); size_t RS = S2.size(); // Shorter strings always compare less than longer strings. if (LS != RS) return LS < RS; // If either string contains non ascii characters, memcmp them. if (LLVM_UNLIKELY(!isAsciiString(S1) || !isAsciiString(S2))) return memcmp(S1.data(), S2.data(), LS) < 0; // Both strings are ascii, perform a case-insenstive comparison. return S1.compare_lower(S2.data()) < 0; } void GSIHashStreamBuilder::finalizeBuckets(uint32_t RecordZeroOffset) { std::array<std::vector<std::pair<StringRef, PSHashRecord>>, IPHR_HASH + 1> TmpBuckets; uint32_t SymOffset = RecordZeroOffset; for (const CVSymbol &Sym : Records) { PSHashRecord HR; // Add one when writing symbol offsets to disk. See GSI1::fixSymRecs. HR.Off = SymOffset + 1; HR.CRef = 1; // Always use a refcount of 1. // Hash the name to figure out which bucket this goes into. StringRef Name = getSymbolName(Sym); size_t BucketIdx = hashStringV1(Name) % IPHR_HASH; TmpBuckets[BucketIdx].push_back(std::make_pair(Name, HR)); SymOffset += Sym.length(); } // Compute the three tables: the hash records in bucket and chain order, the // bucket presence bitmap, and the bucket chain start offsets. HashRecords.reserve(Records.size()); for (ulittle32_t &Word : HashBitmap) Word = 0; for (size_t BucketIdx = 0; BucketIdx < IPHR_HASH + 1; ++BucketIdx) { auto &Bucket = TmpBuckets[BucketIdx]; if (Bucket.empty()) continue; HashBitmap[BucketIdx / 32] |= 1U << (BucketIdx % 32); // Calculate what the offset of the first hash record in the chain would // be if it were inflated to contain 32-bit pointers. On a 32-bit system, // each record would be 12 bytes. See HROffsetCalc in gsi.h. const int SizeOfHROffsetCalc = 12; ulittle32_t ChainStartOff = ulittle32_t(HashRecords.size() * SizeOfHROffsetCalc); HashBuckets.push_back(ChainStartOff); // Sort each bucket by memcmp of the symbol's name. It's important that // we use the same sorting algorithm as is used by the reference // implementation to ensure that the search for a record within a bucket // can properly early-out when it detects the record won't be found. The // algorithm used here corredsponds to the function // caseInsensitiveComparePchPchCchCch in the reference implementation. llvm::sort(Bucket.begin(), Bucket.end(), [](const std::pair<StringRef, PSHashRecord> &Left, const std::pair<StringRef, PSHashRecord> &Right) { return gsiRecordLess(Left.first, Right.first); }); for (const auto &Entry : Bucket) HashRecords.push_back(Entry.second); } } GSIStreamBuilder::GSIStreamBuilder(msf::MSFBuilder &Msf) : Msf(Msf), PSH(llvm::make_unique<GSIHashStreamBuilder>()), GSH(llvm::make_unique<GSIHashStreamBuilder>()) {} GSIStreamBuilder::~GSIStreamBuilder() {} uint32_t GSIStreamBuilder::calculatePublicsHashStreamSize() const { uint32_t Size = 0; Size += sizeof(PublicsStreamHeader); Size += PSH->calculateSerializedLength(); Size += PSH->Records.size() * sizeof(uint32_t); // AddrMap // FIXME: Add thunk map and section offsets for incremental linking. return Size; } uint32_t GSIStreamBuilder::calculateGlobalsHashStreamSize() const { return GSH->calculateSerializedLength(); } Error GSIStreamBuilder::finalizeMsfLayout() { // First we write public symbol records, then we write global symbol records. uint32_t PSHZero = 0; uint32_t GSHZero = PSH->calculateRecordByteSize(); PSH->finalizeBuckets(PSHZero); GSH->finalizeBuckets(GSHZero); Expected<uint32_t> Idx = Msf.addStream(calculateGlobalsHashStreamSize()); if (!Idx) return Idx.takeError(); GSH->StreamIndex = *Idx; Idx = Msf.addStream(calculatePublicsHashStreamSize()); if (!Idx) return Idx.takeError(); PSH->StreamIndex = *Idx; uint32_t RecordBytes = GSH->calculateRecordByteSize() + PSH->calculateRecordByteSize(); Idx = Msf.addStream(RecordBytes); if (!Idx) return Idx.takeError(); RecordStreamIdx = *Idx; return Error::success(); } static bool comparePubSymByAddrAndName( const std::pair<const CVSymbol *, const PublicSym32 *> &LS, const std::pair<const CVSymbol *, const PublicSym32 *> &RS) { if (LS.second->Segment != RS.second->Segment) return LS.second->Segment < RS.second->Segment; if (LS.second->Offset != RS.second->Offset) return LS.second->Offset < RS.second->Offset; return LS.second->Name < RS.second->Name; } /// Compute the address map. The address map is an array of symbol offsets /// sorted so that it can be binary searched by address. static std::vector<ulittle32_t> computeAddrMap(ArrayRef<CVSymbol> Records) { // Make a vector of pointers to the symbols so we can sort it by address. // Also gather the symbol offsets while we're at it. std::vector<PublicSym32> DeserializedPublics; std::vector<std::pair<const CVSymbol *, const PublicSym32 *>> PublicsByAddr; std::vector<uint32_t> SymOffsets; DeserializedPublics.reserve(Records.size()); PublicsByAddr.reserve(Records.size()); SymOffsets.reserve(Records.size()); uint32_t SymOffset = 0; for (const CVSymbol &Sym : Records) { assert(Sym.kind() == SymbolKind::S_PUB32); DeserializedPublics.push_back( cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(Sym))); PublicsByAddr.emplace_back(&Sym, &DeserializedPublics.back()); SymOffsets.push_back(SymOffset); SymOffset += Sym.length(); } std::stable_sort(PublicsByAddr.begin(), PublicsByAddr.end(), comparePubSymByAddrAndName); // Fill in the symbol offsets in the appropriate order. std::vector<ulittle32_t> AddrMap; AddrMap.reserve(Records.size()); for (auto &Sym : PublicsByAddr) { ptrdiff_t Idx = std::distance(Records.data(), Sym.first); assert(Idx >= 0 && size_t(Idx) < Records.size()); AddrMap.push_back(ulittle32_t(SymOffsets[Idx])); } return AddrMap; } uint32_t GSIStreamBuilder::getPublicsStreamIndex() const { return PSH->StreamIndex; } uint32_t GSIStreamBuilder::getGlobalsStreamIndex() const { return GSH->StreamIndex; } void GSIStreamBuilder::addPublicSymbol(const PublicSym32 &Pub) { PSH->addSymbol(Pub, Msf); } void GSIStreamBuilder::addGlobalSymbol(const ProcRefSym &Sym) { GSH->addSymbol(Sym, Msf); } void GSIStreamBuilder::addGlobalSymbol(const DataSym &Sym) { GSH->addSymbol(Sym, Msf); } void GSIStreamBuilder::addGlobalSymbol(const ConstantSym &Sym) { GSH->addSymbol(Sym, Msf); } void GSIStreamBuilder::addGlobalSymbol(const UDTSym &Sym) { GSH->addSymbol(Sym, Msf); } void GSIStreamBuilder::addGlobalSymbol(const codeview::CVSymbol &Sym) { GSH->addSymbol(Sym); } static Error writeRecords(BinaryStreamWriter &Writer, ArrayRef<CVSymbol> Records) { BinaryItemStream<CVSymbol> ItemStream(support::endianness::little); ItemStream.setItems(Records); BinaryStreamRef RecordsRef(ItemStream); return Writer.writeStreamRef(RecordsRef); } Error GSIStreamBuilder::commitSymbolRecordStream( WritableBinaryStreamRef Stream) { BinaryStreamWriter Writer(Stream); // Write public symbol records first, followed by global symbol records. This // must match the order that we assume in finalizeMsfLayout when computing // PSHZero and GSHZero. if (auto EC = writeRecords(Writer, PSH->Records)) return EC; if (auto EC = writeRecords(Writer, GSH->Records)) return EC; return Error::success(); } Error GSIStreamBuilder::commitPublicsHashStream( WritableBinaryStreamRef Stream) { BinaryStreamWriter Writer(Stream); PublicsStreamHeader Header; // FIXME: Fill these in. They are for incremental linking. Header.SymHash = PSH->calculateSerializedLength(); Header.AddrMap = PSH->Records.size() * 4; Header.NumThunks = 0; Header.SizeOfThunk = 0; Header.ISectThunkTable = 0; memset(Header.Padding, 0, sizeof(Header.Padding)); Header.OffThunkTable = 0; Header.NumSections = 0; if (auto EC = Writer.writeObject(Header)) return EC; if (auto EC = PSH->commit(Writer)) return EC; std::vector<ulittle32_t> AddrMap = computeAddrMap(PSH->Records); if (auto EC = Writer.writeArray(makeArrayRef(AddrMap))) return EC; return Error::success(); } Error GSIStreamBuilder::commitGlobalsHashStream( WritableBinaryStreamRef Stream) { BinaryStreamWriter Writer(Stream); return GSH->commit(Writer); } Error GSIStreamBuilder::commit(const msf::MSFLayout &Layout, WritableBinaryStreamRef Buffer) { auto GS = WritableMappedBlockStream::createIndexedStream( Layout, Buffer, getGlobalsStreamIndex(), Msf.getAllocator()); auto PS = WritableMappedBlockStream::createIndexedStream( Layout, Buffer, getPublicsStreamIndex(), Msf.getAllocator()); auto PRS = WritableMappedBlockStream::createIndexedStream( Layout, Buffer, getRecordStreamIdx(), Msf.getAllocator()); if (auto EC = commitSymbolRecordStream(*PRS)) return EC; if (auto EC = commitGlobalsHashStream(*GS)) return EC; if (auto EC = commitPublicsHashStream(*PS)) return EC; return Error::success(); } <|endoftext|>
<commit_before>/* Stream.cpp - adds parsing methods to Stream class Copyright (c) 2008 David A. Mellis. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Created July 2011 parsing functions based on TextFinder library by Michael Margolis */ #include "Arduino.h" #include "Stream.h" #define PARSE_TIMEOUT 1000 // default number of milli-seconds to wait #define NO_SKIP_CHAR 1 // a magic char not found in a valid ASCII numeric field // private method to read stream with timeout int Stream::timedRead() { int c; _startMillis = millis(); do { c = read(); if (c >= 0) return c; } while(millis() - _startMillis < _timeout); return -1; // -1 indicates timeout } // private method to peek stream with timeout int Stream::timedPeek() { int c; _startMillis = millis(); do { c = peek(); if (c >= 0) return c; } while(millis() - _startMillis < _timeout); return -1; // -1 indicates timeout } // returns peek of the next digit in the stream or -1 if timeout // discards non-numeric characters int Stream::peekNextDigit() { int c; while (1) { c = timedPeek(); if (c < 0) return c; // timeout if (c == '-') return c; if (c >= '0' && c <= '9') return c; read(); // discard non-numeric } } // Public Methods ////////////////////////////////////////////////////////////// void Stream::setTimeout(unsigned long timeout) // sets the maximum number of milliseconds to wait { _timeout = timeout; } // find returns true if the target string is found bool Stream::find(char *target) { return findUntil(target, NULL); } // reads data from the stream until the target string of given length is found // returns true if target string is found, false if timed out bool Stream::find(char *target, size_t length) { return findUntil(target, length, NULL, 0); } // as find but search ends if the terminator string is found bool Stream::findUntil(char *target, char *terminator) { return findUntil(target, strlen(target), terminator, strlen(terminator)); } // reads data from the stream until the target string of the given length is found // search terminated if the terminator string is found // returns true if target string is found, false if terminated or timed out bool Stream::findUntil(char *target, size_t targetLen, char *terminator, size_t termLen) { size_t index = 0; // maximum target string length is 64k bytes! size_t termIndex = 0; int c; if( *target == 0) return true; // return true if target is a null string while( (c = timedRead()) > 0){ if( c == target[index]){ //////Serial.print("found "); Serial.write(c); Serial.print("index now"); Serial.println(index+1); if(++index >= targetLen){ // return true if all chars in the target match return true; } } else{ index = 0; // reset index if any char does not match } if(termLen > 0 && c == terminator[termIndex]){ if(++termIndex >= termLen) return false; // return false if terminate string found before target string } else termIndex = 0; } return false; } // returns the first valid (long) integer value from the current position. // initial characters that are not digits (or the minus sign) are skipped // function is terminated by the first character that is not a digit. long Stream::parseInt() { return parseInt(NO_SKIP_CHAR); // terminate on first non-digit character (or timeout) } // as above but a given skipChar is ignored // this allows format characters (typically commas) in values to be ignored long Stream::parseInt(char skipChar) { boolean isNegative = false; long value = 0; int c; c = peekNextDigit(); // ignore non numeric leading characters if(c < 0) return 0; // zero returned if timeout do{ if(c == skipChar) ; // ignore this charactor else if(c == '-') isNegative = true; else if(c >= '0' && c <= '9') // is c a digit? value = value * 10 + c - '0'; read(); // consume the character we got with peek c = timedPeek(); } while( (c >= '0' && c <= '9') || c == skipChar ); if(isNegative) value = -value; return value; } // as parseInt but returns a floating point value float Stream::parseFloat() { return parseFloat(NO_SKIP_CHAR); } // as above but the given skipChar is ignored // this allows format characters (typically commas) in values to be ignored float Stream::parseFloat(char skipChar){ boolean isNegative = false; boolean isFraction = false; long value = 0; char c; float fraction = 1.0; c = peekNextDigit(); // ignore non numeric leading characters if(c < 0) return 0; // zero returned if timeout do{ if(c == skipChar) ; // ignore else if(c == '-') isNegative = true; else if (c == '.') isFraction = true; else if(c >= '0' && c <= '9') { // is c a digit? value = value * 10 + c - '0'; if(isFraction) fraction *= 0.1; } read(); // consume the character we got with peek c = timedPeek(); } while( (c >= '0' && c <= '9') || c == '.' || c == skipChar ); if(isNegative) value = -value; if(isFraction) return value * fraction; else return value; } // read characters from stream into buffer // terminates if length characters have been read, or timeout (see setTimeout) // returns the number of characters placed in the buffer // the buffer is NOT null terminated. // size_t Stream::readBytes(char *buffer, size_t length) { size_t count = 0; while (count < length) { int c = timedRead(); if (c < 0) break; *buffer++ = (char)c; count++; } return count; } // as readBytes with terminator character // terminates if length characters have been read, timeout, or if the terminator character detected // returns the number of characters placed in the buffer (0 means no valid data found) size_t Stream::readBytesUntil(char terminator, char *buffer, size_t length) { if (length < 1) return 0; size_t index = 0; while (index < length) { int c = timedRead(); if (c < 0 || c == terminator) break; *buffer++ = (char)c; index++; } return index; // return number of characters, not including null terminator } <commit_msg>Fixing findUntil() problem with repeated initial characters. (Jeffery.zksun)<commit_after>/* Stream.cpp - adds parsing methods to Stream class Copyright (c) 2008 David A. Mellis. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Created July 2011 parsing functions based on TextFinder library by Michael Margolis */ #include "Arduino.h" #include "Stream.h" #define PARSE_TIMEOUT 1000 // default number of milli-seconds to wait #define NO_SKIP_CHAR 1 // a magic char not found in a valid ASCII numeric field // private method to read stream with timeout int Stream::timedRead() { int c; _startMillis = millis(); do { c = read(); if (c >= 0) return c; } while(millis() - _startMillis < _timeout); return -1; // -1 indicates timeout } // private method to peek stream with timeout int Stream::timedPeek() { int c; _startMillis = millis(); do { c = peek(); if (c >= 0) return c; } while(millis() - _startMillis < _timeout); return -1; // -1 indicates timeout } // returns peek of the next digit in the stream or -1 if timeout // discards non-numeric characters int Stream::peekNextDigit() { int c; while (1) { c = timedPeek(); if (c < 0) return c; // timeout if (c == '-') return c; if (c >= '0' && c <= '9') return c; read(); // discard non-numeric } } // Public Methods ////////////////////////////////////////////////////////////// void Stream::setTimeout(unsigned long timeout) // sets the maximum number of milliseconds to wait { _timeout = timeout; } // find returns true if the target string is found bool Stream::find(char *target) { return findUntil(target, NULL); } // reads data from the stream until the target string of given length is found // returns true if target string is found, false if timed out bool Stream::find(char *target, size_t length) { return findUntil(target, length, NULL, 0); } // as find but search ends if the terminator string is found bool Stream::findUntil(char *target, char *terminator) { return findUntil(target, strlen(target), terminator, strlen(terminator)); } // reads data from the stream until the target string of the given length is found // search terminated if the terminator string is found // returns true if target string is found, false if terminated or timed out bool Stream::findUntil(char *target, size_t targetLen, char *terminator, size_t termLen) { size_t index = 0; // maximum target string length is 64k bytes! size_t termIndex = 0; int c; if( *target == 0) return true; // return true if target is a null string while( (c = timedRead()) > 0){ if(c != target[index]) index = 0; // reset index if any char does not match if( c == target[index]){ //////Serial.print("found "); Serial.write(c); Serial.print("index now"); Serial.println(index+1); if(++index >= targetLen){ // return true if all chars in the target match return true; } } if(termLen > 0 && c == terminator[termIndex]){ if(++termIndex >= termLen) return false; // return false if terminate string found before target string } else termIndex = 0; } return false; } // returns the first valid (long) integer value from the current position. // initial characters that are not digits (or the minus sign) are skipped // function is terminated by the first character that is not a digit. long Stream::parseInt() { return parseInt(NO_SKIP_CHAR); // terminate on first non-digit character (or timeout) } // as above but a given skipChar is ignored // this allows format characters (typically commas) in values to be ignored long Stream::parseInt(char skipChar) { boolean isNegative = false; long value = 0; int c; c = peekNextDigit(); // ignore non numeric leading characters if(c < 0) return 0; // zero returned if timeout do{ if(c == skipChar) ; // ignore this charactor else if(c == '-') isNegative = true; else if(c >= '0' && c <= '9') // is c a digit? value = value * 10 + c - '0'; read(); // consume the character we got with peek c = timedPeek(); } while( (c >= '0' && c <= '9') || c == skipChar ); if(isNegative) value = -value; return value; } // as parseInt but returns a floating point value float Stream::parseFloat() { return parseFloat(NO_SKIP_CHAR); } // as above but the given skipChar is ignored // this allows format characters (typically commas) in values to be ignored float Stream::parseFloat(char skipChar){ boolean isNegative = false; boolean isFraction = false; long value = 0; char c; float fraction = 1.0; c = peekNextDigit(); // ignore non numeric leading characters if(c < 0) return 0; // zero returned if timeout do{ if(c == skipChar) ; // ignore else if(c == '-') isNegative = true; else if (c == '.') isFraction = true; else if(c >= '0' && c <= '9') { // is c a digit? value = value * 10 + c - '0'; if(isFraction) fraction *= 0.1; } read(); // consume the character we got with peek c = timedPeek(); } while( (c >= '0' && c <= '9') || c == '.' || c == skipChar ); if(isNegative) value = -value; if(isFraction) return value * fraction; else return value; } // read characters from stream into buffer // terminates if length characters have been read, or timeout (see setTimeout) // returns the number of characters placed in the buffer // the buffer is NOT null terminated. // size_t Stream::readBytes(char *buffer, size_t length) { size_t count = 0; while (count < length) { int c = timedRead(); if (c < 0) break; *buffer++ = (char)c; count++; } return count; } // as readBytes with terminator character // terminates if length characters have been read, timeout, or if the terminator character detected // returns the number of characters placed in the buffer (0 means no valid data found) size_t Stream::readBytesUntil(char terminator, char *buffer, size_t length) { if (length < 1) return 0; size_t index = 0; while (index < length) { int c = timedRead(); if (c < 0 || c == terminator) break; *buffer++ = (char)c; index++; } return index; // return number of characters, not including null terminator } <|endoftext|>
<commit_before>#include <stdexcept> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/gpu/gpu.hpp> #include "performance.h" using namespace std; using namespace cv; INIT(matchTemplate) { Mat src; gen(src, 500, 500, CV_32F, 0, 1); Mat templ; gen(templ, 500, 500, CV_32F, 0, 1); gpu::GpuMat d_src(src), d_templ(templ), d_dst; gpu::matchTemplate(d_src, d_templ, d_dst, CV_TM_CCORR); } TEST(matchTemplate) { Mat src, templ, dst; gen(src, 3000, 3000, CV_32F, 0, 1); gpu::GpuMat d_src(src), d_templ, d_dst; for (int templ_size = 5; templ_size < 200; templ_size *= 5) { SUBTEST << "src " << src.rows << ", templ " << templ_size << ", 32F, CCORR"; gen(templ, templ_size, templ_size, CV_32F, 0, 1); dst.create(src.rows - templ.rows + 1, src.cols - templ.cols + 1, CV_32F); CPU_ON; matchTemplate(src, templ, dst, CV_TM_CCORR); CPU_OFF; d_templ = templ; d_dst.create(d_src.rows - d_templ.rows + 1, d_src.cols - d_templ.cols + 1, CV_32F); GPU_ON; gpu::matchTemplate(d_src, d_templ, d_dst, CV_TM_CCORR); GPU_OFF; } } TEST(minMaxLoc) { Mat src; gpu::GpuMat d_src; double min_val, max_val; Point min_loc, max_loc; for (int size = 2000; size <= 8000; size *= 2) { SUBTEST << "src " << size << ", 32F, no mask"; gen(src, size, size, CV_32F, 0, 1); CPU_ON; minMaxLoc(src, &min_val, &max_val, &min_loc, &max_loc); CPU_OFF; d_src = src; GPU_ON; gpu::minMaxLoc(d_src, &min_val, &max_val, &min_loc, &max_loc); GPU_OFF; } } TEST(remap) { Mat src, dst, xmap, ymap; gpu::GpuMat d_src, d_dst, d_xmap, d_ymap; for (int size = 1000; size <= 8000; size *= 2) { SUBTEST << "src " << size << " and 8U, 32F maps"; gen(src, size, size, CV_8UC1, 0, 256); xmap.create(size, size, CV_32F); ymap.create(size, size, CV_32F); for (int i = 0; i < size; ++i) { float* xmap_row = xmap.ptr<float>(i); float* ymap_row = ymap.ptr<float>(i); for (int j = 0; j < size; ++j) { xmap_row[j] = (j - size * 0.5f) * 0.75f + size * 0.5f; ymap_row[j] = (i - size * 0.5f) * 0.75f + size * 0.5f; } } dst.create(xmap.size(), src.type()); CPU_ON; remap(src, dst, xmap, ymap, INTER_LINEAR); CPU_OFF; d_src = src; d_xmap = xmap; d_ymap = ymap; d_dst.create(d_xmap.size(), d_src.type()); GPU_ON; gpu::remap(d_src, d_dst, d_xmap, d_ymap); GPU_OFF; } } TEST(dft) { Mat src, dst; gpu::GpuMat d_src, d_dst; for (int size = 1000; size <= 4000; size *= 2) { SUBTEST << "size " << size << ", 32FC2, complex-to-complex"; gen(src, size, size, CV_32FC2, Scalar::all(0), Scalar::all(1)); dst.create(src.size(), src.type()); CPU_ON; dft(src, dst); CPU_OFF; d_src = src; d_dst.create(d_src.size(), d_src.type()); GPU_ON; gpu::dft(d_src, d_dst, Size(size, size)); GPU_OFF; } } TEST(cornerHarris) { Mat src, dst; gpu::GpuMat d_src, d_dst; for (int size = 2000; size <= 4000; size *= 2) { SUBTEST << "size " << size << ", 32F"; gen(src, size, size, CV_32F, 0, 1); dst.create(src.size(), src.type()); CPU_ON; cornerHarris(src, dst, 5, 7, 0.1, BORDER_REFLECT101); CPU_OFF; d_src = src; d_dst.create(src.size(), src.type()); GPU_ON; gpu::cornerHarris(d_src, d_dst, 5, 7, 0.1, BORDER_REFLECT101); GPU_OFF; } } TEST(integral) { Mat src, sum; gpu::GpuMat d_src, d_sum; for (int size = 1000; size <= 8000; size *= 2) { SUBTEST << "size " << size << ", 8U"; gen(src, size, size, CV_8U, 0, 256); sum.create(size + 1, size + 1, CV_32S); CPU_ON; integral(src, sum); CPU_OFF; d_src = src; d_sum.create(size + 1, size + 1, CV_32S); GPU_ON; gpu::integral(d_src, d_sum); GPU_OFF; } } TEST(norm) { Mat src; gpu::GpuMat d_src; for (int size = 1000; size <= 8000; size *= 2) { SUBTEST << "size " << size << ", 8U"; gen(src, size, size, CV_8U, 0, 256); CPU_ON; norm(src); CPU_OFF; d_src = src; GPU_ON; gpu::norm(d_src); GPU_OFF; } } TEST(meanShift) { int sp = 10, sr = 10; Mat src, dst; gpu::GpuMat d_src, d_dst; for (int size = 400; size <= 800; size *= 2) { SUBTEST << "size " << size << ", 8UC3 vs 8UC4"; gen(src, size, size, CV_8UC3, Scalar::all(0), Scalar::all(256)); dst.create(src.size(), src.type()); CPU_ON; pyrMeanShiftFiltering(src, dst, sp, sr); CPU_OFF; gen(src, size, size, CV_8UC4, Scalar::all(0), Scalar::all(256)); d_src = src; d_dst.create(d_src.size(), d_src.type()); GPU_ON; gpu::meanShiftFiltering(d_src, d_dst, sp, sr); GPU_OFF; } } TEST(SURF) { Mat src1 = imread(abspath("bowlingL.png"), CV_LOAD_IMAGE_GRAYSCALE); Mat src2 = imread(abspath("bowlingR.png"), CV_LOAD_IMAGE_GRAYSCALE); if (src1.empty()) throw runtime_error("can't open bowlingL.png"); if (src2.empty()) throw runtime_error("can't open bowlingR.png"); gpu::GpuMat d_src1(src1); gpu::GpuMat d_src2(src2); SURF surf; vector<KeyPoint> keypoints1, keypoints2; CPU_ON; surf(src1, Mat(), keypoints1); surf(src2, Mat(), keypoints2); CPU_OFF; gpu::SURF_GPU d_surf; gpu::GpuMat d_keypoints1, d_keypoints2; gpu::GpuMat d_descriptors1, d_descriptors2; GPU_ON; d_surf(d_src1, gpu::GpuMat(), d_keypoints1); d_surf(d_src2, gpu::GpuMat(), d_keypoints2); GPU_OFF; } TEST(BruteForceMatcher) { // Init CPU matcher int desc_len = 128; BruteForceMatcher< L2<float> > matcher; Mat query; gen(query, 3000, desc_len, CV_32F, 0, 10); Mat train; gen(train, 3000, desc_len, CV_32F, 0, 10); // Init GPU matcher gpu::BruteForceMatcher_GPU< L2<float> > d_matcher; gpu::GpuMat d_query(query); gpu::GpuMat d_train(train); // Output vector< vector<DMatch> > matches(1); vector< vector<DMatch> > d_matches(1); SUBTEST << "match"; CPU_ON; matcher.match(query, train, matches[0]); CPU_OFF; GPU_ON; d_matcher.match(d_query, d_train, d_matches[0]); GPU_OFF; SUBTEST << "knnMatch"; int knn = 10; CPU_ON; matcher.knnMatch(query, train, matches, knn); CPU_OFF; GPU_ON; d_matcher.knnMatch(d_query, d_train, d_matches, knn); GPU_OFF; SUBTEST << "radiusMatch"; float max_distance = 45.0f; CPU_ON; matcher.radiusMatch(query, train, matches, max_distance); CPU_OFF; GPU_ON; d_matcher.radiusMatch(d_query, d_train, d_matches, max_distance); GPU_OFF; } TEST(magnitude) { Mat x, y, mag; gpu::GpuMat d_x, d_y, d_mag; for (int size = 2000; size <= 4000; size += 1000) { SUBTEST << "size " << size; gen(x, size, size, CV_32F, 0, 1); gen(y, size, size, CV_32F, 0, 1); mag.create(size, size, CV_32F); CPU_ON; magnitude(x, y, mag); CPU_OFF; d_x = x; d_y = y; d_mag.create(size, size, CV_32F); GPU_ON; gpu::magnitude(d_x, d_y, d_mag); GPU_OFF; } } TEST(add) { Mat src1, src2, dst; gpu::GpuMat d_src1, d_src2, d_dst; for (int size = 2000; size <= 4000; size += 1000) { SUBTEST << "size " << size << ", 32F"; gen(src1, size, size, CV_32F, 0, 1); gen(src2, size, size, CV_32F, 0, 1); dst.create(size, size, CV_32F); CPU_ON; add(src1, src2, dst); CPU_OFF; d_src1 = src1; d_src2 = src2; d_dst.create(size, size, CV_32F); GPU_ON; gpu::add(d_src1, d_src2, d_dst); GPU_OFF; } } TEST(log) { Mat src, dst; gpu::GpuMat d_src, d_dst; for (int size = 2000; size <= 4000; size += 1000) { SUBTEST << "size " << size << ", 32F"; gen(src, size, size, CV_32F, 1, 10); dst.create(size, size, CV_32F); CPU_ON; log(src, dst); CPU_OFF; d_src = src; d_dst.create(size, size, CV_32F); GPU_ON; gpu::log(d_src, d_dst); GPU_OFF; } } TEST(exp) { Mat src, dst; gpu::GpuMat d_src, d_dst; for (int size = 2000; size <= 4000; size += 1000) { SUBTEST << "size " << size << ", 32F"; gen(src, size, size, CV_32F, 0, 1); dst.create(size, size, CV_32F); CPU_ON; exp(src, dst); CPU_OFF; d_src = src; d_dst.create(size, size, CV_32F); GPU_ON; gpu::exp(d_src, d_dst); GPU_OFF; } }<commit_msg>added performance tests for mulSpectrum, resize, Sobel<commit_after>#include <stdexcept> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/gpu/gpu.hpp> #include "performance.h" using namespace std; using namespace cv; INIT(matchTemplate) { Mat src; gen(src, 500, 500, CV_32F, 0, 1); Mat templ; gen(templ, 500, 500, CV_32F, 0, 1); gpu::GpuMat d_src(src), d_templ(templ), d_dst; gpu::matchTemplate(d_src, d_templ, d_dst, CV_TM_CCORR); } TEST(matchTemplate) { Mat src, templ, dst; gen(src, 3000, 3000, CV_32F, 0, 1); gpu::GpuMat d_src(src), d_templ, d_dst; for (int templ_size = 5; templ_size < 200; templ_size *= 5) { SUBTEST << "src " << src.rows << ", templ " << templ_size << ", 32F, CCORR"; gen(templ, templ_size, templ_size, CV_32F, 0, 1); dst.create(src.rows - templ.rows + 1, src.cols - templ.cols + 1, CV_32F); CPU_ON; matchTemplate(src, templ, dst, CV_TM_CCORR); CPU_OFF; d_templ = templ; d_dst.create(d_src.rows - d_templ.rows + 1, d_src.cols - d_templ.cols + 1, CV_32F); GPU_ON; gpu::matchTemplate(d_src, d_templ, d_dst, CV_TM_CCORR); GPU_OFF; } } TEST(minMaxLoc) { Mat src; gpu::GpuMat d_src; double min_val, max_val; Point min_loc, max_loc; for (int size = 2000; size <= 8000; size *= 2) { SUBTEST << "src " << size << ", 32F, no mask"; gen(src, size, size, CV_32F, 0, 1); CPU_ON; minMaxLoc(src, &min_val, &max_val, &min_loc, &max_loc); CPU_OFF; d_src = src; GPU_ON; gpu::minMaxLoc(d_src, &min_val, &max_val, &min_loc, &max_loc); GPU_OFF; } } TEST(remap) { Mat src, dst, xmap, ymap; gpu::GpuMat d_src, d_dst, d_xmap, d_ymap; for (int size = 1000; size <= 8000; size *= 2) { SUBTEST << "src " << size << " and 8U, 32F maps"; gen(src, size, size, CV_8UC1, 0, 256); xmap.create(size, size, CV_32F); ymap.create(size, size, CV_32F); for (int i = 0; i < size; ++i) { float* xmap_row = xmap.ptr<float>(i); float* ymap_row = ymap.ptr<float>(i); for (int j = 0; j < size; ++j) { xmap_row[j] = (j - size * 0.5f) * 0.75f + size * 0.5f; ymap_row[j] = (i - size * 0.5f) * 0.75f + size * 0.5f; } } dst.create(xmap.size(), src.type()); CPU_ON; remap(src, dst, xmap, ymap, INTER_LINEAR); CPU_OFF; d_src = src; d_xmap = xmap; d_ymap = ymap; d_dst.create(d_xmap.size(), d_src.type()); GPU_ON; gpu::remap(d_src, d_dst, d_xmap, d_ymap); GPU_OFF; } } TEST(dft) { Mat src, dst; gpu::GpuMat d_src, d_dst; for (int size = 1000; size <= 4000; size *= 2) { SUBTEST << "size " << size << ", 32FC2, complex-to-complex"; gen(src, size, size, CV_32FC2, Scalar::all(0), Scalar::all(1)); dst.create(src.size(), src.type()); CPU_ON; dft(src, dst); CPU_OFF; d_src = src; d_dst.create(d_src.size(), d_src.type()); GPU_ON; gpu::dft(d_src, d_dst, Size(size, size)); GPU_OFF; } } TEST(cornerHarris) { Mat src, dst; gpu::GpuMat d_src, d_dst; for (int size = 2000; size <= 4000; size *= 2) { SUBTEST << "size " << size << ", 32F"; gen(src, size, size, CV_32F, 0, 1); dst.create(src.size(), src.type()); CPU_ON; cornerHarris(src, dst, 5, 7, 0.1, BORDER_REFLECT101); CPU_OFF; d_src = src; d_dst.create(src.size(), src.type()); GPU_ON; gpu::cornerHarris(d_src, d_dst, 5, 7, 0.1, BORDER_REFLECT101); GPU_OFF; } } TEST(integral) { Mat src, sum; gpu::GpuMat d_src, d_sum; for (int size = 1000; size <= 8000; size *= 2) { SUBTEST << "size " << size << ", 8U"; gen(src, size, size, CV_8U, 0, 256); sum.create(size + 1, size + 1, CV_32S); CPU_ON; integral(src, sum); CPU_OFF; d_src = src; d_sum.create(size + 1, size + 1, CV_32S); GPU_ON; gpu::integral(d_src, d_sum); GPU_OFF; } } TEST(norm) { Mat src; gpu::GpuMat d_src; for (int size = 1000; size <= 8000; size *= 2) { SUBTEST << "size " << size << ", 8U"; gen(src, size, size, CV_8U, 0, 256); CPU_ON; norm(src); CPU_OFF; d_src = src; GPU_ON; gpu::norm(d_src); GPU_OFF; } } TEST(meanShift) { int sp = 10, sr = 10; Mat src, dst; gpu::GpuMat d_src, d_dst; for (int size = 400; size <= 800; size *= 2) { SUBTEST << "size " << size << ", 8UC3 vs 8UC4"; gen(src, size, size, CV_8UC3, Scalar::all(0), Scalar::all(256)); dst.create(src.size(), src.type()); CPU_ON; pyrMeanShiftFiltering(src, dst, sp, sr); CPU_OFF; gen(src, size, size, CV_8UC4, Scalar::all(0), Scalar::all(256)); d_src = src; d_dst.create(d_src.size(), d_src.type()); GPU_ON; gpu::meanShiftFiltering(d_src, d_dst, sp, sr); GPU_OFF; } } TEST(SURF) { Mat src1 = imread(abspath("bowlingL.png"), CV_LOAD_IMAGE_GRAYSCALE); Mat src2 = imread(abspath("bowlingR.png"), CV_LOAD_IMAGE_GRAYSCALE); if (src1.empty()) throw runtime_error("can't open bowlingL.png"); if (src2.empty()) throw runtime_error("can't open bowlingR.png"); gpu::GpuMat d_src1(src1); gpu::GpuMat d_src2(src2); SURF surf; vector<KeyPoint> keypoints1, keypoints2; CPU_ON; surf(src1, Mat(), keypoints1); surf(src2, Mat(), keypoints2); CPU_OFF; gpu::SURF_GPU d_surf; gpu::GpuMat d_keypoints1, d_keypoints2; gpu::GpuMat d_descriptors1, d_descriptors2; GPU_ON; d_surf(d_src1, gpu::GpuMat(), d_keypoints1); d_surf(d_src2, gpu::GpuMat(), d_keypoints2); GPU_OFF; } TEST(BruteForceMatcher) { // Init CPU matcher int desc_len = 128; BruteForceMatcher< L2<float> > matcher; Mat query; gen(query, 3000, desc_len, CV_32F, 0, 10); Mat train; gen(train, 3000, desc_len, CV_32F, 0, 10); // Init GPU matcher gpu::BruteForceMatcher_GPU< L2<float> > d_matcher; gpu::GpuMat d_query(query); gpu::GpuMat d_train(train); // Output vector< vector<DMatch> > matches(1); vector< vector<DMatch> > d_matches(1); SUBTEST << "match"; CPU_ON; matcher.match(query, train, matches[0]); CPU_OFF; GPU_ON; d_matcher.match(d_query, d_train, d_matches[0]); GPU_OFF; SUBTEST << "knnMatch"; int knn = 10; CPU_ON; matcher.knnMatch(query, train, matches, knn); CPU_OFF; GPU_ON; d_matcher.knnMatch(d_query, d_train, d_matches, knn); GPU_OFF; SUBTEST << "radiusMatch"; float max_distance = 45.0f; CPU_ON; matcher.radiusMatch(query, train, matches, max_distance); CPU_OFF; GPU_ON; d_matcher.radiusMatch(d_query, d_train, d_matches, max_distance); GPU_OFF; } TEST(magnitude) { Mat x, y, mag; gpu::GpuMat d_x, d_y, d_mag; for (int size = 2000; size <= 4000; size += 1000) { SUBTEST << "size " << size; gen(x, size, size, CV_32F, 0, 1); gen(y, size, size, CV_32F, 0, 1); mag.create(size, size, CV_32F); CPU_ON; magnitude(x, y, mag); CPU_OFF; d_x = x; d_y = y; d_mag.create(size, size, CV_32F); GPU_ON; gpu::magnitude(d_x, d_y, d_mag); GPU_OFF; } } TEST(add) { Mat src1, src2, dst; gpu::GpuMat d_src1, d_src2, d_dst; for (int size = 2000; size <= 4000; size += 1000) { SUBTEST << "size " << size << ", 32F"; gen(src1, size, size, CV_32F, 0, 1); gen(src2, size, size, CV_32F, 0, 1); dst.create(size, size, CV_32F); CPU_ON; add(src1, src2, dst); CPU_OFF; d_src1 = src1; d_src2 = src2; d_dst.create(size, size, CV_32F); GPU_ON; gpu::add(d_src1, d_src2, d_dst); GPU_OFF; } } TEST(log) { Mat src, dst; gpu::GpuMat d_src, d_dst; for (int size = 2000; size <= 4000; size += 1000) { SUBTEST << "size " << size << ", 32F"; gen(src, size, size, CV_32F, 1, 10); dst.create(size, size, CV_32F); CPU_ON; log(src, dst); CPU_OFF; d_src = src; d_dst.create(size, size, CV_32F); GPU_ON; gpu::log(d_src, d_dst); GPU_OFF; } } TEST(exp) { Mat src, dst; gpu::GpuMat d_src, d_dst; for (int size = 2000; size <= 4000; size += 1000) { SUBTEST << "size " << size << ", 32F"; gen(src, size, size, CV_32F, 0, 1); dst.create(size, size, CV_32F); CPU_ON; exp(src, dst); CPU_OFF; d_src = src; d_dst.create(size, size, CV_32F); GPU_ON; gpu::exp(d_src, d_dst); GPU_OFF; } } TEST(mulSpectrums) { Mat src1, src2, dst; gpu::GpuMat d_src1, d_src2, d_dst; for (int size = 2000; size <= 4000; size += 1000) { SUBTEST << "size " << size; gen(src1, size, size, CV_32FC2, Scalar::all(0), Scalar::all(1)); gen(src2, size, size, CV_32FC2, Scalar::all(0), Scalar::all(1)); dst.create(size, size, CV_32FC2); CPU_ON; mulSpectrums(src1, src2, dst, 0, true); CPU_OFF; d_src1 = src1; d_src2 = src2; d_dst.create(size, size, CV_32FC2); GPU_ON; gpu::mulSpectrums(d_src1, d_src2, d_dst, 0, true); GPU_OFF; } } TEST(resize) { Mat src, dst; gpu::GpuMat d_src, d_dst; for (int size = 1000; size <= 3000; size += 1000) { SUBTEST << "size " << size; gen(src, size, size, CV_8U, 0, 256); dst.create(size * 2, size * 2, CV_8U); CPU_ON; resize(src, dst, dst.size()); CPU_OFF; d_src = src; d_dst.create(size * 2, size * 2, CV_8U); GPU_ON; gpu::resize(d_src, d_dst, d_dst.size()); GPU_OFF; } } TEST(Sobel) { Mat src, dst; gpu::GpuMat d_src, d_dst; for (int size = 2000; size <= 4000; size += 1000) { SUBTEST << "size " << size << ", 32F"; gen(src, size, size, CV_32F, 0, 1); dst.create(size, size, CV_32F); CPU_ON; Sobel(src, dst, dst.depth(), 1, 1); CPU_OFF; d_src = src; d_dst.create(size, size, CV_32F); GPU_ON; gpu::Sobel(d_src, d_dst, d_dst.depth(), 1, 1); GPU_OFF; } }<|endoftext|>
<commit_before>#pragma once #include "depthai-shared/common/ProcessorType.hpp" #include "depthai-shared/common/optional.hpp" #include "depthai-shared/properties/Properties.hpp" namespace dai { /** * Specify ScriptProperties options such as script uri, script name, ... */ struct ScriptProperties : PropertiesSerializable<Properties, ScriptProperties> { /** * Uri which points to actual script */ std::string scriptUri = ""; /** * Name of script */ std::string scriptName = "<script>"; /** * Which processor should execute the script */ ProcessorType processor = ProcessorType::LEON_CSS; }; DEPTHAI_SERIALIZE_EXT(ScriptProperties, scriptUri, scriptName, processor); } // namespace dai <commit_msg>remove empty string initializer<commit_after>#pragma once #include "depthai-shared/common/ProcessorType.hpp" #include "depthai-shared/common/optional.hpp" #include "depthai-shared/properties/Properties.hpp" namespace dai { /** * Specify ScriptProperties options such as script uri, script name, ... */ struct ScriptProperties : PropertiesSerializable<Properties, ScriptProperties> { /** * Uri which points to actual script */ std::string scriptUri; /** * Name of script */ std::string scriptName = "<script>"; /** * Which processor should execute the script */ ProcessorType processor = ProcessorType::LEON_CSS; }; DEPTHAI_SERIALIZE_EXT(ScriptProperties, scriptUri, scriptName, processor); } // namespace dai <|endoftext|>
<commit_before>#ifndef OSRM_ENGINE_ROUTING_BASE_MLD_HPP #define OSRM_ENGINE_ROUTING_BASE_MLD_HPP #include "engine/algorithm.hpp" #include "engine/datafacade/contiguous_internalmem_datafacade.hpp" #include "engine/routing_algorithms/routing_base.hpp" #include "engine/search_engine_data.hpp" #include "util/typedefs.hpp" #include <boost/assert.hpp> namespace osrm { namespace engine { namespace routing_algorithms { namespace mld { namespace { // Unrestricted search (Args is const PhantomNodes &): // * use partition.GetQueryLevel to find the node query level based on source and target phantoms // * allow to traverse all cells inline LevelID getNodeQureyLevel(const partition::MultiLevelPartitionView &partition, NodeID node, const PhantomNodes &phantom_nodes) { auto level = [&partition, node](const SegmentID &source, const SegmentID &target) { if (source.enabled && target.enabled) return partition.GetQueryLevel(source.id, target.id, node); return INVALID_LEVEL_ID; }; return std::min(std::min(level(phantom_nodes.source_phantom.forward_segment_id, phantom_nodes.target_phantom.forward_segment_id), level(phantom_nodes.source_phantom.forward_segment_id, phantom_nodes.target_phantom.reverse_segment_id)), std::min(level(phantom_nodes.source_phantom.reverse_segment_id, phantom_nodes.target_phantom.forward_segment_id), level(phantom_nodes.source_phantom.reverse_segment_id, phantom_nodes.target_phantom.reverse_segment_id))); } inline bool checkParentCellRestriction(CellID, const PhantomNodes &) { return true; } // Restricted search (Args is LevelID, CellID): // * use the fixed level for queries // * check if the node cell is the same as the specified parent onr inline LevelID getNodeQureyLevel(const partition::MultiLevelPartitionView &, NodeID, LevelID level, CellID) { return level; } inline bool checkParentCellRestriction(CellID cell, LevelID, CellID parent) { return cell == parent; } } template <bool DIRECTION, typename... Args> void routingStep(const datafacade::ContiguousInternalMemoryDataFacade<Algorithm> &facade, SearchEngineData<Algorithm>::QueryHeap &forward_heap, SearchEngineData<Algorithm>::QueryHeap &reverse_heap, NodeID &middle_node, EdgeWeight &path_upper_bound, const bool force_loop_forward, const bool force_loop_reverse, Args... args) { const auto &partition = facade.GetMultiLevelPartition(); const auto &cells = facade.GetCellStorage(); const auto node = forward_heap.DeleteMin(); const auto weight = forward_heap.GetKey(node); // Upper bound for the path source -> target with // weight(source -> node) = weight weight(to -> target) ≤ reverse_weight // is weight + reverse_weight // More tighter upper bound requires additional condition reverse_heap.WasRemoved(to) // with weight(to -> target) = reverse_weight and all weights ≥ 0 if (reverse_heap.WasInserted(node)) { auto reverse_weight = reverse_heap.GetKey(node); auto path_weight = weight + reverse_weight; // if loops are forced, they are so at the source if (!(force_loop_forward && forward_heap.GetData(node).parent == node) && !(force_loop_reverse && reverse_heap.GetData(node).parent == node) && (path_weight >= 0) && (path_weight < path_upper_bound)) { middle_node = node; path_upper_bound = path_weight; } } const auto level = getNodeQureyLevel(partition, node, args...); if (level >= 1 && !forward_heap.GetData(node).from_clique_arc) { if (DIRECTION == FORWARD_DIRECTION) { // Shortcuts in forward direction const auto &cell = cells.GetCell(level, partition.GetCell(level, node)); auto destination = cell.GetDestinationNodes().begin(); for (auto shortcut_weight : cell.GetOutWeight(node)) { BOOST_ASSERT(destination != cell.GetDestinationNodes().end()); const NodeID to = *destination; if (shortcut_weight != INVALID_EDGE_WEIGHT && node != to) { const EdgeWeight to_weight = weight + shortcut_weight; if (!forward_heap.WasInserted(to)) { forward_heap.Insert(to, to_weight, {node, true}); } else if (to_weight < forward_heap.GetKey(to)) { forward_heap.GetData(to) = {node, true}; forward_heap.DecreaseKey(to, to_weight); } } ++destination; } } else { // Shortcuts in backward direction const auto &cell = cells.GetCell(level, partition.GetCell(level, node)); auto source = cell.GetSourceNodes().begin(); for (auto shortcut_weight : cell.GetInWeight(node)) { BOOST_ASSERT(source != cell.GetSourceNodes().end()); const NodeID to = *source; if (shortcut_weight != INVALID_EDGE_WEIGHT && node != to) { const EdgeWeight to_weight = weight + shortcut_weight; if (!forward_heap.WasInserted(to)) { forward_heap.Insert(to, to_weight, {node, true}); } else if (to_weight < forward_heap.GetKey(to)) { forward_heap.GetData(to) = {node, true}; forward_heap.DecreaseKey(to, to_weight); } } ++source; } } } // Boundary edges for (const auto edge : facade.GetBorderEdgeRange(level, node)) { const auto &edge_data = facade.GetEdgeData(edge); if (DIRECTION == FORWARD_DIRECTION ? edge_data.forward : edge_data.backward) { const NodeID to = facade.GetTarget(edge); if (checkParentCellRestriction(partition.GetCell(level + 1, to), args...)) { BOOST_ASSERT_MSG(edge_data.weight > 0, "edge_weight invalid"); const EdgeWeight to_weight = weight + edge_data.weight; if (!forward_heap.WasInserted(to)) { forward_heap.Insert(to, to_weight, {node, false}); } else if (to_weight < forward_heap.GetKey(to)) { forward_heap.GetData(to) = {node, false}; forward_heap.DecreaseKey(to, to_weight); } } } } } template <typename... Args> std::tuple<EdgeWeight, std::vector<NodeID>, std::vector<EdgeID>> search(SearchEngineData<Algorithm> &engine_working_data, const datafacade::ContiguousInternalMemoryDataFacade<Algorithm> &facade, SearchEngineData<Algorithm>::QueryHeap &forward_heap, SearchEngineData<Algorithm>::QueryHeap &reverse_heap, const bool force_loop_forward, const bool force_loop_reverse, EdgeWeight weight_upper_bound, Args... args) { const auto &partition = facade.GetMultiLevelPartition(); BOOST_ASSERT(!forward_heap.Empty() && forward_heap.MinKey() < INVALID_EDGE_WEIGHT); BOOST_ASSERT(!reverse_heap.Empty() && reverse_heap.MinKey() < INVALID_EDGE_WEIGHT); // run two-Target Dijkstra routing step. NodeID middle = SPECIAL_NODEID; EdgeWeight weight = weight_upper_bound; EdgeWeight forward_heap_min = forward_heap.MinKey(); EdgeWeight reverse_heap_min = reverse_heap.MinKey(); while (forward_heap.Size() + reverse_heap.Size() > 0 && forward_heap_min + reverse_heap_min < weight) { if (!forward_heap.Empty()) { routingStep<FORWARD_DIRECTION>(facade, forward_heap, reverse_heap, middle, weight, force_loop_forward, force_loop_reverse, args...); if (!forward_heap.Empty()) forward_heap_min = forward_heap.MinKey(); } if (!reverse_heap.Empty()) { routingStep<REVERSE_DIRECTION>(facade, reverse_heap, forward_heap, middle, weight, force_loop_reverse, force_loop_forward, args...); if (!reverse_heap.Empty()) reverse_heap_min = reverse_heap.MinKey(); } }; // No path found for both target nodes? if (weight >= weight_upper_bound || SPECIAL_NODEID == middle) { return std::make_tuple(INVALID_EDGE_WEIGHT, std::vector<NodeID>(), std::vector<EdgeID>()); } // Get packed path as edges {from node ID, to node ID, edge ID} std::vector<std::tuple<NodeID, NodeID, bool>> packed_path; NodeID current_node = middle, parent_node = forward_heap.GetData(middle).parent; while (parent_node != current_node) { const auto &data = forward_heap.GetData(current_node); packed_path.push_back(std::make_tuple(parent_node, current_node, data.from_clique_arc)); current_node = parent_node; parent_node = forward_heap.GetData(parent_node).parent; } std::reverse(std::begin(packed_path), std::end(packed_path)); const NodeID source_node = current_node; current_node = middle, parent_node = reverse_heap.GetData(middle).parent; while (parent_node != current_node) { const auto &data = reverse_heap.GetData(current_node); packed_path.push_back(std::make_tuple(current_node, parent_node, data.from_clique_arc)); current_node = parent_node; parent_node = reverse_heap.GetData(parent_node).parent; } // Unpack path std::vector<NodeID> unpacked_nodes; std::vector<EdgeID> unpacked_edges; unpacked_nodes.reserve(packed_path.size()); unpacked_edges.reserve(packed_path.size()); unpacked_nodes.push_back(source_node); for (auto const &packed_edge : packed_path) { NodeID source, target; bool overlay_edge; std::tie(source, target, overlay_edge) = packed_edge; if (!overlay_edge) { // a base graph edge unpacked_nodes.push_back(target); unpacked_edges.push_back(facade.FindEdge(source, target)); } else { // an overlay graph edge LevelID level = getNodeQureyLevel(partition, source, args...); CellID parent_cell_id = partition.GetCell(level, source); BOOST_ASSERT(parent_cell_id == partition.GetCell(level, target)); LevelID sublevel = level - 1; // Here heaps can be reused, let's go deeper! forward_heap.Clear(); reverse_heap.Clear(); forward_heap.Insert(source, 0, {source}); reverse_heap.Insert(target, 0, {target}); // TODO: when structured bindings will be allowed change to // auto [subpath_weight, subpath_source, subpath_target, subpath] = ... EdgeWeight subpath_weight; std::vector<NodeID> subpath_nodes; std::vector<EdgeID> subpath_edges; std::tie(subpath_weight, subpath_nodes, subpath_edges) = search(engine_working_data, facade, forward_heap, reverse_heap, force_loop_forward, force_loop_reverse, INVALID_EDGE_WEIGHT, sublevel, parent_cell_id); BOOST_ASSERT(!subpath_edges.empty()); BOOST_ASSERT(subpath_nodes.size() > 1); BOOST_ASSERT(subpath_nodes.front() == source); BOOST_ASSERT(subpath_nodes.back() == target); unpacked_nodes.insert( unpacked_nodes.end(), std::next(subpath_nodes.begin()), subpath_nodes.end()); unpacked_edges.insert(unpacked_edges.end(), subpath_edges.begin(), subpath_edges.end()); } } return std::make_tuple(weight, std::move(unpacked_nodes), std::move(unpacked_edges)); } // TODO reorder parameters // Alias to be compatible with the overload for CoreCH that needs 4 heaps for shortest path search inline void search(SearchEngineData<Algorithm> &engine_working_data, const datafacade::ContiguousInternalMemoryDataFacade<Algorithm> &facade, SearchEngineData<Algorithm>::QueryHeap &forward_heap, SearchEngineData<Algorithm>::QueryHeap &reverse_heap, EdgeWeight &weight, std::vector<NodeID> &packed_leg, const bool force_loop_forward, const bool force_loop_reverse, const PhantomNodes &phantom_nodes, const EdgeWeight weight_upper_bound = INVALID_EDGE_WEIGHT) { // TODO: change search calling interface to use unpacked_edges result std::tie(weight, packed_leg, std::ignore) = mld::search(engine_working_data, facade, forward_heap, reverse_heap, force_loop_forward, force_loop_reverse, weight_upper_bound, phantom_nodes); } // TODO: remove CH-related stub template <typename RandomIter, typename FacadeT> void unpackPath(const FacadeT &facade, RandomIter packed_path_begin, RandomIter packed_path_end, const PhantomNodes &phantom_nodes, std::vector<PathData> &unpacked_path) { const auto nodes_number = std::distance(packed_path_begin, packed_path_end); BOOST_ASSERT(nodes_number > 0); std::vector<NodeID> unpacked_nodes; std::vector<EdgeID> unpacked_edges; unpacked_nodes.reserve(nodes_number); unpacked_edges.reserve(nodes_number); unpacked_nodes.push_back(*packed_path_begin); if (nodes_number > 1) { util::for_each_pair( packed_path_begin, packed_path_end, [&facade, &unpacked_nodes, &unpacked_edges](const auto from, const auto to) { unpacked_nodes.push_back(to); unpacked_edges.push_back(facade.FindEdge(from, to)); }); } annotatePath(facade, phantom_nodes, unpacked_nodes, unpacked_edges, unpacked_path); } inline double getNetworkDistance(SearchEngineData<Algorithm> &engine_working_data, const datafacade::ContiguousInternalMemoryDataFacade<Algorithm> &facade, SearchEngineData<Algorithm>::QueryHeap &forward_heap, SearchEngineData<Algorithm>::QueryHeap &reverse_heap, const PhantomNode &source_phantom, const PhantomNode &target_phantom, EdgeWeight weight_upper_bound = INVALID_EDGE_WEIGHT) { forward_heap.Clear(); reverse_heap.Clear(); const PhantomNodes phantom_nodes{source_phantom, target_phantom}; insertNodesInHeaps(forward_heap, reverse_heap, phantom_nodes); EdgeWeight weight; std::vector<NodeID> unpacked_nodes; std::vector<EdgeID> unpacked_edges; std::tie(weight, unpacked_nodes, unpacked_edges) = search(engine_working_data, facade, forward_heap, reverse_heap, DO_NOT_FORCE_LOOPS, DO_NOT_FORCE_LOOPS, weight_upper_bound, phantom_nodes); if (weight == INVALID_EDGE_WEIGHT) return std::numeric_limits<double>::max(); std::vector<PathData> unpacked_path; annotatePath(facade, phantom_nodes, unpacked_nodes, unpacked_edges, unpacked_path); return getPathDistance(facade, unpacked_path, source_phantom, target_phantom); } } // namespace mld } // namespace routing_algorithms } // namespace engine } // namespace osrm #endif // OSRM_ENGINE_ROUTING_BASE_MLD_HPP <commit_msg>Fix minor review comments<commit_after>#ifndef OSRM_ENGINE_ROUTING_BASE_MLD_HPP #define OSRM_ENGINE_ROUTING_BASE_MLD_HPP #include "engine/algorithm.hpp" #include "engine/datafacade/contiguous_internalmem_datafacade.hpp" #include "engine/routing_algorithms/routing_base.hpp" #include "engine/search_engine_data.hpp" #include "util/typedefs.hpp" #include <boost/assert.hpp> namespace osrm { namespace engine { namespace routing_algorithms { namespace mld { namespace { // Unrestricted search (Args is const PhantomNodes &): // * use partition.GetQueryLevel to find the node query level based on source and target phantoms // * allow to traverse all cells inline LevelID getNodeQureyLevel(const partition::MultiLevelPartitionView &partition, NodeID node, const PhantomNodes &phantom_nodes) { auto level = [&partition, node](const SegmentID &source, const SegmentID &target) { if (source.enabled && target.enabled) return partition.GetQueryLevel(source.id, target.id, node); return INVALID_LEVEL_ID; }; return std::min(std::min(level(phantom_nodes.source_phantom.forward_segment_id, phantom_nodes.target_phantom.forward_segment_id), level(phantom_nodes.source_phantom.forward_segment_id, phantom_nodes.target_phantom.reverse_segment_id)), std::min(level(phantom_nodes.source_phantom.reverse_segment_id, phantom_nodes.target_phantom.forward_segment_id), level(phantom_nodes.source_phantom.reverse_segment_id, phantom_nodes.target_phantom.reverse_segment_id))); } inline bool checkParentCellRestriction(CellID, const PhantomNodes &) { return true; } // Restricted search (Args is LevelID, CellID): // * use the fixed level for queries // * check if the node cell is the same as the specified parent onr inline LevelID getNodeQureyLevel(const partition::MultiLevelPartitionView &, NodeID, LevelID level, CellID) { return level; } inline bool checkParentCellRestriction(CellID cell, LevelID, CellID parent) { return cell == parent; } } template <bool DIRECTION, typename... Args> void routingStep(const datafacade::ContiguousInternalMemoryDataFacade<Algorithm> &facade, SearchEngineData<Algorithm>::QueryHeap &forward_heap, SearchEngineData<Algorithm>::QueryHeap &reverse_heap, NodeID &middle_node, EdgeWeight &path_upper_bound, const bool force_loop_forward, const bool force_loop_reverse, Args... args) { const auto &partition = facade.GetMultiLevelPartition(); const auto &cells = facade.GetCellStorage(); const auto node = forward_heap.DeleteMin(); const auto weight = forward_heap.GetKey(node); // Upper bound for the path source -> target with // weight(source -> node) = weight weight(to -> target) ≤ reverse_weight // is weight + reverse_weight // More tighter upper bound requires additional condition reverse_heap.WasRemoved(to) // with weight(to -> target) = reverse_weight and all weights ≥ 0 if (reverse_heap.WasInserted(node)) { auto reverse_weight = reverse_heap.GetKey(node); auto path_weight = weight + reverse_weight; // if loops are forced, they are so at the source if (!(force_loop_forward && forward_heap.GetData(node).parent == node) && !(force_loop_reverse && reverse_heap.GetData(node).parent == node) && (path_weight >= 0) && (path_weight < path_upper_bound)) { middle_node = node; path_upper_bound = path_weight; } } const auto level = getNodeQureyLevel(partition, node, args...); if (level >= 1 && !forward_heap.GetData(node).from_clique_arc) { if (DIRECTION == FORWARD_DIRECTION) { // Shortcuts in forward direction const auto &cell = cells.GetCell(level, partition.GetCell(level, node)); auto destination = cell.GetDestinationNodes().begin(); for (auto shortcut_weight : cell.GetOutWeight(node)) { BOOST_ASSERT(destination != cell.GetDestinationNodes().end()); const NodeID to = *destination; if (shortcut_weight != INVALID_EDGE_WEIGHT && node != to) { const EdgeWeight to_weight = weight + shortcut_weight; if (!forward_heap.WasInserted(to)) { forward_heap.Insert(to, to_weight, {node, true}); } else if (to_weight < forward_heap.GetKey(to)) { forward_heap.GetData(to) = {node, true}; forward_heap.DecreaseKey(to, to_weight); } } ++destination; } } else { // Shortcuts in backward direction const auto &cell = cells.GetCell(level, partition.GetCell(level, node)); auto source = cell.GetSourceNodes().begin(); for (auto shortcut_weight : cell.GetInWeight(node)) { BOOST_ASSERT(source != cell.GetSourceNodes().end()); const NodeID to = *source; if (shortcut_weight != INVALID_EDGE_WEIGHT && node != to) { const EdgeWeight to_weight = weight + shortcut_weight; if (!forward_heap.WasInserted(to)) { forward_heap.Insert(to, to_weight, {node, true}); } else if (to_weight < forward_heap.GetKey(to)) { forward_heap.GetData(to) = {node, true}; forward_heap.DecreaseKey(to, to_weight); } } ++source; } } } // Boundary edges for (const auto edge : facade.GetBorderEdgeRange(level, node)) { const auto &edge_data = facade.GetEdgeData(edge); if (DIRECTION == FORWARD_DIRECTION ? edge_data.forward : edge_data.backward) { const NodeID to = facade.GetTarget(edge); if (checkParentCellRestriction(partition.GetCell(level + 1, to), args...)) { BOOST_ASSERT_MSG(edge_data.weight > 0, "edge_weight invalid"); const EdgeWeight to_weight = weight + edge_data.weight; if (!forward_heap.WasInserted(to)) { forward_heap.Insert(to, to_weight, {node, false}); } else if (to_weight < forward_heap.GetKey(to)) { forward_heap.GetData(to) = {node, false}; forward_heap.DecreaseKey(to, to_weight); } } } } } template <typename... Args> std::tuple<EdgeWeight, std::vector<NodeID>, std::vector<EdgeID>> search(SearchEngineData<Algorithm> &engine_working_data, const datafacade::ContiguousInternalMemoryDataFacade<Algorithm> &facade, SearchEngineData<Algorithm>::QueryHeap &forward_heap, SearchEngineData<Algorithm>::QueryHeap &reverse_heap, const bool force_loop_forward, const bool force_loop_reverse, EdgeWeight weight_upper_bound, Args... args) { const auto &partition = facade.GetMultiLevelPartition(); BOOST_ASSERT(!forward_heap.Empty() && forward_heap.MinKey() < INVALID_EDGE_WEIGHT); BOOST_ASSERT(!reverse_heap.Empty() && reverse_heap.MinKey() < INVALID_EDGE_WEIGHT); // run two-Target Dijkstra routing step. NodeID middle = SPECIAL_NODEID; EdgeWeight weight = weight_upper_bound; EdgeWeight forward_heap_min = forward_heap.MinKey(); EdgeWeight reverse_heap_min = reverse_heap.MinKey(); while (forward_heap.Size() + reverse_heap.Size() > 0 && forward_heap_min + reverse_heap_min < weight) { if (!forward_heap.Empty()) { routingStep<FORWARD_DIRECTION>(facade, forward_heap, reverse_heap, middle, weight, force_loop_forward, force_loop_reverse, args...); if (!forward_heap.Empty()) forward_heap_min = forward_heap.MinKey(); } if (!reverse_heap.Empty()) { routingStep<REVERSE_DIRECTION>(facade, reverse_heap, forward_heap, middle, weight, force_loop_reverse, force_loop_forward, args...); if (!reverse_heap.Empty()) reverse_heap_min = reverse_heap.MinKey(); } }; // No path found for both target nodes? if (weight >= weight_upper_bound || SPECIAL_NODEID == middle) { return std::make_tuple(INVALID_EDGE_WEIGHT, std::vector<NodeID>(), std::vector<EdgeID>()); } // Get packed path as edges {from node ID, to node ID, edge ID} std::vector<std::tuple<NodeID, NodeID, bool>> packed_path; NodeID current_node = middle, parent_node = forward_heap.GetData(middle).parent; while (parent_node != current_node) { const auto &data = forward_heap.GetData(current_node); packed_path.push_back(std::make_tuple(parent_node, current_node, data.from_clique_arc)); current_node = parent_node; parent_node = forward_heap.GetData(parent_node).parent; } std::reverse(std::begin(packed_path), std::end(packed_path)); const NodeID source_node = current_node; current_node = middle, parent_node = reverse_heap.GetData(middle).parent; while (parent_node != current_node) { const auto &data = reverse_heap.GetData(current_node); packed_path.push_back(std::make_tuple(current_node, parent_node, data.from_clique_arc)); current_node = parent_node; parent_node = reverse_heap.GetData(parent_node).parent; } // Unpack path std::vector<NodeID> unpacked_nodes; std::vector<EdgeID> unpacked_edges; unpacked_nodes.reserve(packed_path.size()); unpacked_edges.reserve(packed_path.size()); unpacked_nodes.push_back(source_node); for (auto const &packed_edge : packed_path) { NodeID source, target; bool overlay_edge; std::tie(source, target, overlay_edge) = packed_edge; if (!overlay_edge) { // a base graph edge unpacked_nodes.push_back(target); unpacked_edges.push_back(facade.FindEdge(source, target)); } else { // an overlay graph edge LevelID level = getNodeQureyLevel(partition, source, args...); CellID parent_cell_id = partition.GetCell(level, source); BOOST_ASSERT(parent_cell_id == partition.GetCell(level, target)); LevelID sublevel = level - 1; // Here heaps can be reused, let's go deeper! forward_heap.Clear(); reverse_heap.Clear(); forward_heap.Insert(source, 0, {source}); reverse_heap.Insert(target, 0, {target}); // TODO: when structured bindings will be allowed change to // auto [subpath_weight, subpath_source, subpath_target, subpath] = ... EdgeWeight subpath_weight; std::vector<NodeID> subpath_nodes; std::vector<EdgeID> subpath_edges; std::tie(subpath_weight, subpath_nodes, subpath_edges) = search(engine_working_data, facade, forward_heap, reverse_heap, force_loop_forward, force_loop_reverse, INVALID_EDGE_WEIGHT, sublevel, parent_cell_id); BOOST_ASSERT(!subpath_edges.empty()); BOOST_ASSERT(subpath_nodes.size() > 1); BOOST_ASSERT(subpath_nodes.front() == source); BOOST_ASSERT(subpath_nodes.back() == target); unpacked_nodes.insert( unpacked_nodes.end(), std::next(subpath_nodes.begin()), subpath_nodes.end()); unpacked_edges.insert(unpacked_edges.end(), subpath_edges.begin(), subpath_edges.end()); } } return std::make_tuple(weight, std::move(unpacked_nodes), std::move(unpacked_edges)); } // Alias to be compatible with the CH-based search inline void search(SearchEngineData<Algorithm> &engine_working_data, const datafacade::ContiguousInternalMemoryDataFacade<Algorithm> &facade, SearchEngineData<Algorithm>::QueryHeap &forward_heap, SearchEngineData<Algorithm>::QueryHeap &reverse_heap, EdgeWeight &weight, std::vector<NodeID> &unpacked_nodes, const bool force_loop_forward, const bool force_loop_reverse, const PhantomNodes &phantom_nodes, const EdgeWeight weight_upper_bound = INVALID_EDGE_WEIGHT) { // TODO: change search calling interface to use unpacked_edges result std::tie(weight, unpacked_nodes, std::ignore) = search(engine_working_data, facade, forward_heap, reverse_heap, force_loop_forward, force_loop_reverse, weight_upper_bound, phantom_nodes); } // TODO: refactor CH-related stub to use unpacked_edges template <typename RandomIter, typename FacadeT> void unpackPath(const FacadeT &facade, RandomIter packed_path_begin, RandomIter packed_path_end, const PhantomNodes &phantom_nodes, std::vector<PathData> &unpacked_path) { const auto nodes_number = std::distance(packed_path_begin, packed_path_end); BOOST_ASSERT(nodes_number > 0); std::vector<NodeID> unpacked_nodes; std::vector<EdgeID> unpacked_edges; unpacked_nodes.reserve(nodes_number); unpacked_edges.reserve(nodes_number); unpacked_nodes.push_back(*packed_path_begin); if (nodes_number > 1) { util::for_each_pair( packed_path_begin, packed_path_end, [&facade, &unpacked_nodes, &unpacked_edges](const auto from, const auto to) { unpacked_nodes.push_back(to); unpacked_edges.push_back(facade.FindEdge(from, to)); }); } annotatePath(facade, phantom_nodes, unpacked_nodes, unpacked_edges, unpacked_path); } inline double getNetworkDistance(SearchEngineData<Algorithm> &engine_working_data, const datafacade::ContiguousInternalMemoryDataFacade<Algorithm> &facade, SearchEngineData<Algorithm>::QueryHeap &forward_heap, SearchEngineData<Algorithm>::QueryHeap &reverse_heap, const PhantomNode &source_phantom, const PhantomNode &target_phantom, EdgeWeight weight_upper_bound = INVALID_EDGE_WEIGHT) { forward_heap.Clear(); reverse_heap.Clear(); const PhantomNodes phantom_nodes{source_phantom, target_phantom}; insertNodesInHeaps(forward_heap, reverse_heap, phantom_nodes); EdgeWeight weight; std::vector<NodeID> unpacked_nodes; std::vector<EdgeID> unpacked_edges; std::tie(weight, unpacked_nodes, unpacked_edges) = search(engine_working_data, facade, forward_heap, reverse_heap, DO_NOT_FORCE_LOOPS, DO_NOT_FORCE_LOOPS, weight_upper_bound, phantom_nodes); if (weight == INVALID_EDGE_WEIGHT) return std::numeric_limits<double>::max(); std::vector<PathData> unpacked_path; annotatePath(facade, phantom_nodes, unpacked_nodes, unpacked_edges, unpacked_path); return getPathDistance(facade, unpacked_path, source_phantom, target_phantom); } } // namespace mld } // namespace routing_algorithms } // namespace engine } // namespace osrm #endif // OSRM_ENGINE_ROUTING_BASE_MLD_HPP <|endoftext|>
<commit_before> #include "expressiongraph_wbf/solver/constraints.hpp" #include "expressiongraph_wbf/solver/controller_base.hpp" #include <qpOASES/SQProblem.hpp> //#include <map> using namespace wbf; using namespace std; using namespace KDL; namespace wbf { class velocity_solver{ private: std::vector<int> joint_indexes; int time_index; unsigned int n_of_joints; unsigned int n_of_output; c_map_type c_map; Eigen::MatrixXd J; Eigen::MatrixXd Jt; Eigen::MatrixXd J1,J3,J6; Eigen::VectorXd lambda_des; Eigen::VectorXd lambda1,lambda3,lambda6; qpOASES::SQProblem QP; ///< QP Solver bool prepared; /* int Compute(const std::vector<double> &q_in, double time, Eigen::VectorXd &tau_out,bool time_present);*/ public: velocity_solver( const std::vector<int>& joint_indexes, const int time_index=-1 ); velocity_solver(); /* void setJointIndex(const std::vector<int>&indx); void setTimeIndex(const int); bool addConstraint(const std::string& name, const constraint &c); bool addConstraint(const std::string& name, const constraint::Ptr &c); bool RemoveConstraint(const std::string &s); int Prepare(); int Compute(const std::vector<double> &q_in, double time, Eigen::VectorXd &tau_out); int Compute(const std::vector<double> &q_in,Eigen::VectorXd &tau_out); //memory assignment copy... Eigen::VectorXd getLastDesiredForce(){return lambda_des;}; */ typedef boost::shared_ptr<velocity_solver> Ptr; }; } <commit_msg>initial commmit vel<commit_after> #include "expressiongraph_wbf/solver/constraints.hpp" #include "expressiongraph_wbf/solver/controller_base.hpp" #include <qpOASES/SQProblem.hpp> //#include <map> using namespace wbf; using namespace std; using namespace KDL; namespace wbf { class velocity_solver{ private: std::vector<int> joint_indexes; int time_index; unsigned int n_of_joints; unsigned int n_of_output; c_map_type c_map; Eigen::MatrixXd J; Eigen::MatrixXd Jt; Eigen::MatrixXd J1,J3,J6; Eigen::VectorXd lambda_des; Eigen::VectorXd lambda1,lambda3,lambda6; qpOASES::SQProblem QP; ///< QP Solver bool prepared; /* int Compute(const std::vector<double> &q_in, double time, Eigen::VectorXd &tau_out,bool time_present);*/ public: velocity_solver( const std::vector<int>& joint_indexes, const int time_index=-1 ); velocity_solver(); /* void setJointIndex(const std::vector<int>&indx); void setTimeIndex(const int); bool addConstraint(const std::string& name, const constraint &c); bool addConstraint(const std::string& name, const constraint::Ptr &c); bool RemoveConstraint(const std::string &s); int Prepare(); int Compute(const std::vector<double> &q_in, double time, Eigen::VectorXd &tau_out); int Compute(const std::vector<double> &q_in,Eigen::VectorXd &tau_out); //memory assignment copy... Eigen::VectorXd getLastDesiredForce(){return lambda_des;}; */ typedef boost::shared_ptr<velocity_solver> Ptr; }; } <|endoftext|>
<commit_before>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011-2013 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * This file is part of libcppa. * * libcppa 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. * * * * libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #ifndef CPPA_TYPED_ACTOR_PTR_HPP #define CPPA_TYPED_ACTOR_PTR_HPP #include "cppa/replies_to.hpp" #include "cppa/match_expr.hpp" #include "cppa/spawn_options.hpp" #include "cppa/detail/typed_actor_util.hpp" namespace cppa { template<typename... Signatures> class typed_actor_ptr; // functions that need access to typed_actor_ptr::unbox() template<spawn_options Options, typename... Ts> typed_actor_ptr<typename detail::deduce_signature<Ts>::type...> spawn_typed(const match_expr<Ts...>&); template<typename... Ts> void send_exit(const typed_actor_ptr<Ts...>&, std::uint32_t); template<typename... Ts, typename... Us> typed_message_future< typename detail::deduce_output_type< util::type_list<Ts...>, util::type_list< typename detail::implicit_conversions< typename util::rm_const_and_ref< Us >::type >::type... > >::type > sync_send(const typed_actor_ptr<Ts...>&, Us&&...); template<typename... Signatures> class typed_actor_ptr { template<spawn_options Options, typename... Ts> friend typed_actor_ptr<typename detail::deduce_signature<Ts>::type...> spawn_typed(const match_expr<Ts...>&); template<typename... Ts> friend void send_exit(const typed_actor_ptr<Ts...>&, std::uint32_t); template<typename... Ts, typename... Us> friend typed_message_future< typename detail::deduce_output_type< util::type_list<Ts...>, util::type_list< typename detail::implicit_conversions< typename util::rm_const_and_ref< Us >::type >::type... > >::type > sync_send(const typed_actor_ptr<Ts...>&, Us&&...); public: typedef util::type_list<Signatures...> signatures; typed_actor_ptr() = default; typed_actor_ptr(typed_actor_ptr&&) = default; typed_actor_ptr(const typed_actor_ptr&) = default; typed_actor_ptr& operator=(typed_actor_ptr&&) = default; typed_actor_ptr& operator=(const typed_actor_ptr&) = default; private: const actor_ptr& unbox() const { return m_ptr; } typed_actor_ptr(actor_ptr ptr) : m_ptr(std::move(ptr)) { } actor_ptr m_ptr; }; } // namespace cppa #endif // CPPA_TYPED_ACTOR_PTR_HPP <commit_msg>allow automatic "upcast" of typed actors<commit_after>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011-2013 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * This file is part of libcppa. * * libcppa 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. * * * * libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #ifndef CPPA_TYPED_ACTOR_PTR_HPP #define CPPA_TYPED_ACTOR_PTR_HPP #include "cppa/replies_to.hpp" #include "cppa/match_expr.hpp" #include "cppa/spawn_options.hpp" #include "cppa/detail/typed_actor_util.hpp" namespace cppa { template<typename... Signatures> class typed_actor_ptr; // functions that need access to typed_actor_ptr::unbox() template<spawn_options Options, typename... Ts> typed_actor_ptr<typename detail::deduce_signature<Ts>::type...> spawn_typed(const match_expr<Ts...>&); template<typename... Ts> void send_exit(const typed_actor_ptr<Ts...>&, std::uint32_t); template<typename... Ts, typename... Us> typed_message_future< typename detail::deduce_output_type< util::type_list<Ts...>, util::type_list< typename detail::implicit_conversions< typename util::rm_const_and_ref< Us >::type >::type... > >::type > sync_send(const typed_actor_ptr<Ts...>&, Us&&...); template<typename... Signatures> class typed_actor_ptr { template<typename... OtherSignatures> friend class typed_actor_ptr; template<spawn_options Options, typename... Ts> friend typed_actor_ptr<typename detail::deduce_signature<Ts>::type...> spawn_typed(const match_expr<Ts...>&); template<typename... Ts> friend void send_exit(const typed_actor_ptr<Ts...>&, std::uint32_t); template<typename... Ts, typename... Us> friend typed_message_future< typename detail::deduce_output_type< util::type_list<Ts...>, util::type_list< typename detail::implicit_conversions< typename util::rm_const_and_ref< Us >::type >::type... > >::type > sync_send(const typed_actor_ptr<Ts...>&, Us&&...); public: typedef util::type_list<Signatures...> signatures; typed_actor_ptr() = default; typed_actor_ptr(typed_actor_ptr&&) = default; typed_actor_ptr(const typed_actor_ptr&) = default; typed_actor_ptr& operator=(typed_actor_ptr&&) = default; typed_actor_ptr& operator=(const typed_actor_ptr&) = default; template<typename... Others> typed_actor_ptr(typed_actor_ptr<Others...> other) { static_assert(util::tl_is_strict_subset< util::type_list<Signatures...>, util::type_list<Others...> >::value, "'this' must be a strict subset of 'other'"); m_ptr = std::move(other.m_ptr); } private: const actor_ptr& unbox() const { return m_ptr; } typed_actor_ptr(actor_ptr ptr) : m_ptr(std::move(ptr)) { } actor_ptr m_ptr; }; } // namespace cppa #endif // CPPA_TYPED_ACTOR_PTR_HPP <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: binarywritehandler.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-05-20 15:42:59 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CONFIGMGR_BINARYWRITEHANDLER_HXX #define CONFIGMGR_BINARYWRITEHANDLER_HXX #ifndef _CONFIGMGR_TREE_VALUENODE_HXX #include "valuenode.hxx" #endif #ifndef CONFIGMGR_BINARYWRITER_HXX #include "binarywriter.hxx" #endif #ifndef CONFIGMGR_BINARYTYPE_HXX #include "binarytype.hxx" #endif #ifndef CONFIGMGR_CONFIGURATION_ATTRIBUTES_HXX_ #include "attributes.hxx" #endif #ifndef CONFIGMGR_MATCHLOCALE_HXX #include "matchlocale.hxx" #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_ #include <com/sun/star/configuration/backend/XLayer.hpp> #endif // _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_ #ifndef _COM_SUN_STAR_IO_IOEXCEPTION_HPP_ #include <com/sun/star/io/IOException.hpp> #endif namespace configmgr { // ----------------------------------------------------------------------------- namespace backend { namespace css = com::sun::star; namespace io = css::io; namespace uno = css::uno; namespace backenduno = css::configuration::backend ; // ----------------------------------------------------------------------------- class BinaryWriteHandler : private NodeAction { BinaryWriter m_BinaryWriter; rtl::OUString m_aComponentName; public: BinaryWriteHandler(rtl::OUString const & _aFileURL, rtl::OUString const & _aComponentName, MultiServiceFactory const & _aFactory); bool generateHeader( const uno::Reference<backenduno::XLayer> * pLayers, sal_Int32 nNumLayers, const OUString& aEntity, const localehelper::LocaleSequence & aKnownLocales ) SAL_THROW( (io::IOException, uno::RuntimeException) ); void writeComponentTree(const ISubtree * _pComponentTree) SAL_THROW( (io::IOException, uno::RuntimeException) ); void writeTemplatesTree(const ISubtree * _pTemplatesTree) SAL_THROW( (io::IOException, uno::RuntimeException) ); private: void writeTree(ISubtree const & rTree) SAL_THROW( (io::IOException, uno::RuntimeException) ); // Node Action virtual void handle(ISubtree const & aSubtree); virtual void handle(ValueNode const & aValue); private: void writeFileHeader( rtl::OUString const & _aSchemaVersion, const uno::Sequence<OUString> & aKnownLocales, const uno::Sequence<OUString> & aDataLocales ) SAL_THROW( (io::IOException, uno::RuntimeException) ); void writeLayerInfoList(uno::Reference<backenduno::XLayer> const * pLayers, sal_Int32 nNumlayers) SAL_THROW( (io::IOException, uno::RuntimeException) ); void writeGroupNode(rtl::OUString const& _aName,node::Attributes const& _aAttributes) SAL_THROW( (io::IOException, uno::RuntimeException) ); void writeValueNode(rtl::OUString const& _aName, node::Attributes const& _aAttributes, uno::Type const& _aType, uno::Any const& _aUserValue, uno::Any const& _aDefaultValue) SAL_THROW( (io::IOException, uno::RuntimeException) ); void writeSetNode(rtl::OUString const& _aName, rtl::OUString const& _aTemplateName, rtl::OUString const& _aTemplateModule, node::Attributes const& _aAttributes) SAL_THROW( (io::IOException, uno::RuntimeException) ); void writeAttributes(node::Attributes const& _aAttributes) SAL_THROW( (io::IOException, uno::RuntimeException) ); void BinaryWriteHandler::writeNodeType(binary::NodeType::Type _eType) SAL_THROW( (io::IOException, uno::RuntimeException) ); void BinaryWriteHandler::writeStop() SAL_THROW( (io::IOException, uno::RuntimeException) ); void writeType(uno::Type const& _aType) SAL_THROW( (io::IOException, uno::RuntimeException) ); void BinaryWriteHandler::writeValue( uno::Any const& _aValue) SAL_THROW( (io::IOException, uno::RuntimeException) ); }; // --------------------------------------------------------------------------- } // ----------------------------------------------------------------------------- }// namespace configmgr #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.4.18); FILE MERGED 2005/09/05 17:03:54 rt 1.4.18.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: binarywritehandler.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 03:27:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONFIGMGR_BINARYWRITEHANDLER_HXX #define CONFIGMGR_BINARYWRITEHANDLER_HXX #ifndef _CONFIGMGR_TREE_VALUENODE_HXX #include "valuenode.hxx" #endif #ifndef CONFIGMGR_BINARYWRITER_HXX #include "binarywriter.hxx" #endif #ifndef CONFIGMGR_BINARYTYPE_HXX #include "binarytype.hxx" #endif #ifndef CONFIGMGR_CONFIGURATION_ATTRIBUTES_HXX_ #include "attributes.hxx" #endif #ifndef CONFIGMGR_MATCHLOCALE_HXX #include "matchlocale.hxx" #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_ #include <com/sun/star/configuration/backend/XLayer.hpp> #endif // _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_ #ifndef _COM_SUN_STAR_IO_IOEXCEPTION_HPP_ #include <com/sun/star/io/IOException.hpp> #endif namespace configmgr { // ----------------------------------------------------------------------------- namespace backend { namespace css = com::sun::star; namespace io = css::io; namespace uno = css::uno; namespace backenduno = css::configuration::backend ; // ----------------------------------------------------------------------------- class BinaryWriteHandler : private NodeAction { BinaryWriter m_BinaryWriter; rtl::OUString m_aComponentName; public: BinaryWriteHandler(rtl::OUString const & _aFileURL, rtl::OUString const & _aComponentName, MultiServiceFactory const & _aFactory); bool generateHeader( const uno::Reference<backenduno::XLayer> * pLayers, sal_Int32 nNumLayers, const OUString& aEntity, const localehelper::LocaleSequence & aKnownLocales ) SAL_THROW( (io::IOException, uno::RuntimeException) ); void writeComponentTree(const ISubtree * _pComponentTree) SAL_THROW( (io::IOException, uno::RuntimeException) ); void writeTemplatesTree(const ISubtree * _pTemplatesTree) SAL_THROW( (io::IOException, uno::RuntimeException) ); private: void writeTree(ISubtree const & rTree) SAL_THROW( (io::IOException, uno::RuntimeException) ); // Node Action virtual void handle(ISubtree const & aSubtree); virtual void handle(ValueNode const & aValue); private: void writeFileHeader( rtl::OUString const & _aSchemaVersion, const uno::Sequence<OUString> & aKnownLocales, const uno::Sequence<OUString> & aDataLocales ) SAL_THROW( (io::IOException, uno::RuntimeException) ); void writeLayerInfoList(uno::Reference<backenduno::XLayer> const * pLayers, sal_Int32 nNumlayers) SAL_THROW( (io::IOException, uno::RuntimeException) ); void writeGroupNode(rtl::OUString const& _aName,node::Attributes const& _aAttributes) SAL_THROW( (io::IOException, uno::RuntimeException) ); void writeValueNode(rtl::OUString const& _aName, node::Attributes const& _aAttributes, uno::Type const& _aType, uno::Any const& _aUserValue, uno::Any const& _aDefaultValue) SAL_THROW( (io::IOException, uno::RuntimeException) ); void writeSetNode(rtl::OUString const& _aName, rtl::OUString const& _aTemplateName, rtl::OUString const& _aTemplateModule, node::Attributes const& _aAttributes) SAL_THROW( (io::IOException, uno::RuntimeException) ); void writeAttributes(node::Attributes const& _aAttributes) SAL_THROW( (io::IOException, uno::RuntimeException) ); void BinaryWriteHandler::writeNodeType(binary::NodeType::Type _eType) SAL_THROW( (io::IOException, uno::RuntimeException) ); void BinaryWriteHandler::writeStop() SAL_THROW( (io::IOException, uno::RuntimeException) ); void writeType(uno::Type const& _aType) SAL_THROW( (io::IOException, uno::RuntimeException) ); void BinaryWriteHandler::writeValue( uno::Any const& _aValue) SAL_THROW( (io::IOException, uno::RuntimeException) ); }; // --------------------------------------------------------------------------- } // ----------------------------------------------------------------------------- }// namespace configmgr #endif <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // imgui-metal.c // Since this will only need to compile with clang we can use // mix designated initializers and C++ code. //------------------------------------------------------------------------------ #include "osxentry.h" #include "sokol_gfx.h" #include "sokol_time.h" #include "imgui.h" const int WIDTH = 1024; const int HEIGHT = 768; const int MaxVertices = (1<<16); const int MaxIndices = MaxVertices * 3; uint64_t last_time = 0; bool show_test_window = true; bool show_another_window = false; sg_draw_state draw_state = { }; sg_pass_action pass_action = { }; ImDrawVert vertices[MaxVertices]; uint16_t indices[MaxIndices]; typedef struct { ImVec2 disp_size; } vs_params_t; void imgui_draw_cb(ImDrawData*); void init(const void* mtl_device) { // setup sokol_gfx and sokol_time sg_desc desc = { .mtl_device = mtl_device, .mtl_renderpass_descriptor_cb = osx_mtk_get_render_pass_descriptor, .mtl_drawable_cb = osx_mtk_get_drawable }; sg_setup(&desc); stm_setup(); // setup the imgui environment ImGui::CreateContext(); ImGui::StyleColorsDark(); ImGuiIO& io = ImGui::GetIO(); io.IniFilename = nullptr; io.RenderDrawListsFn = imgui_draw_cb; io.Fonts->AddFontDefault(); io.KeyMap[ImGuiKey_Tab] = 0x30; io.KeyMap[ImGuiKey_LeftArrow] = 0x7B; io.KeyMap[ImGuiKey_RightArrow] = 0x7C; io.KeyMap[ImGuiKey_DownArrow] = 0x7D; io.KeyMap[ImGuiKey_UpArrow] = 0x7E; io.KeyMap[ImGuiKey_Home] = 0x73; io.KeyMap[ImGuiKey_End] = 0x77; io.KeyMap[ImGuiKey_Delete] = 0x75; io.KeyMap[ImGuiKey_Backspace] = 0x33; io.KeyMap[ImGuiKey_Enter] = 0x24; io.KeyMap[ImGuiKey_Escape] = 0x35; io.KeyMap[ImGuiKey_A] = 0x00; io.KeyMap[ImGuiKey_C] = 0x08; io.KeyMap[ImGuiKey_V] = 0x09; io.KeyMap[ImGuiKey_X] = 0x07; io.KeyMap[ImGuiKey_Y] = 0x10; io.KeyMap[ImGuiKey_Z] = 0x06; // OSX => ImGui input forwarding osx_mouse_pos([] (float x, float y) { ImGui::GetIO().MousePos = ImVec2(x, y); }); osx_mouse_btn_down([] (int btn) { ImGui::GetIO().MouseDown[btn] = true; }); osx_mouse_btn_up([] (int btn) { ImGui::GetIO().MouseDown[btn] = false; }); osx_mouse_wheel([] (float v) { ImGui::GetIO().MouseWheel = 0.25f * v; }); osx_key_down([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = true; }); osx_key_up([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = false; }); osx_char([] (wchar_t c) { ImGui::GetIO().AddInputCharacter(c); }); // dynamic vertex- and index-buffers for ImGui-generated geometry sg_buffer_desc vbuf_desc = { .usage = SG_USAGE_STREAM, .size = sizeof(vertices) }; draw_state.vertex_buffers[0] = sg_make_buffer(&vbuf_desc); sg_buffer_desc ibuf_desc = { .type = SG_BUFFERTYPE_INDEXBUFFER, .usage = SG_USAGE_STREAM, .size = sizeof(indices) }; draw_state.index_buffer = sg_make_buffer(&ibuf_desc); // font texture for ImGui's default font unsigned char* font_pixels; int font_width, font_height; io.Fonts->GetTexDataAsRGBA32(&font_pixels, &font_width, &font_height); sg_image_desc img_desc = { .width = font_width, .height = font_height, .pixel_format = SG_PIXELFORMAT_RGBA8, .wrap_u = SG_WRAP_CLAMP_TO_EDGE, .wrap_v = SG_WRAP_CLAMP_TO_EDGE, .content.subimage[0][0] = { .ptr = font_pixels, .size = font_width * font_height * 4 } }; draw_state.fs_images[0] = sg_make_image(&img_desc); // shader object for imgui renering sg_shader_desc shd_desc = { .vs.uniform_blocks[0].size = sizeof(vs_params_t), .vs.source = "#include <metal_stdlib>\n" "using namespace metal;\n" "struct params_t {\n" " float2 disp_size;\n" "};\n" "struct vs_in {\n" " float2 pos [[attribute(0)]];\n" " float2 uv [[attribute(1)]];\n" " float4 color [[attribute(2)]];\n" "};\n" "struct vs_out {\n" " float4 pos [[position]];\n" " float2 uv;\n" " float4 color;\n" "};\n" "vertex vs_out _main(vs_in in [[stage_in]], constant params_t& params [[buffer(0)]]) {\n" " vs_out out;\n" " out.pos = float4(((in.pos / params.disp_size)-0.5)*float2(2.0,-2.0), 0.5, 1.0);\n" " out.uv = in.uv;\n" " out.color = in.color;\n" " return out;\n" "}\n", .fs.images[0].type = SG_IMAGETYPE_2D, .fs.source = "#include <metal_stdlib>\n" "using namespace metal;\n" "struct fs_in {\n" " float2 uv;\n" " float4 color;\n" "};\n" "fragment float4 _main(fs_in in [[stage_in]], texture2d<float> tex [[texture(0)]], sampler smp [[sampler(0)]]) {\n" " return tex.sample(smp, in.uv) * in.color;\n" "}\n" }; sg_shader shd = sg_make_shader(&shd_desc); // pipeline object for imgui rendering sg_pipeline_desc pip_desc = { .layout = { .buffers[0].stride = sizeof(ImDrawVert), .attrs = { [0] = { .offset=offsetof(ImDrawVert,pos), .format=SG_VERTEXFORMAT_FLOAT2 }, [1] = { .offset=offsetof(ImDrawVert,uv), .format=SG_VERTEXFORMAT_FLOAT2 }, [2] = { .offset=offsetof(ImDrawVert,col), .format=SG_VERTEXFORMAT_UBYTE4N } } }, .shader = shd, .index_type = SG_INDEXTYPE_UINT16, .blend = { .enabled = true, .src_factor_rgb = SG_BLENDFACTOR_SRC_ALPHA, .dst_factor_rgb = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA, .color_write_mask = SG_COLORMASK_RGB } }; draw_state.pipeline = sg_make_pipeline(&pip_desc); // initial clear color pass_action = (sg_pass_action){ .colors[0] = { .action = SG_ACTION_CLEAR, .val = { 0.0f, 0.5f, 0.7f, 1.0f } } }; } void frame() { const int width = osx_width(); const int height = osx_height(); ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2(width, height); io.DeltaTime = (float) stm_sec(stm_laptime(&last_time)); ImGui::NewFrame(); // 1. Show a simple window // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug" static float f = 0.0f; ImGui::Text("Hello, world!"); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ImGui::ColorEdit3("clear color", &pass_action.colors[0].val[0]); if (ImGui::Button("Test Window")) show_test_window ^= 1; if (ImGui::Button("Another Window")) show_another_window ^= 1; ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); // 2. Show another simple window, this time using an explicit Begin/End pair if (show_another_window) { ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver); ImGui::Begin("Another Window", &show_another_window); ImGui::Text("Hello"); ImGui::End(); } // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow() if (show_test_window) { ImGui::SetNextWindowPos(ImVec2(460, 20), ImGuiSetCond_FirstUseEver); ImGui::ShowTestWindow(); } // the sokol draw pass sg_begin_default_pass(&pass_action, width, height); ImGui::Render(); sg_end_pass(); sg_commit(); } void shutdown() { ImGui::DestroyContext(); sg_shutdown(); } int main() { osx_start(WIDTH, HEIGHT, 1, "Sokol Dear ImGui (Metal)", init, frame, shutdown); return 0; } void imgui_draw_cb(ImDrawData* draw_data) { if (draw_data->CmdListsCount == 0) { return; } // copy vertices and indices int num_vertices = 0; int num_indices = 0; int num_cmdlists = 0; for (; num_cmdlists < draw_data->CmdListsCount; num_cmdlists++) { const ImDrawList* cl = draw_data->CmdLists[num_cmdlists]; const int cl_num_vertices = cl->VtxBuffer.size(); const int cl_num_indices = cl->IdxBuffer.size(); // overflow check if ((num_vertices + cl_num_vertices) > MaxVertices) { break; } if ((num_indices + cl_num_indices) > MaxIndices) { break; } // copy vertices memcpy(&vertices[num_vertices], &cl->VtxBuffer.front(), cl_num_vertices*sizeof(ImDrawVert)); // copy indices, need to rebase to start of global vertex buffer const ImDrawIdx* src_index_ptr = &cl->IdxBuffer.front(); const uint16_t base_vertex_index = num_vertices; for (int i = 0; i < cl_num_indices; i++) { indices[num_indices++] = src_index_ptr[i] + base_vertex_index; } num_vertices += cl_num_vertices; } // update vertex and index buffers const int vertex_data_size = num_vertices * sizeof(ImDrawVert); const int index_data_size = num_indices * sizeof(uint16_t); sg_update_buffer(draw_state.vertex_buffers[0], vertices, vertex_data_size); sg_update_buffer(draw_state.index_buffer, indices, index_data_size); // render the command list vs_params_t vs_params; vs_params.disp_size = ImGui::GetIO().DisplaySize; sg_apply_draw_state(&draw_state); sg_apply_uniform_block(SG_SHADERSTAGE_VS, 0, &vs_params, sizeof(vs_params)); int base_element = 0; for (int cl_index = 0; cl_index < num_cmdlists; cl_index++) { const ImDrawList* cmd_list = draw_data->CmdLists[cl_index]; for (const ImDrawCmd& cmd : cmd_list->CmdBuffer) { if (cmd.UserCallback) { cmd.UserCallback(cmd_list, &cmd); } else { const int sx = (int) cmd.ClipRect.x; const int sy = (int) cmd.ClipRect.y; const int sw = (int) (cmd.ClipRect.z - cmd.ClipRect.x); const int sh = (int) (cmd.ClipRect.w - cmd.ClipRect.y); sg_apply_scissor_rect(sx, sy, sw, sh, true); sg_draw(base_element, cmd.ElemCount, 1); } base_element += cmd.ElemCount; } } } <commit_msg>fix the imgui-metal texture filtering to be the same as the sokol-app demos<commit_after>//------------------------------------------------------------------------------ // imgui-metal.c // Since this will only need to compile with clang we can use // mix designated initializers and C++ code. //------------------------------------------------------------------------------ #include "osxentry.h" #include "sokol_gfx.h" #include "sokol_time.h" #include "imgui.h" const int WIDTH = 1024; const int HEIGHT = 768; const int MaxVertices = (1<<16); const int MaxIndices = MaxVertices * 3; uint64_t last_time = 0; bool show_test_window = true; bool show_another_window = false; sg_draw_state draw_state = { }; sg_pass_action pass_action = { }; ImDrawVert vertices[MaxVertices]; uint16_t indices[MaxIndices]; typedef struct { ImVec2 disp_size; } vs_params_t; void imgui_draw_cb(ImDrawData*); void init(const void* mtl_device) { // setup sokol_gfx and sokol_time sg_desc desc = { .mtl_device = mtl_device, .mtl_renderpass_descriptor_cb = osx_mtk_get_render_pass_descriptor, .mtl_drawable_cb = osx_mtk_get_drawable }; sg_setup(&desc); stm_setup(); // setup the imgui environment ImGui::CreateContext(); ImGui::StyleColorsDark(); ImGuiIO& io = ImGui::GetIO(); io.IniFilename = nullptr; io.RenderDrawListsFn = imgui_draw_cb; io.Fonts->AddFontDefault(); io.KeyMap[ImGuiKey_Tab] = 0x30; io.KeyMap[ImGuiKey_LeftArrow] = 0x7B; io.KeyMap[ImGuiKey_RightArrow] = 0x7C; io.KeyMap[ImGuiKey_DownArrow] = 0x7D; io.KeyMap[ImGuiKey_UpArrow] = 0x7E; io.KeyMap[ImGuiKey_Home] = 0x73; io.KeyMap[ImGuiKey_End] = 0x77; io.KeyMap[ImGuiKey_Delete] = 0x75; io.KeyMap[ImGuiKey_Backspace] = 0x33; io.KeyMap[ImGuiKey_Enter] = 0x24; io.KeyMap[ImGuiKey_Escape] = 0x35; io.KeyMap[ImGuiKey_A] = 0x00; io.KeyMap[ImGuiKey_C] = 0x08; io.KeyMap[ImGuiKey_V] = 0x09; io.KeyMap[ImGuiKey_X] = 0x07; io.KeyMap[ImGuiKey_Y] = 0x10; io.KeyMap[ImGuiKey_Z] = 0x06; // OSX => ImGui input forwarding osx_mouse_pos([] (float x, float y) { ImGui::GetIO().MousePos = ImVec2(x, y); }); osx_mouse_btn_down([] (int btn) { ImGui::GetIO().MouseDown[btn] = true; }); osx_mouse_btn_up([] (int btn) { ImGui::GetIO().MouseDown[btn] = false; }); osx_mouse_wheel([] (float v) { ImGui::GetIO().MouseWheel = 0.25f * v; }); osx_key_down([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = true; }); osx_key_up([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = false; }); osx_char([] (wchar_t c) { ImGui::GetIO().AddInputCharacter(c); }); // dynamic vertex- and index-buffers for ImGui-generated geometry sg_buffer_desc vbuf_desc = { .usage = SG_USAGE_STREAM, .size = sizeof(vertices) }; draw_state.vertex_buffers[0] = sg_make_buffer(&vbuf_desc); sg_buffer_desc ibuf_desc = { .type = SG_BUFFERTYPE_INDEXBUFFER, .usage = SG_USAGE_STREAM, .size = sizeof(indices) }; draw_state.index_buffer = sg_make_buffer(&ibuf_desc); // font texture for ImGui's default font unsigned char* font_pixels; int font_width, font_height; io.Fonts->GetTexDataAsRGBA32(&font_pixels, &font_width, &font_height); sg_image_desc img_desc = { .width = font_width, .height = font_height, .pixel_format = SG_PIXELFORMAT_RGBA8, .wrap_u = SG_WRAP_CLAMP_TO_EDGE, .wrap_v = SG_WRAP_CLAMP_TO_EDGE, .min_filter = SG_FILTER_LINEAR, .mag_filter = SG_FILTER_LINEAR, .content.subimage[0][0] = { .ptr = font_pixels, .size = font_width * font_height * 4 } }; draw_state.fs_images[0] = sg_make_image(&img_desc); // shader object for imgui renering sg_shader_desc shd_desc = { .vs.uniform_blocks[0].size = sizeof(vs_params_t), .vs.source = "#include <metal_stdlib>\n" "using namespace metal;\n" "struct params_t {\n" " float2 disp_size;\n" "};\n" "struct vs_in {\n" " float2 pos [[attribute(0)]];\n" " float2 uv [[attribute(1)]];\n" " float4 color [[attribute(2)]];\n" "};\n" "struct vs_out {\n" " float4 pos [[position]];\n" " float2 uv;\n" " float4 color;\n" "};\n" "vertex vs_out _main(vs_in in [[stage_in]], constant params_t& params [[buffer(0)]]) {\n" " vs_out out;\n" " out.pos = float4(((in.pos / params.disp_size)-0.5)*float2(2.0,-2.0), 0.5, 1.0);\n" " out.uv = in.uv;\n" " out.color = in.color;\n" " return out;\n" "}\n", .fs.images[0].type = SG_IMAGETYPE_2D, .fs.source = "#include <metal_stdlib>\n" "using namespace metal;\n" "struct fs_in {\n" " float2 uv;\n" " float4 color;\n" "};\n" "fragment float4 _main(fs_in in [[stage_in]], texture2d<float> tex [[texture(0)]], sampler smp [[sampler(0)]]) {\n" " return tex.sample(smp, in.uv) * in.color;\n" "}\n" }; sg_shader shd = sg_make_shader(&shd_desc); // pipeline object for imgui rendering sg_pipeline_desc pip_desc = { .layout = { .buffers[0].stride = sizeof(ImDrawVert), .attrs = { [0] = { .offset=offsetof(ImDrawVert,pos), .format=SG_VERTEXFORMAT_FLOAT2 }, [1] = { .offset=offsetof(ImDrawVert,uv), .format=SG_VERTEXFORMAT_FLOAT2 }, [2] = { .offset=offsetof(ImDrawVert,col), .format=SG_VERTEXFORMAT_UBYTE4N } } }, .shader = shd, .index_type = SG_INDEXTYPE_UINT16, .blend = { .enabled = true, .src_factor_rgb = SG_BLENDFACTOR_SRC_ALPHA, .dst_factor_rgb = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA, .color_write_mask = SG_COLORMASK_RGB } }; draw_state.pipeline = sg_make_pipeline(&pip_desc); // initial clear color pass_action = (sg_pass_action){ .colors[0] = { .action = SG_ACTION_CLEAR, .val = { 0.0f, 0.5f, 0.7f, 1.0f } } }; } void frame() { const int width = osx_width(); const int height = osx_height(); ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2(width, height); io.DeltaTime = (float) stm_sec(stm_laptime(&last_time)); ImGui::NewFrame(); // 1. Show a simple window // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug" static float f = 0.0f; ImGui::Text("Hello, world!"); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ImGui::ColorEdit3("clear color", &pass_action.colors[0].val[0]); if (ImGui::Button("Test Window")) show_test_window ^= 1; if (ImGui::Button("Another Window")) show_another_window ^= 1; ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); // 2. Show another simple window, this time using an explicit Begin/End pair if (show_another_window) { ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver); ImGui::Begin("Another Window", &show_another_window); ImGui::Text("Hello"); ImGui::End(); } // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow() if (show_test_window) { ImGui::SetNextWindowPos(ImVec2(460, 20), ImGuiSetCond_FirstUseEver); ImGui::ShowTestWindow(); } // the sokol draw pass sg_begin_default_pass(&pass_action, width, height); ImGui::Render(); sg_end_pass(); sg_commit(); } void shutdown() { ImGui::DestroyContext(); sg_shutdown(); } int main() { osx_start(WIDTH, HEIGHT, 1, "Sokol Dear ImGui (Metal)", init, frame, shutdown); return 0; } void imgui_draw_cb(ImDrawData* draw_data) { if (draw_data->CmdListsCount == 0) { return; } // copy vertices and indices int num_vertices = 0; int num_indices = 0; int num_cmdlists = 0; for (; num_cmdlists < draw_data->CmdListsCount; num_cmdlists++) { const ImDrawList* cl = draw_data->CmdLists[num_cmdlists]; const int cl_num_vertices = cl->VtxBuffer.size(); const int cl_num_indices = cl->IdxBuffer.size(); // overflow check if ((num_vertices + cl_num_vertices) > MaxVertices) { break; } if ((num_indices + cl_num_indices) > MaxIndices) { break; } // copy vertices memcpy(&vertices[num_vertices], &cl->VtxBuffer.front(), cl_num_vertices*sizeof(ImDrawVert)); // copy indices, need to rebase to start of global vertex buffer const ImDrawIdx* src_index_ptr = &cl->IdxBuffer.front(); const uint16_t base_vertex_index = num_vertices; for (int i = 0; i < cl_num_indices; i++) { indices[num_indices++] = src_index_ptr[i] + base_vertex_index; } num_vertices += cl_num_vertices; } // update vertex and index buffers const int vertex_data_size = num_vertices * sizeof(ImDrawVert); const int index_data_size = num_indices * sizeof(uint16_t); sg_update_buffer(draw_state.vertex_buffers[0], vertices, vertex_data_size); sg_update_buffer(draw_state.index_buffer, indices, index_data_size); // render the command list vs_params_t vs_params; vs_params.disp_size = ImGui::GetIO().DisplaySize; sg_apply_draw_state(&draw_state); sg_apply_uniform_block(SG_SHADERSTAGE_VS, 0, &vs_params, sizeof(vs_params)); int base_element = 0; for (int cl_index = 0; cl_index < num_cmdlists; cl_index++) { const ImDrawList* cmd_list = draw_data->CmdLists[cl_index]; for (const ImDrawCmd& cmd : cmd_list->CmdBuffer) { if (cmd.UserCallback) { cmd.UserCallback(cmd_list, &cmd); } else { const int sx = (int) cmd.ClipRect.x; const int sy = (int) cmd.ClipRect.y; const int sw = (int) (cmd.ClipRect.z - cmd.ClipRect.x); const int sh = (int) (cmd.ClipRect.w - cmd.ClipRect.y); sg_apply_scissor_rect(sx, sy, sw, sh, true); sg_draw(base_element, cmd.ElemCount, 1); } base_element += cmd.ElemCount; } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: cachemulticaster.cxx,v $ * * $Revision: 1.1 $ * * last change: $Author: jb $ $Date: 2002-03-15 11:48:53 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "cachemulticaster.hxx" #ifndef INCLUDED_ALGORITHM #include <algorithm> #define INCLUDED_ALGORITHM #endif #ifndef INCLUDED_FUNCTIONAL #include <functional> #define INCLUDED_FUNCTIONAL #endif namespace configmgr { // --------------------------------------------------------------------------- namespace backend { // --------------------------------------------------------------------------- namespace { // manually implemented helpers, as rtl::References don't work well with std binders typedef CacheChangeMulticaster::ListenerRef ListenerRef; // --------------------------------------------------------------------------- // replacing std::bind2nd( std::mem_fun(&aFunc), aArg ) struct NotifyDisposing : std::unary_function<ListenerRef,void> { typedef ICachedDataProvider Arg; Arg & m_arg; NotifyDisposing(Arg * _pProvider) CFG_NOTHROW() : m_arg(*_pProvider) {} void operator()(ListenerRef const & _xListener) const CFG_NOTHROW() { _xListener->disposing(m_arg); } }; // --------------------------------------------------------------------------- // replacing std::bind2nd( std::mem_fun(&ICachedDataListener::componentCreated), _aComponentName ) struct NotifyCreated : std::unary_function<ListenerRef,void> { typedef ComponentRequest const Arg; Arg & m_arg; NotifyCreated(Arg * _pComponent) CFG_NOTHROW() : m_arg(*_pComponent) {} void operator()(ListenerRef const & _xListener) const CFG_NOTHROW() { _xListener->componentCreated(m_arg); } }; // --------------------------------------------------------------------------- // replacing std::bind2nd( std::mem_fun(&ICachedDataListener::componentChanged), _aComponentName ) struct NotifyChanged : std::unary_function<ListenerRef,void> { typedef UpdateRequest const Arg; Arg & m_arg; NotifyChanged(Arg * _pUpdate) CFG_NOTHROW() : m_arg(*_pUpdate) {} void operator()(ListenerRef const & _xListener) const CFG_NOTHROW() { _xListener->componentChanged(m_arg); } }; // --------------------------------------------------------------------------- } // anonymous namespace //---------------------------------------------------------------------------- CacheChangeMulticaster::CacheChangeMulticaster() : m_aMutex() , m_aListeners() { } // --------------------------------------------------------------------------- CacheChangeMulticaster::~CacheChangeMulticaster() { OSL_ENSURE( m_aListeners.empty(), "Forgot to dispose multicaster" ); } // --------------------------------------------------------------------------- inline CacheChangeMulticaster::ListenerList CacheChangeMulticaster::copyListenerList() { osl::MutexGuard aListGuard(m_aMutex); return m_aListeners; } // --------------------------------------------------------------------------- void CacheChangeMulticaster::dispose(ICachedDataProvider & _rProvider) CFG_NOTHROW() { osl::ClearableMutexGuard aListGuard(m_aMutex); ListenerList aNotifyListeners; aNotifyListeners.swap(m_aListeners); aListGuard.clear(); std::for_each( aNotifyListeners.begin(), aNotifyListeners.end(), NotifyDisposing(&_rProvider) ); } // --------------------------------------------------------------------------- void CacheChangeMulticaster::notifyCreated(ComponentRequest const & _aComponent) CFG_NOTHROW() { ListenerList aNotifyListeners( this->copyListenerList() ); std::for_each( aNotifyListeners.begin(), aNotifyListeners.end(), NotifyCreated(&_aComponent) ); } // --------------------------------------------------------------------------- void CacheChangeMulticaster::notifyChanged(UpdateRequest const & _anUpdate) CFG_NOTHROW() { ListenerList aNotifyListeners( this->copyListenerList() ); std::for_each( aNotifyListeners.begin(), aNotifyListeners.end(), NotifyChanged(&_anUpdate) ); } // --------------------------------------------------------------------------- void CacheChangeMulticaster::addListener(ListenerRef _xListener) CFG_NOTHROW() { osl::MutexGuard aListGuard(m_aMutex); OSL_PRECOND(std::find(m_aListeners.begin(),m_aListeners.end(),_xListener) == m_aListeners.end(), "WARNING: Cache Change Listener was already registered - will be notified multiply."); OSL_PRECOND(_xListener.is(), "ERROR: trying to register a NULL listener"); if (_xListener.is()) m_aListeners.push_front(_xListener); } // --------------------------------------------------------------------------- void CacheChangeMulticaster::removeListener(ListenerRef _xListener) CFG_NOTHROW() { osl::MutexGuard aListGuard(m_aMutex); m_aListeners.remove(_xListener); } // --------------------------------------------------------------------------- } // namespace backend // --------------------------------------------------------------------------- } // namespace configmgr <commit_msg>INTEGRATION: CWS ooo19126 (1.1.224); FILE MERGED 2005/09/05 17:05:14 rt 1.1.224.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cachemulticaster.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 04:23:44 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "cachemulticaster.hxx" #ifndef INCLUDED_ALGORITHM #include <algorithm> #define INCLUDED_ALGORITHM #endif #ifndef INCLUDED_FUNCTIONAL #include <functional> #define INCLUDED_FUNCTIONAL #endif namespace configmgr { // --------------------------------------------------------------------------- namespace backend { // --------------------------------------------------------------------------- namespace { // manually implemented helpers, as rtl::References don't work well with std binders typedef CacheChangeMulticaster::ListenerRef ListenerRef; // --------------------------------------------------------------------------- // replacing std::bind2nd( std::mem_fun(&aFunc), aArg ) struct NotifyDisposing : std::unary_function<ListenerRef,void> { typedef ICachedDataProvider Arg; Arg & m_arg; NotifyDisposing(Arg * _pProvider) CFG_NOTHROW() : m_arg(*_pProvider) {} void operator()(ListenerRef const & _xListener) const CFG_NOTHROW() { _xListener->disposing(m_arg); } }; // --------------------------------------------------------------------------- // replacing std::bind2nd( std::mem_fun(&ICachedDataListener::componentCreated), _aComponentName ) struct NotifyCreated : std::unary_function<ListenerRef,void> { typedef ComponentRequest const Arg; Arg & m_arg; NotifyCreated(Arg * _pComponent) CFG_NOTHROW() : m_arg(*_pComponent) {} void operator()(ListenerRef const & _xListener) const CFG_NOTHROW() { _xListener->componentCreated(m_arg); } }; // --------------------------------------------------------------------------- // replacing std::bind2nd( std::mem_fun(&ICachedDataListener::componentChanged), _aComponentName ) struct NotifyChanged : std::unary_function<ListenerRef,void> { typedef UpdateRequest const Arg; Arg & m_arg; NotifyChanged(Arg * _pUpdate) CFG_NOTHROW() : m_arg(*_pUpdate) {} void operator()(ListenerRef const & _xListener) const CFG_NOTHROW() { _xListener->componentChanged(m_arg); } }; // --------------------------------------------------------------------------- } // anonymous namespace //---------------------------------------------------------------------------- CacheChangeMulticaster::CacheChangeMulticaster() : m_aMutex() , m_aListeners() { } // --------------------------------------------------------------------------- CacheChangeMulticaster::~CacheChangeMulticaster() { OSL_ENSURE( m_aListeners.empty(), "Forgot to dispose multicaster" ); } // --------------------------------------------------------------------------- inline CacheChangeMulticaster::ListenerList CacheChangeMulticaster::copyListenerList() { osl::MutexGuard aListGuard(m_aMutex); return m_aListeners; } // --------------------------------------------------------------------------- void CacheChangeMulticaster::dispose(ICachedDataProvider & _rProvider) CFG_NOTHROW() { osl::ClearableMutexGuard aListGuard(m_aMutex); ListenerList aNotifyListeners; aNotifyListeners.swap(m_aListeners); aListGuard.clear(); std::for_each( aNotifyListeners.begin(), aNotifyListeners.end(), NotifyDisposing(&_rProvider) ); } // --------------------------------------------------------------------------- void CacheChangeMulticaster::notifyCreated(ComponentRequest const & _aComponent) CFG_NOTHROW() { ListenerList aNotifyListeners( this->copyListenerList() ); std::for_each( aNotifyListeners.begin(), aNotifyListeners.end(), NotifyCreated(&_aComponent) ); } // --------------------------------------------------------------------------- void CacheChangeMulticaster::notifyChanged(UpdateRequest const & _anUpdate) CFG_NOTHROW() { ListenerList aNotifyListeners( this->copyListenerList() ); std::for_each( aNotifyListeners.begin(), aNotifyListeners.end(), NotifyChanged(&_anUpdate) ); } // --------------------------------------------------------------------------- void CacheChangeMulticaster::addListener(ListenerRef _xListener) CFG_NOTHROW() { osl::MutexGuard aListGuard(m_aMutex); OSL_PRECOND(std::find(m_aListeners.begin(),m_aListeners.end(),_xListener) == m_aListeners.end(), "WARNING: Cache Change Listener was already registered - will be notified multiply."); OSL_PRECOND(_xListener.is(), "ERROR: trying to register a NULL listener"); if (_xListener.is()) m_aListeners.push_front(_xListener); } // --------------------------------------------------------------------------- void CacheChangeMulticaster::removeListener(ListenerRef _xListener) CFG_NOTHROW() { osl::MutexGuard aListGuard(m_aMutex); m_aListeners.remove(_xListener); } // --------------------------------------------------------------------------- } // namespace backend // --------------------------------------------------------------------------- } // namespace configmgr <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: conncleanup.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2003-03-19 16:38:14 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_CONNCLEANUP_HXX_ #include <connectivity/conncleanup.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif //......................................................................... namespace dbtools { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::lang; //===================================================================== static const ::rtl::OUString& getActiveConnectionPropertyName() { static const ::rtl::OUString s_sActiveConnectionPropertyName = ::rtl::OUString::createFromAscii("ActiveConnection"); return s_sActiveConnectionPropertyName; } //===================================================================== //= OAutoConnectionDisposer //===================================================================== //--------------------------------------------------------------------- OAutoConnectionDisposer::OAutoConnectionDisposer(const Reference< XRowSet >& _rxRowSet, const Reference< XConnection >& _rxConnection) :m_xRowSet( _rxRowSet ) ,m_bRSListening( sal_False ) ,m_bPropertyListening( sal_False ) { Reference< XPropertySet > xProps(_rxRowSet, UNO_QUERY); OSL_ENSURE(xProps.is(), "OAutoConnectionDisposer::OAutoConnectionDisposer: invalid rowset (no XPropertySet)!"); if (!xProps.is()) return; try { xProps->setPropertyValue( getActiveConnectionPropertyName(), makeAny( _rxConnection ) ); m_xOriginalConnection = _rxConnection; startPropertyListening( xProps ); } catch( const Exception& ) { OSL_ENSURE( sal_False, "OAutoConnectionDisposer::OAutoConnectionDisposer: caught an exception!" ); } } //--------------------------------------------------------------------- void OAutoConnectionDisposer::startPropertyListening( const Reference< XPropertySet >& _rxRowSet ) { try { _rxRowSet->addPropertyChangeListener( getActiveConnectionPropertyName(), this ); m_bPropertyListening = sal_True; } catch( const Exception& ) { OSL_ENSURE( sal_False, "OAutoConnectionDisposer::startPropertyListening: caught an exception!" ); } } //--------------------------------------------------------------------- void OAutoConnectionDisposer::stopPropertyListening( const Reference< XPropertySet >& _rxEventSource ) { // prevent deletion of ourself while we're herein Reference< XInterface > xKeepAlive(static_cast< XWeak* >(this)); try { // remove ourself as property change listener OSL_ENSURE( _rxEventSource.is(), "OAutoConnectionDisposer::stopPropertyListening: invalid event source (no XPropertySet)!" ); if ( _rxEventSource.is() ) { _rxEventSource->removePropertyChangeListener( getActiveConnectionPropertyName(), this ); m_bPropertyListening = sal_False; } } catch( const Exception& ) { OSL_ENSURE( sal_False, "OAutoConnectionDisposer::stopPropertyListening: caught an exception!" ); } } //--------------------------------------------------------------------- void OAutoConnectionDisposer::startRowSetListening() { OSL_ENSURE( !m_bRSListening, "OAutoConnectionDisposer::startRowSetListening: already listening!" ); try { if ( !m_bRSListening ) m_xRowSet->addRowSetListener( this ); } catch( const Exception& ) { OSL_ENSURE( sal_False, "OAutoConnectionDisposer::startRowSetListening: caught an exception!" ); } m_bRSListening = sal_True; } //--------------------------------------------------------------------- void OAutoConnectionDisposer::stopRowSetListening() { OSL_ENSURE( m_bRSListening, "OAutoConnectionDisposer::stopRowSetListening: not listening!" ); try { m_xRowSet->removeRowSetListener( this ); } catch( const Exception& ) { OSL_ENSURE( sal_False, "OAutoConnectionDisposer::stopRowSetListening: caught an exception!" ); } m_bRSListening = sal_False; } //--------------------------------------------------------------------- void SAL_CALL OAutoConnectionDisposer::propertyChange( const PropertyChangeEvent& _rEvent ) throw (RuntimeException) { if ( _rEvent.PropertyName.equals( getActiveConnectionPropertyName() ) ) { // somebody set a new ActiveConnection Reference< XConnection > xNewConnection; _rEvent.NewValue >>= xNewConnection; if ( isRowSetListening() ) { // we're listening at the row set, this means that the row set does not have our // m_xOriginalConnection as active connection anymore // So there are two possibilities // a. somebody sets a new connection which is not our original one // b. somebody sets a new connection, which is exactly the original one // a. we're not interested in a, but in b: In this case, we simply need to move to the state // we had originally: listen for property changes, do not listen for row set changes, and // do not dispose the connection until the row set does not need it anymore if ( xNewConnection.get() == m_xOriginalConnection.get() ) { stopRowSetListening(); } } else { // start listening at the row set. We're allowed to dispose the old connection as soon // as the RowSet changed // Unfortunately, the our database form implementations sometimes fire the change of their // ActiveConnection twice. This is a error in forms/source/component/DatabaseForm.cxx, but // changing this would require incompatible changes we can't do for a while. // So for the moment, we have to live with it here. // // The only scenario where this doubled notification causes problems is when the connection // of the form is reset to the one we're responsible for (m_xOriginalConnection), so we // check this here. // // Yes, this is a HACK :( // // 94407 - 08.11.2001 - fs@openoffice.org if ( xNewConnection.get() != m_xOriginalConnection.get() ) { #ifdef _DEBUG Reference< XConnection > xOldConnection; _rEvent.OldValue >>= xOldConnection; OSL_ENSURE( xOldConnection.get() == m_xOriginalConnection.get(), "OAutoConnectionDisposer::propertyChange: unexpected (original) property value!" ); #endif startRowSetListening(); } } } } //--------------------------------------------------------------------- void SAL_CALL OAutoConnectionDisposer::disposing( const EventObject& _rSource ) throw (RuntimeException) { // the rowset is beeing disposed, and nobody has set a new ActiveConnection in the meantime if ( isRowSetListening() ) stopRowSetListening(); clearConnection(); if ( isPropertyListening() ) stopPropertyListening( Reference< XPropertySet >( _rSource.Source, UNO_QUERY ) ); } //--------------------------------------------------------------------- void OAutoConnectionDisposer::clearConnection() { try { // dispose the old connection Reference< XComponent > xComp(m_xOriginalConnection, UNO_QUERY); if (xComp.is()) xComp->dispose(); m_xOriginalConnection.clear(); } catch(Exception&) { OSL_ENSURE(sal_False, "OAutoConnectionDisposer::clearConnection: caught an exception!"); } } //--------------------------------------------------------------------- void SAL_CALL OAutoConnectionDisposer::cursorMoved( const ::com::sun::star::lang::EventObject& event ) throw (::com::sun::star::uno::RuntimeException) { } //--------------------------------------------------------------------- void SAL_CALL OAutoConnectionDisposer::rowChanged( const ::com::sun::star::lang::EventObject& event ) throw (::com::sun::star::uno::RuntimeException) { } //--------------------------------------------------------------------- void SAL_CALL OAutoConnectionDisposer::rowSetChanged( const ::com::sun::star::lang::EventObject& event ) throw (::com::sun::star::uno::RuntimeException) { stopRowSetListening(); clearConnection(); } //--------------------------------------------------------------------- //......................................................................... } // namespace dbtools //......................................................................... <commit_msg>INTEGRATION: CWS dbgmacros1 (1.4.4); FILE MERGED 2003/04/09 10:23:19 kso 1.4.4.1: #108413# - debug macro unification.<commit_after>/************************************************************************* * * $RCSfile: conncleanup.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2003-04-15 17:35:34 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_CONNCLEANUP_HXX_ #include <connectivity/conncleanup.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif //......................................................................... namespace dbtools { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::lang; //===================================================================== static const ::rtl::OUString& getActiveConnectionPropertyName() { static const ::rtl::OUString s_sActiveConnectionPropertyName = ::rtl::OUString::createFromAscii("ActiveConnection"); return s_sActiveConnectionPropertyName; } //===================================================================== //= OAutoConnectionDisposer //===================================================================== //--------------------------------------------------------------------- OAutoConnectionDisposer::OAutoConnectionDisposer(const Reference< XRowSet >& _rxRowSet, const Reference< XConnection >& _rxConnection) :m_xRowSet( _rxRowSet ) ,m_bRSListening( sal_False ) ,m_bPropertyListening( sal_False ) { Reference< XPropertySet > xProps(_rxRowSet, UNO_QUERY); OSL_ENSURE(xProps.is(), "OAutoConnectionDisposer::OAutoConnectionDisposer: invalid rowset (no XPropertySet)!"); if (!xProps.is()) return; try { xProps->setPropertyValue( getActiveConnectionPropertyName(), makeAny( _rxConnection ) ); m_xOriginalConnection = _rxConnection; startPropertyListening( xProps ); } catch( const Exception& ) { OSL_ENSURE( sal_False, "OAutoConnectionDisposer::OAutoConnectionDisposer: caught an exception!" ); } } //--------------------------------------------------------------------- void OAutoConnectionDisposer::startPropertyListening( const Reference< XPropertySet >& _rxRowSet ) { try { _rxRowSet->addPropertyChangeListener( getActiveConnectionPropertyName(), this ); m_bPropertyListening = sal_True; } catch( const Exception& ) { OSL_ENSURE( sal_False, "OAutoConnectionDisposer::startPropertyListening: caught an exception!" ); } } //--------------------------------------------------------------------- void OAutoConnectionDisposer::stopPropertyListening( const Reference< XPropertySet >& _rxEventSource ) { // prevent deletion of ourself while we're herein Reference< XInterface > xKeepAlive(static_cast< XWeak* >(this)); try { // remove ourself as property change listener OSL_ENSURE( _rxEventSource.is(), "OAutoConnectionDisposer::stopPropertyListening: invalid event source (no XPropertySet)!" ); if ( _rxEventSource.is() ) { _rxEventSource->removePropertyChangeListener( getActiveConnectionPropertyName(), this ); m_bPropertyListening = sal_False; } } catch( const Exception& ) { OSL_ENSURE( sal_False, "OAutoConnectionDisposer::stopPropertyListening: caught an exception!" ); } } //--------------------------------------------------------------------- void OAutoConnectionDisposer::startRowSetListening() { OSL_ENSURE( !m_bRSListening, "OAutoConnectionDisposer::startRowSetListening: already listening!" ); try { if ( !m_bRSListening ) m_xRowSet->addRowSetListener( this ); } catch( const Exception& ) { OSL_ENSURE( sal_False, "OAutoConnectionDisposer::startRowSetListening: caught an exception!" ); } m_bRSListening = sal_True; } //--------------------------------------------------------------------- void OAutoConnectionDisposer::stopRowSetListening() { OSL_ENSURE( m_bRSListening, "OAutoConnectionDisposer::stopRowSetListening: not listening!" ); try { m_xRowSet->removeRowSetListener( this ); } catch( const Exception& ) { OSL_ENSURE( sal_False, "OAutoConnectionDisposer::stopRowSetListening: caught an exception!" ); } m_bRSListening = sal_False; } //--------------------------------------------------------------------- void SAL_CALL OAutoConnectionDisposer::propertyChange( const PropertyChangeEvent& _rEvent ) throw (RuntimeException) { if ( _rEvent.PropertyName.equals( getActiveConnectionPropertyName() ) ) { // somebody set a new ActiveConnection Reference< XConnection > xNewConnection; _rEvent.NewValue >>= xNewConnection; if ( isRowSetListening() ) { // we're listening at the row set, this means that the row set does not have our // m_xOriginalConnection as active connection anymore // So there are two possibilities // a. somebody sets a new connection which is not our original one // b. somebody sets a new connection, which is exactly the original one // a. we're not interested in a, but in b: In this case, we simply need to move to the state // we had originally: listen for property changes, do not listen for row set changes, and // do not dispose the connection until the row set does not need it anymore if ( xNewConnection.get() == m_xOriginalConnection.get() ) { stopRowSetListening(); } } else { // start listening at the row set. We're allowed to dispose the old connection as soon // as the RowSet changed // Unfortunately, the our database form implementations sometimes fire the change of their // ActiveConnection twice. This is a error in forms/source/component/DatabaseForm.cxx, but // changing this would require incompatible changes we can't do for a while. // So for the moment, we have to live with it here. // // The only scenario where this doubled notification causes problems is when the connection // of the form is reset to the one we're responsible for (m_xOriginalConnection), so we // check this here. // // Yes, this is a HACK :( // // 94407 - 08.11.2001 - fs@openoffice.org if ( xNewConnection.get() != m_xOriginalConnection.get() ) { #if OSL_DEBUG_LEVEL > 0 Reference< XConnection > xOldConnection; _rEvent.OldValue >>= xOldConnection; OSL_ENSURE( xOldConnection.get() == m_xOriginalConnection.get(), "OAutoConnectionDisposer::propertyChange: unexpected (original) property value!" ); #endif startRowSetListening(); } } } } //--------------------------------------------------------------------- void SAL_CALL OAutoConnectionDisposer::disposing( const EventObject& _rSource ) throw (RuntimeException) { // the rowset is beeing disposed, and nobody has set a new ActiveConnection in the meantime if ( isRowSetListening() ) stopRowSetListening(); clearConnection(); if ( isPropertyListening() ) stopPropertyListening( Reference< XPropertySet >( _rSource.Source, UNO_QUERY ) ); } //--------------------------------------------------------------------- void OAutoConnectionDisposer::clearConnection() { try { // dispose the old connection Reference< XComponent > xComp(m_xOriginalConnection, UNO_QUERY); if (xComp.is()) xComp->dispose(); m_xOriginalConnection.clear(); } catch(Exception&) { OSL_ENSURE(sal_False, "OAutoConnectionDisposer::clearConnection: caught an exception!"); } } //--------------------------------------------------------------------- void SAL_CALL OAutoConnectionDisposer::cursorMoved( const ::com::sun::star::lang::EventObject& event ) throw (::com::sun::star::uno::RuntimeException) { } //--------------------------------------------------------------------- void SAL_CALL OAutoConnectionDisposer::rowChanged( const ::com::sun::star::lang::EventObject& event ) throw (::com::sun::star::uno::RuntimeException) { } //--------------------------------------------------------------------- void SAL_CALL OAutoConnectionDisposer::rowSetChanged( const ::com::sun::star::lang::EventObject& event ) throw (::com::sun::star::uno::RuntimeException) { stopRowSetListening(); clearConnection(); } //--------------------------------------------------------------------- //......................................................................... } // namespace dbtools //......................................................................... <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dbexception.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: oj $ $Date: 2000-10-24 15:00:32 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_ #include <com/sun/star/sdb/SQLContext.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_ #include <com/sun/star/sdbc/SQLWarning.hpp> #endif #ifndef _COM_SUN_STAR_SDB_SQLERROREVENT_HPP_ #include <com/sun/star/sdb/SQLErrorEvent.hpp> #endif #define CONNECTIVITY_PROPERTY_NAME_SPACE dbtools #ifndef _CONNECTIVITY_PROPERTYIDS_HXX_ #include "propertyids.hxx" #endif using namespace comphelper; //......................................................................... namespace dbtools { //......................................................................... using namespace connectivity::dbtools; //============================================================================== //= SQLExceptionInfo - encapsulating the type info of an SQLException-derived class //============================================================================== //------------------------------------------------------------------------------ SQLExceptionInfo::SQLExceptionInfo() :m_eType(UNDEFINED) { } //------------------------------------------------------------------------------ SQLExceptionInfo::SQLExceptionInfo(const ::com::sun::star::sdbc::SQLException& _rError) { m_aContent <<= _rError; implDetermineType(); } //------------------------------------------------------------------------------ SQLExceptionInfo::SQLExceptionInfo(const ::com::sun::star::sdbc::SQLWarning& _rError) { m_aContent <<= _rError; implDetermineType(); } //------------------------------------------------------------------------------ SQLExceptionInfo::SQLExceptionInfo(const ::com::sun::star::sdb::SQLContext& _rError) { m_aContent <<= _rError; implDetermineType(); } //------------------------------------------------------------------------------ SQLExceptionInfo::SQLExceptionInfo(const SQLExceptionInfo& _rCopySource) :m_aContent(_rCopySource.m_aContent) ,m_eType(_rCopySource.m_eType) { } //------------------------------------------------------------------------------ SQLExceptionInfo::SQLExceptionInfo(const ::com::sun::star::sdb::SQLErrorEvent& _rError) { const staruno::Type& aSQLExceptionType = ::getCppuType(reinterpret_cast< ::com::sun::star::sdbc::SQLException*>(NULL)); staruno::Type aReasonType = _rError.Reason.getValueType(); sal_Bool bValid = isAssignableFrom(aSQLExceptionType, aReasonType); OSL_ENSHURE(bValid, "SQLExceptionInfo::SQLExceptionInfo : invalid argument (does not contain an SQLException) !"); if (bValid) m_aContent = _rError.Reason; implDetermineType(); } //------------------------------------------------------------------------------ SQLExceptionInfo::SQLExceptionInfo(const staruno::Any& _rError) { const staruno::Type& aSQLExceptionType = ::getCppuType(reinterpret_cast< ::com::sun::star::sdbc::SQLException*>(NULL)); sal_Bool bValid = isAssignableFrom(aSQLExceptionType, _rError.getValueType()); if (bValid) m_aContent = _rError; // no assertion here : if used with the NextException member of an SQLException bValid==sal_False is allowed. implDetermineType(); } //------------------------------------------------------------------------------ void SQLExceptionInfo::implDetermineType() { staruno::Type aContentType = m_aContent.getValueType(); if (isA(aContentType, static_cast< ::com::sun::star::sdb::SQLContext*>(NULL))) m_eType = SQL_CONTEXT; else if (isA(aContentType, static_cast< ::com::sun::star::sdbc::SQLWarning*>(NULL))) m_eType = SQL_WARNING; else if (isA(aContentType, static_cast< ::com::sun::star::sdbc::SQLException*>(NULL))) m_eType = SQL_EXCEPTION; else m_eType = UNDEFINED; } //------------------------------------------------------------------------------ sal_Bool SQLExceptionInfo::isKindOf(TYPE _eType) const { switch (_eType) { case SQL_CONTEXT: return (m_eType == SQL_CONTEXT); case SQL_WARNING: return (m_eType == SQL_CONTEXT) || (m_eType == SQL_WARNING); case SQL_EXCEPTION: return (m_eType == SQL_CONTEXT) || (m_eType == SQL_WARNING) || (m_eType == SQL_EXCEPTION); case UNDEFINED: return (m_eType == UNDEFINED); } return sal_False; } //------------------------------------------------------------------------------ SQLExceptionInfo::operator const ::com::sun::star::sdbc::SQLException*() const { OSL_ENSHURE(isKindOf(SQL_EXCEPTION), "SQLExceptionInfo::operator SQLException* : invalid call !"); return reinterpret_cast<const ::com::sun::star::sdbc::SQLException*>(m_aContent.getValue()); } //------------------------------------------------------------------------------ SQLExceptionInfo::operator const ::com::sun::star::sdbc::SQLWarning*() const { OSL_ENSHURE(isKindOf(SQL_WARNING), "SQLExceptionInfo::operator SQLException* : invalid call !"); return reinterpret_cast<const ::com::sun::star::sdbc::SQLWarning*>(m_aContent.getValue()); } //------------------------------------------------------------------------------ SQLExceptionInfo::operator const ::com::sun::star::sdb::SQLContext*() const { OSL_ENSHURE(isKindOf(SQL_CONTEXT), "SQLExceptionInfo::operator SQLException* : invalid call !"); return reinterpret_cast<const ::com::sun::star::sdb::SQLContext*>(m_aContent.getValue()); } //============================================================================== //= SQLExceptionIteratorHelper - iterating through an SQLException chain //============================================================================== //------------------------------------------------------------------------------ SQLExceptionIteratorHelper::SQLExceptionIteratorHelper(const ::com::sun::star::sdbc::SQLException* _pStart, NODES_INCLUDED _eMask) :m_pCurrent(_pStart) ,m_eCurrentType(SQLExceptionInfo::SQL_EXCEPTION) // no other chance without RTTI ,m_eMask(_eMask) { // initially check the start of the chain against the include mask if (m_pCurrent && (m_eMask >= NI_EXCEPTIONS)) next(); } //------------------------------------------------------------------------------ SQLExceptionIteratorHelper::SQLExceptionIteratorHelper(const ::com::sun::star::sdbc::SQLWarning* _pStart, NODES_INCLUDED _eMask) :m_pCurrent(_pStart) ,m_eCurrentType(SQLExceptionInfo::SQL_WARNING) // no other chance without RTTI ,m_eMask(_eMask) { // initially check the start of the chain against the include mask if (m_pCurrent && (m_eMask >= NI_WARNINGS)) next(); } //------------------------------------------------------------------------------ SQLExceptionIteratorHelper::SQLExceptionIteratorHelper(const ::com::sun::star::sdb::SQLContext* _pStart, NODES_INCLUDED _eMask) :m_pCurrent(_pStart) ,m_eCurrentType(SQLExceptionInfo::SQL_CONTEXT) // no other chance without RTTI ,m_eMask(_eMask) { // initially check the start of the chain against the include mask if (m_pCurrent && (m_eMask >= NI_CONTEXTINFOS)) next(); } //------------------------------------------------------------------------------ const ::com::sun::star::sdbc::SQLException* SQLExceptionIteratorHelper::next() { OSL_ENSHURE(hasMoreElements(), "SQLExceptionIteratorHelper::next : invalid call (please use hasMoreElements) !"); const ::com::sun::star::sdbc::SQLException* pReturn = m_pCurrent; if (m_pCurrent) { // check for the next element within the chain const staruno::Type& aSqlExceptionCompare = ::getCppuType(reinterpret_cast< ::com::sun::star::sdbc::SQLException*>(NULL)); const staruno::Type& aSqlWarningCompare = ::getCppuType(reinterpret_cast< ::com::sun::star::sdbc::SQLWarning*>(NULL)); const staruno::Type& aSqlContextCompare = ::getCppuType(reinterpret_cast< ::com::sun::star::sdb::SQLContext*>(NULL)); const ::com::sun::star::sdbc::SQLException* pSearch = m_pCurrent; SQLExceptionInfo::TYPE eSearchType = m_eCurrentType; sal_Bool bIncludeThis = sal_False; while (pSearch && !bIncludeThis) { if (!pSearch->NextException.hasValue()) { // last chain element pSearch = NULL; break; } staruno::Type aNextElementType = pSearch->NextException.getValueType(); if (!isAssignableFrom(aSqlExceptionCompare, aNextElementType)) { // the next chain element isn't an SQLException OSL_ENSHURE(sal_False, "SQLExceptionIteratorHelper::next : the exception chain is invalid !"); pSearch = NULL; break; } // the next element SQLExceptionInfo aInfo(pSearch->NextException); eSearchType = aInfo.getType(); switch (eSearchType) { case SQLExceptionInfo::SQL_CONTEXT: pSearch = reinterpret_cast<const ::com::sun::star::sdb::SQLContext*>(pSearch->NextException.getValue()); bIncludeThis = eSearchType >= NI_CONTEXTINFOS; break; case SQLExceptionInfo::SQL_WARNING: pSearch = reinterpret_cast<const ::com::sun::star::sdbc::SQLWarning*>(pSearch->NextException.getValue()); bIncludeThis = eSearchType >= NI_WARNINGS; break; case SQLExceptionInfo::SQL_EXCEPTION: pSearch = reinterpret_cast<const ::com::sun::star::sdbc::SQLException*>(pSearch->NextException.getValue()); bIncludeThis = eSearchType >= NI_EXCEPTIONS; break; default: pSearch = NULL; bIncludeThis = sal_False; break; } } m_pCurrent = pSearch; m_eCurrentType = eSearchType; } return pReturn; } using namespace ::com::sun::star::uno; //============================================================ //= FunctionSequenceException //============================================================ FunctionSequenceException::FunctionSequenceException(const Reference< XInterface >& _Context, const Any& _Next) :SQLException(ERRORMSG_SEQUENCE, _Context, SQLSTATE_SEQUENCE, 0, _Next){}; //......................................................................... } // namespace dbtools //......................................................................... /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.1 2000/10/05 08:50:41 fs * moved the files from unotools to here * * * Revision 1.0 29.09.00 08:17:11 fs ************************************************************************/ <commit_msg>corrected the initial setting of the SQLExceptionInfo<commit_after>/************************************************************************* * * $RCSfile: dbexception.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: fs $ $Date: 2000-11-08 18:54:44 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_ #include <com/sun/star/sdb/SQLContext.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_ #include <com/sun/star/sdbc/SQLWarning.hpp> #endif #ifndef _COM_SUN_STAR_SDB_SQLERROREVENT_HPP_ #include <com/sun/star/sdb/SQLErrorEvent.hpp> #endif #define CONNECTIVITY_PROPERTY_NAME_SPACE dbtools #ifndef _CONNECTIVITY_PROPERTYIDS_HXX_ #include "propertyids.hxx" #endif using namespace comphelper; //......................................................................... namespace dbtools { //......................................................................... using namespace connectivity::dbtools; //============================================================================== //= SQLExceptionInfo - encapsulating the type info of an SQLException-derived class //============================================================================== //------------------------------------------------------------------------------ SQLExceptionInfo::SQLExceptionInfo() :m_eType(UNDEFINED) { } //------------------------------------------------------------------------------ SQLExceptionInfo::SQLExceptionInfo(const ::com::sun::star::sdbc::SQLException& _rError) { m_aContent <<= _rError; implDetermineType(); } //------------------------------------------------------------------------------ SQLExceptionInfo::SQLExceptionInfo(const ::com::sun::star::sdbc::SQLWarning& _rError) { m_aContent <<= _rError; implDetermineType(); } //------------------------------------------------------------------------------ SQLExceptionInfo::SQLExceptionInfo(const ::com::sun::star::sdb::SQLContext& _rError) { m_aContent <<= _rError; implDetermineType(); } //------------------------------------------------------------------------------ SQLExceptionInfo::SQLExceptionInfo(const SQLExceptionInfo& _rCopySource) :m_aContent(_rCopySource.m_aContent) ,m_eType(_rCopySource.m_eType) { } //------------------------------------------------------------------------------ SQLExceptionInfo::SQLExceptionInfo(const ::com::sun::star::sdb::SQLErrorEvent& _rError) { const staruno::Type& aSQLExceptionType = ::getCppuType(reinterpret_cast< ::com::sun::star::sdbc::SQLException*>(NULL)); staruno::Type aReasonType = _rError.Reason.getValueType(); sal_Bool bValid = isAssignableFrom(aSQLExceptionType, aReasonType); OSL_ENSHURE(bValid, "SQLExceptionInfo::SQLExceptionInfo : invalid argument (does not contain an SQLException) !"); if (bValid) m_aContent = _rError.Reason; implDetermineType(); } //------------------------------------------------------------------------------ SQLExceptionInfo::SQLExceptionInfo(const staruno::Any& _rError) { const staruno::Type& aSQLExceptionType = ::getCppuType(reinterpret_cast< ::com::sun::star::sdbc::SQLException*>(NULL)); sal_Bool bValid = isAssignableFrom(aSQLExceptionType, _rError.getValueType()); if (bValid) m_aContent = _rError; // no assertion here : if used with the NextException member of an SQLException bValid==sal_False is allowed. implDetermineType(); } //------------------------------------------------------------------------------ void SQLExceptionInfo::implDetermineType() { staruno::Type aContentType = m_aContent.getValueType(); if (isA(aContentType, static_cast< ::com::sun::star::sdb::SQLContext*>(NULL))) m_eType = SQL_CONTEXT; else if (isA(aContentType, static_cast< ::com::sun::star::sdbc::SQLWarning*>(NULL))) m_eType = SQL_WARNING; else if (isA(aContentType, static_cast< ::com::sun::star::sdbc::SQLException*>(NULL))) m_eType = SQL_EXCEPTION; else m_eType = UNDEFINED; } //------------------------------------------------------------------------------ sal_Bool SQLExceptionInfo::isKindOf(TYPE _eType) const { switch (_eType) { case SQL_CONTEXT: return (m_eType == SQL_CONTEXT); case SQL_WARNING: return (m_eType == SQL_CONTEXT) || (m_eType == SQL_WARNING); case SQL_EXCEPTION: return (m_eType == SQL_CONTEXT) || (m_eType == SQL_WARNING) || (m_eType == SQL_EXCEPTION); case UNDEFINED: return (m_eType == UNDEFINED); } return sal_False; } //------------------------------------------------------------------------------ SQLExceptionInfo::operator const ::com::sun::star::sdbc::SQLException*() const { OSL_ENSHURE(isKindOf(SQL_EXCEPTION), "SQLExceptionInfo::operator SQLException* : invalid call !"); return reinterpret_cast<const ::com::sun::star::sdbc::SQLException*>(m_aContent.getValue()); } //------------------------------------------------------------------------------ SQLExceptionInfo::operator const ::com::sun::star::sdbc::SQLWarning*() const { OSL_ENSHURE(isKindOf(SQL_WARNING), "SQLExceptionInfo::operator SQLException* : invalid call !"); return reinterpret_cast<const ::com::sun::star::sdbc::SQLWarning*>(m_aContent.getValue()); } //------------------------------------------------------------------------------ SQLExceptionInfo::operator const ::com::sun::star::sdb::SQLContext*() const { OSL_ENSHURE(isKindOf(SQL_CONTEXT), "SQLExceptionInfo::operator SQLException* : invalid call !"); return reinterpret_cast<const ::com::sun::star::sdb::SQLContext*>(m_aContent.getValue()); } //============================================================================== //= SQLExceptionIteratorHelper - iterating through an SQLException chain //============================================================================== //------------------------------------------------------------------------------ SQLExceptionIteratorHelper::SQLExceptionIteratorHelper(const ::com::sun::star::sdbc::SQLException* _pStart, NODES_INCLUDED _eMask) :m_pCurrent(_pStart) ,m_eCurrentType(SQLExceptionInfo::SQL_EXCEPTION) // no other chance without RTTI ,m_eMask(_eMask) { // initially check the start of the chain against the include mask if (m_pCurrent && (m_eMask > NI_EXCEPTIONS)) next(); } //------------------------------------------------------------------------------ SQLExceptionIteratorHelper::SQLExceptionIteratorHelper(const ::com::sun::star::sdbc::SQLWarning* _pStart, NODES_INCLUDED _eMask) :m_pCurrent(_pStart) ,m_eCurrentType(SQLExceptionInfo::SQL_WARNING) // no other chance without RTTI ,m_eMask(_eMask) { // initially check the start of the chain against the include mask if (m_pCurrent && (m_eMask > NI_WARNINGS)) next(); } //------------------------------------------------------------------------------ SQLExceptionIteratorHelper::SQLExceptionIteratorHelper(const ::com::sun::star::sdb::SQLContext* _pStart, NODES_INCLUDED _eMask) :m_pCurrent(_pStart) ,m_eCurrentType(SQLExceptionInfo::SQL_CONTEXT) // no other chance without RTTI ,m_eMask(_eMask) { // initially check the start of the chain against the include mask if (m_pCurrent && (m_eMask > NI_CONTEXTINFOS)) next(); } //------------------------------------------------------------------------------ const ::com::sun::star::sdbc::SQLException* SQLExceptionIteratorHelper::next() { OSL_ENSHURE(hasMoreElements(), "SQLExceptionIteratorHelper::next : invalid call (please use hasMoreElements) !"); const ::com::sun::star::sdbc::SQLException* pReturn = m_pCurrent; if (m_pCurrent) { // check for the next element within the chain const staruno::Type& aSqlExceptionCompare = ::getCppuType(reinterpret_cast< ::com::sun::star::sdbc::SQLException*>(NULL)); const staruno::Type& aSqlWarningCompare = ::getCppuType(reinterpret_cast< ::com::sun::star::sdbc::SQLWarning*>(NULL)); const staruno::Type& aSqlContextCompare = ::getCppuType(reinterpret_cast< ::com::sun::star::sdb::SQLContext*>(NULL)); const ::com::sun::star::sdbc::SQLException* pSearch = m_pCurrent; SQLExceptionInfo::TYPE eSearchType = m_eCurrentType; sal_Bool bIncludeThis = sal_False; while (pSearch && !bIncludeThis) { if (!pSearch->NextException.hasValue()) { // last chain element pSearch = NULL; break; } staruno::Type aNextElementType = pSearch->NextException.getValueType(); if (!isAssignableFrom(aSqlExceptionCompare, aNextElementType)) { // the next chain element isn't an SQLException OSL_ENSHURE(sal_False, "SQLExceptionIteratorHelper::next : the exception chain is invalid !"); pSearch = NULL; break; } // the next element SQLExceptionInfo aInfo(pSearch->NextException); eSearchType = aInfo.getType(); switch (eSearchType) { case SQLExceptionInfo::SQL_CONTEXT: pSearch = reinterpret_cast<const ::com::sun::star::sdb::SQLContext*>(pSearch->NextException.getValue()); bIncludeThis = eSearchType >= NI_CONTEXTINFOS; break; case SQLExceptionInfo::SQL_WARNING: pSearch = reinterpret_cast<const ::com::sun::star::sdbc::SQLWarning*>(pSearch->NextException.getValue()); bIncludeThis = eSearchType >= NI_WARNINGS; break; case SQLExceptionInfo::SQL_EXCEPTION: pSearch = reinterpret_cast<const ::com::sun::star::sdbc::SQLException*>(pSearch->NextException.getValue()); bIncludeThis = eSearchType >= NI_EXCEPTIONS; break; default: pSearch = NULL; bIncludeThis = sal_False; break; } } m_pCurrent = pSearch; m_eCurrentType = eSearchType; } return pReturn; } using namespace ::com::sun::star::uno; //============================================================ //= FunctionSequenceException //============================================================ FunctionSequenceException::FunctionSequenceException(const Reference< XInterface >& _Context, const Any& _Next) :SQLException(ERRORMSG_SEQUENCE, _Context, SQLSTATE_SEQUENCE, 0, _Next){}; //......................................................................... } // namespace dbtools //......................................................................... /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.2 2000/10/24 15:00:32 oj * make strings unique for lib's * * Revision 1.1 2000/10/05 08:50:41 fs * moved the files from unotools to here * * * Revision 1.0 29.09.00 08:17:11 fs ************************************************************************/ <|endoftext|>
<commit_before>#include <iostream> #include "Utils.h" int main( int argc, char **argv ) { Utils* pUtil = new Utils; Utils Util; std::cout << pUtil->sumUp( -50 ) << std::endl; delete pUtil; } <commit_msg>indicated an intentional failure<commit_after>#include <iostream> #include "Utils.h" int main( int argc, char **argv ) { Utils* pUtil = new Utils; Utils Util; //this line should cause a comiler error std::cout << pUtil->sumUp( -50 ) << std::endl; delete pUtil; } <|endoftext|>
<commit_before>#include "FakeSerial.h" #include "wiring.h" #include <conio.h> #define RX_BUFFER_SIZE 512 struct ring_buffer { unsigned char buffer[RX_BUFFER_SIZE]; int head; int tail; }; ring_buffer rx_buffer = { { 0 }, 0, 0 }; inline void store_char(unsigned char c, ring_buffer *rx_buffer) { int i = (rx_buffer->head + 1) % RX_BUFFER_SIZE; if(i != rx_buffer->tail) { rx_buffer->buffer[rx_buffer->head] = c; rx_buffer->head = i; } } void read_stdin_to_buffer() { int c; while(kbhit()) { c = getch(); printf("c: %d\n", c); if(c == 0x03) { captureSigInt(0); } store_char((unsigned char)c, &rx_buffer); } } void FakeSerial::begin(long baud) { } uint8_t FakeSerial::available() { read_stdin_to_buffer(); return (RX_BUFFER_SIZE + rx_buffer.head - rx_buffer.tail) % RX_BUFFER_SIZE; } int FakeSerial::read() { printf("read\n"); if(rx_buffer.head == rx_buffer.tail) { return -1; } else { unsigned char c = rx_buffer.buffer[rx_buffer.tail]; rx_buffer.tail = (rx_buffer.tail + 1) % RX_BUFFER_SIZE; printf("c: %d\n", c); // Some substitution to return Serial chars switch(c) { case '\n': c = 13; break; } return c; } } void FakeSerial::end() { } void FakeSerial::write(uint8_t c) { putchar(c); } FakeSerial Serial; <commit_msg>Remove testing printfs<commit_after>#include "FakeSerial.h" #include "wiring.h" #include <conio.h> #define RX_BUFFER_SIZE 512 struct ring_buffer { unsigned char buffer[RX_BUFFER_SIZE]; int head; int tail; }; ring_buffer rx_buffer = { { 0 }, 0, 0 }; inline void store_char(unsigned char c, ring_buffer *rx_buffer) { int i = (rx_buffer->head + 1) % RX_BUFFER_SIZE; if(i != rx_buffer->tail) { rx_buffer->buffer[rx_buffer->head] = c; rx_buffer->head = i; } } void read_stdin_to_buffer() { int c; while(kbhit()) { c = getch(); if(c == 0x03) { captureSigInt(0); } store_char((unsigned char)c, &rx_buffer); } } void FakeSerial::begin(long baud) { } uint8_t FakeSerial::available() { read_stdin_to_buffer(); return (RX_BUFFER_SIZE + rx_buffer.head - rx_buffer.tail) % RX_BUFFER_SIZE; } int FakeSerial::read() { if(rx_buffer.head == rx_buffer.tail) { return -1; } else { unsigned char c = rx_buffer.buffer[rx_buffer.tail]; rx_buffer.tail = (rx_buffer.tail + 1) % RX_BUFFER_SIZE; // Some substitution to return Serial chars switch(c) { case '\n': c = 13; break; } return c; } } void FakeSerial::end() { } void FakeSerial::write(uint8_t c) { putchar(c); } FakeSerial Serial; <|endoftext|>
<commit_before><commit_msg>really do not write empty externalReferences element, fdo#45286 follow-up<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xmlsorti.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: sab $ $Date: 2001-07-26 06:51:20 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #include "xmlsorti.hxx" #include "xmlimprt.hxx" #include "docuno.hxx" #ifndef SC_CONVUNO_HXX #include "convuno.hxx" #endif #ifndef _SC_XMLCONVERTER_HXX #include "XMLConverter.hxx" #endif #ifndef SC_UNONAMES_HXX #include "unonames.hxx" #endif #include <xmloff/xmltkmap.hxx> #include <xmloff/nmspmap.hxx> #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #define SC_USERLIST "UserList" using namespace com::sun::star; using namespace xmloff::token; //------------------------------------------------------------------ ScXMLSortContext::ScXMLSortContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : bEnabledUserList(sal_False), bBindFormatsToContent(sal_True), bIsCaseSensitive(sal_False), bCopyOutputData(sal_False), sCountry(), sLanguage(), sAlgorithm(), SvXMLImportContext( rImport, nPrfx, rLName ) { pDatabaseRangeContext = pTempDatabaseRangeContext; nUserListIndex = 0; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetSortAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SORT_ATTR_BIND_STYLES_TO_CONTENT : { bBindFormatsToContent = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_SORT_ATTR_TARGET_RANGE_ADDRESS : { ScRange aScRange; sal_Int32 nOffset(0); if (ScXMLConverter::GetRangeFromString( aScRange, sValue, GetScImport().GetDocument(), nOffset )) { ScUnoConversion::FillApiAddress( aOutputPosition, aScRange.aStart ); bCopyOutputData = sal_True; } } break; case XML_TOK_SORT_ATTR_CASE_SENSITIVE : { bIsCaseSensitive = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_SORT_ATTR_LANGUAGE : sLanguage = sValue; break; case XML_TOK_SORT_ATTR_COUNTRY : sCountry = sValue; break; case XML_TOK_SORT_ATTR_ALGORITHM : sAlgorithm = sValue; break; } } } ScXMLSortContext::~ScXMLSortContext() { } SvXMLImportContext *ScXMLSortContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetScImport().GetSortElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_SORT_SORT_BY : { pContext = new ScXMLSortByContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSortContext::EndElement() { sal_Int32 nLangLength(sLanguage.getLength()); sal_Int32 nCountryLength(sCountry.getLength()); sal_Int32 nAlgoLength(sAlgorithm.getLength()); sal_uInt8 i (0); if (nLangLength || nCountryLength) i++; if (nAlgoLength) i++; uno::Sequence <beans::PropertyValue> aSortDescriptor(7 + i); uno::Any aTemp; beans::PropertyValue aPropertyValue; aTemp = ::cppu::bool2any(bBindFormatsToContent); aPropertyValue.Name = rtl::OUString::createFromAscii(SC_UNONAME_BINDFMT); aPropertyValue.Value = aTemp; aSortDescriptor[0] = aPropertyValue; aTemp = ::cppu::bool2any(bCopyOutputData); aPropertyValue.Name = rtl::OUString::createFromAscii(SC_UNONAME_COPYOUT); aPropertyValue.Value = aTemp; aSortDescriptor[1] = aPropertyValue; aTemp = ::cppu::bool2any(bIsCaseSensitive); aPropertyValue.Name = rtl::OUString::createFromAscii(SC_UNONAME_ISCASE); aPropertyValue.Value = aTemp; aSortDescriptor[2] = aPropertyValue; aTemp = ::cppu::bool2any(bEnabledUserList); aPropertyValue.Name = rtl::OUString::createFromAscii(SC_UNONAME_ISULIST); aPropertyValue.Value = aTemp; aSortDescriptor[3] = aPropertyValue; aTemp <<= aOutputPosition; aPropertyValue.Name = rtl::OUString::createFromAscii(SC_UNONAME_OUTPOS); aPropertyValue.Value = aTemp; aSortDescriptor[4] = aPropertyValue; aTemp <<= nUserListIndex; aPropertyValue.Name = rtl::OUString::createFromAscii(SC_UNONAME_UINDEX); aPropertyValue.Value = aTemp; aSortDescriptor[5] = aPropertyValue; aTemp <<= aSortFields; aPropertyValue.Name = rtl::OUString::createFromAscii(SC_UNONAME_SORTFLD); aPropertyValue.Value = aTemp; aSortDescriptor[6] = aPropertyValue; if (nLangLength || nCountryLength) { lang::Locale aLocale; aLocale.Language = sLanguage; aLocale.Country = sCountry; aTemp <<= aLocale; aPropertyValue.Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_COLLLOC)); aPropertyValue.Value = aTemp; aSortDescriptor[7] = aPropertyValue; } if (nAlgoLength) { aTemp <<= sAlgorithm; aPropertyValue.Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_COLLALG)); aPropertyValue.Value = aTemp; aSortDescriptor[6 + i] = aPropertyValue; } pDatabaseRangeContext->SetSortSequence(aSortDescriptor); } void ScXMLSortContext::AddSortField(const rtl::OUString& sFieldNumber, const rtl::OUString& sDataType, const rtl::OUString& sOrder) { util::SortField aSortField; aSortField.Field = sFieldNumber.toInt32(); if (IsXMLToken(sOrder, XML_ASCENDING)) aSortField.SortAscending = sal_True; else aSortField.SortAscending = sal_False; if (sDataType.getLength() > 8) { rtl::OUString sTemp = sDataType.copy(0, 8); if (sTemp.compareToAscii(SC_USERLIST) == 0) { bEnabledUserList = sal_True; sTemp = sDataType.copy(8); nUserListIndex = static_cast<sal_Int16>(sTemp.toInt32()); } else { if (IsXMLToken(sDataType, XML_AUTOMATIC)) aSortField.FieldType = util::SortFieldType_AUTOMATIC; } } else { if (IsXMLToken(sDataType, XML_TEXT)) aSortField.FieldType = util::SortFieldType_ALPHANUMERIC; else if (IsXMLToken(sDataType, XML_NUMBER)) aSortField.FieldType = util::SortFieldType_NUMERIC; } aSortFields.realloc(aSortFields.getLength() + 1); aSortFields[aSortFields.getLength() - 1] = aSortField; } ScXMLSortByContext::ScXMLSortByContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLSortContext* pTempSortContext) : SvXMLImportContext( rImport, nPrfx, rLName ), sOrder(GetXMLToken(XML_ASCENDING)), sDataType(GetXMLToken(XML_AUTOMATIC)) { pSortContext = pTempSortContext; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetSortSortByAttrTokenMap(); for( sal_Int16 i=0; i < nAttrCount; i++ ) { rtl::OUString sAttrName = xAttrList->getNameByIndex( i ); rtl::OUString aLocalName; USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName ); rtl::OUString sValue = xAttrList->getValueByIndex( i ); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SORT_BY_ATTR_FIELD_NUMBER : { sFieldNumber = sValue; } break; case XML_TOK_SORT_BY_ATTR_DATA_TYPE : { sDataType = sValue; } break; case XML_TOK_SORT_BY_ATTR_ORDER : { sOrder = sValue; } break; } } } ScXMLSortByContext::~ScXMLSortByContext() { } SvXMLImportContext *ScXMLSortByContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext = 0; if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSortByContext::EndElement() { pSortContext->AddSortField(sFieldNumber, sDataType, sOrder); } <commit_msg>INTEGRATION: CWS calcuno01 (1.12.332); FILE MERGED 2004/01/05 11:57:11 sab 1.12.332.1: #i22706#; improve API using<commit_after>/************************************************************************* * * $RCSfile: xmlsorti.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: vg $ $Date: 2005-03-23 13:01:52 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #include "xmlsorti.hxx" #include "xmlimprt.hxx" #include "docuno.hxx" #ifndef SC_CONVUNO_HXX #include "convuno.hxx" #endif #ifndef _SC_XMLCONVERTER_HXX #include "XMLConverter.hxx" #endif #ifndef SC_UNONAMES_HXX #include "unonames.hxx" #endif #include <xmloff/xmltkmap.hxx> #include <xmloff/nmspmap.hxx> #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #define SC_USERLIST "UserList" using namespace com::sun::star; using namespace xmloff::token; //------------------------------------------------------------------ ScXMLSortContext::ScXMLSortContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLDatabaseRangeContext* pTempDatabaseRangeContext) : SvXMLImportContext( rImport, nPrfx, rLName ), bEnabledUserList(sal_False), bBindFormatsToContent(sal_True), bIsCaseSensitive(sal_False), bCopyOutputData(sal_False), sCountry(), sLanguage(), sAlgorithm(), pDatabaseRangeContext(pTempDatabaseRangeContext), nUserListIndex(0) { sal_Int16 nAttrCount(xAttrList.is() ? xAttrList->getLength() : 0); const SvXMLTokenMap& rAttrTokenMap(GetScImport().GetSortAttrTokenMap()); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix(GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName )); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SORT_ATTR_BIND_STYLES_TO_CONTENT : { bBindFormatsToContent = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_SORT_ATTR_TARGET_RANGE_ADDRESS : { ScRange aScRange; sal_Int32 nOffset(0); if (ScXMLConverter::GetRangeFromString( aScRange, sValue, GetScImport().GetDocument(), nOffset )) { ScUnoConversion::FillApiAddress( aOutputPosition, aScRange.aStart ); bCopyOutputData = sal_True; } } break; case XML_TOK_SORT_ATTR_CASE_SENSITIVE : { bIsCaseSensitive = IsXMLToken(sValue, XML_TRUE); } break; case XML_TOK_SORT_ATTR_LANGUAGE : sLanguage = sValue; break; case XML_TOK_SORT_ATTR_COUNTRY : sCountry = sValue; break; case XML_TOK_SORT_ATTR_ALGORITHM : sAlgorithm = sValue; break; } } } ScXMLSortContext::~ScXMLSortContext() { } SvXMLImportContext *ScXMLSortContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { SvXMLImportContext *pContext(0); const SvXMLTokenMap& rTokenMap(GetScImport().GetSortElemTokenMap()); switch( rTokenMap.Get( nPrefix, rLName ) ) { case XML_TOK_SORT_SORT_BY : { pContext = new ScXMLSortByContext( GetScImport(), nPrefix, rLName, xAttrList, this); } break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName ); return pContext; } void ScXMLSortContext::EndElement() { sal_Int32 nLangLength(sLanguage.getLength()); sal_Int32 nCountryLength(sCountry.getLength()); sal_Int32 nAlgoLength(sAlgorithm.getLength()); sal_uInt8 i (0); if (nLangLength || nCountryLength) ++i; if (nAlgoLength) ++i; uno::Sequence <beans::PropertyValue> aSortDescriptor(7 + i); aSortDescriptor[0].Name = rtl::OUString::createFromAscii(SC_UNONAME_BINDFMT); aSortDescriptor[0].Value = ::cppu::bool2any(bBindFormatsToContent); aSortDescriptor[1].Name = rtl::OUString::createFromAscii(SC_UNONAME_COPYOUT); aSortDescriptor[1].Value = ::cppu::bool2any(bCopyOutputData); aSortDescriptor[2].Name = rtl::OUString::createFromAscii(SC_UNONAME_ISCASE); aSortDescriptor[2].Value = ::cppu::bool2any(bIsCaseSensitive); aSortDescriptor[3].Name = rtl::OUString::createFromAscii(SC_UNONAME_ISULIST); aSortDescriptor[3].Value = ::cppu::bool2any(bEnabledUserList); aSortDescriptor[4].Name = rtl::OUString::createFromAscii(SC_UNONAME_OUTPOS); aSortDescriptor[4].Value <<= aOutputPosition; aSortDescriptor[5].Name = rtl::OUString::createFromAscii(SC_UNONAME_UINDEX); aSortDescriptor[5].Value <<= nUserListIndex; aSortDescriptor[6].Name = rtl::OUString::createFromAscii(SC_UNONAME_SORTFLD); aSortDescriptor[6].Value <<= aSortFields; if (nLangLength || nCountryLength) { lang::Locale aLocale; aLocale.Language = sLanguage; aLocale.Country = sCountry; aSortDescriptor[7].Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_COLLLOC)); aSortDescriptor[7].Value <<= aLocale; } if (nAlgoLength) { aSortDescriptor[6 + i].Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNONAME_COLLALG)); aSortDescriptor[6 + i].Value <<= sAlgorithm; } pDatabaseRangeContext->SetSortSequence(aSortDescriptor); } void ScXMLSortContext::AddSortField(const rtl::OUString& sFieldNumber, const rtl::OUString& sDataType, const rtl::OUString& sOrder) { util::SortField aSortField; aSortField.Field = sFieldNumber.toInt32(); if (IsXMLToken(sOrder, XML_ASCENDING)) aSortField.SortAscending = sal_True; else aSortField.SortAscending = sal_False; if (sDataType.getLength() > 8) { rtl::OUString sTemp = sDataType.copy(0, 8); if (sTemp.compareToAscii(SC_USERLIST) == 0) { bEnabledUserList = sal_True; sTemp = sDataType.copy(8); nUserListIndex = static_cast<sal_Int16>(sTemp.toInt32()); } else { if (IsXMLToken(sDataType, XML_AUTOMATIC)) aSortField.FieldType = util::SortFieldType_AUTOMATIC; } } else { if (IsXMLToken(sDataType, XML_TEXT)) aSortField.FieldType = util::SortFieldType_ALPHANUMERIC; else if (IsXMLToken(sDataType, XML_NUMBER)) aSortField.FieldType = util::SortFieldType_NUMERIC; } aSortFields.realloc(aSortFields.getLength() + 1); aSortFields[aSortFields.getLength() - 1] = aSortField; } ScXMLSortByContext::ScXMLSortByContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList, ScXMLSortContext* pTempSortContext) : SvXMLImportContext( rImport, nPrfx, rLName ), sOrder(GetXMLToken(XML_ASCENDING)), sDataType(GetXMLToken(XML_AUTOMATIC)), pSortContext(pTempSortContext) { sal_Int16 nAttrCount(xAttrList.is() ? xAttrList->getLength() : 0); const SvXMLTokenMap& rAttrTokenMap(GetScImport().GetSortSortByAttrTokenMap()); for( sal_Int16 i=0; i < nAttrCount; ++i ) { const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i )); rtl::OUString aLocalName; USHORT nPrefix(GetScImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName )); const rtl::OUString& sValue(xAttrList->getValueByIndex( i )); switch( rAttrTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_SORT_BY_ATTR_FIELD_NUMBER : { sFieldNumber = sValue; } break; case XML_TOK_SORT_BY_ATTR_DATA_TYPE : { sDataType = sValue; } break; case XML_TOK_SORT_BY_ATTR_ORDER : { sOrder = sValue; } break; } } } ScXMLSortByContext::~ScXMLSortByContext() { } SvXMLImportContext *ScXMLSortByContext::CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ) { return new SvXMLImportContext( GetImport(), nPrefix, rLName ); } void ScXMLSortByContext::EndElement() { pSortContext->AddSortField(sFieldNumber, sDataType, sOrder); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xmlsubti.hxx,v $ * * $Revision: 1.27 $ * * last change: $Author: vg $ $Date: 2005-03-23 13:03:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_XMLSUBTI_HXX #define SC_XMLSUBTI_HXX #ifndef _XMLOFF_XMLICTXT_HXX #include <xmloff/xmlictxt.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _COM_SUN_STAR_SHEET_XSPREADSHEET_HPP_ #include <com/sun/star/sheet/XSpreadsheet.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_ #include <com/sun/star/drawing/XDrawPage.hpp> #endif #ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_ #include <com/sun/star/table/CellAddress.hpp> #endif #ifndef _COM_SUN_STAR_TABLE_XCELLRANGE_HPP_ #include <com/sun/star/table/XCellRange.hpp> #endif #ifndef _COM_SUN_STAR_TABLE_CELLRANGEADDRESS_HPP_ #include <com/sun/star/table/CellRangeAddress.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef __SGI_STL_VECTOR #include <vector> #endif #include <list> #ifndef _SC_XMLTABLESHAPERESIZER_HXX #include "XMLTableShapeResizer.hxx" #endif class ScXMLImport; typedef std::vector<sal_Int32> ScMysalIntVec; typedef std::list<sal_Int32> ScMysalIntList; const ScMysalIntVec::size_type nDefaultRowCount = 20; const ScMysalIntVec::size_type nDefaultColCount = 20; const ScMysalIntVec::size_type nDefaultTabCount = 10; class ScMyTableData { private: com::sun::star::table::CellAddress aTableCellPos; ScMysalIntVec nColsPerCol; ScMysalIntVec nRealCols; ScMysalIntVec nRowsPerRow; ScMysalIntVec nRealRows; sal_Int32 nSpannedCols; sal_Int32 nColCount; sal_Int32 nSubTableSpanned; ScMysalIntList nChangedCols; public: ScMyTableData(sal_Int32 nSheet = -1, sal_Int32 nCol = -1, sal_Int32 nRow = -1); ~ScMyTableData(); com::sun::star::table::CellAddress GetCellPos() const { return aTableCellPos; } sal_Int32 GetRow() const { return aTableCellPos.Row; } sal_Int32 GetColumn() const { return aTableCellPos.Column; } void AddRow(); void AddColumn(); void SetFirstColumn() { aTableCellPos.Column = -1; } sal_Int32 FindNextCol(const sal_Int32 nIndex) const; sal_Int32 GetColsPerCol(const sal_Int32 nIndex) const { return nColsPerCol[nIndex]; } void SetColsPerCol(const sal_Int32 nIndex, sal_Int32 nValue = 1) { nColsPerCol[nIndex] = nValue; } sal_Int32 GetRealCols(const sal_Int32 nIndex, const sal_Bool bIsNormal = sal_True) const; void SetRealCols(const sal_Int32 nIndex, const sal_Int32 nValue) { nRealCols[nIndex] = nValue; } sal_Int32 GetRowsPerRow(const sal_Int32 nIndex) const { return nRowsPerRow[nIndex]; } void SetRowsPerRow(const sal_Int32 nIndex, const sal_Int32 nValue = 1) { nRowsPerRow[nIndex] = nValue; } sal_Int32 GetRealRows(const sal_Int32 nIndex) const { return nIndex < 0 ? 0 : nRealRows[nIndex]; } void SetRealRows(const sal_Int32 nIndex, const sal_Int32 nValue) { nRealRows[nIndex] = nValue; } sal_Int32 GetSpannedCols() const { return nSpannedCols; } void SetSpannedCols(const sal_Int32 nTempSpannedCols) { nSpannedCols = nTempSpannedCols; } sal_Int32 GetColCount() const { return nColCount; } void SetColCount(const sal_Int32 nTempColCount) { nColCount = nTempColCount; } sal_Int32 GetSubTableSpanned() const { return nSubTableSpanned; } void SetSubTableSpanned(const sal_Int32 nValue) { nSubTableSpanned = nValue; } sal_Int32 GetChangedCols(const sal_Int32 nFromIndex, const sal_Int32 nToIndex) const; void SetChangedCols(const sal_Int32 nValue); }; //******************************************************************************************************************************* struct ScMatrixRange { rtl::OUString sFormula; com::sun::star::table::CellRangeAddress aRange; ScMatrixRange(const com::sun::star::table::CellRangeAddress& rRange, const rtl::OUString& rFormula) : aRange(rRange), sFormula(rFormula) { } }; class ScMyTables { private: typedef std::list<ScMatrixRange> ScMyMatrixRangeList; ScXMLImport& rImport; ScMyShapeResizer aResizeShapes; ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet > xCurrentSheet; ::com::sun::star::uno::Reference< ::com::sun::star::table::XCellRange > xCurrentCellRange; ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage > xDrawPage; ::com::sun::star::uno::Reference < ::com::sun::star::drawing::XShapes > xShapes; rtl::OUString sCurrentSheetName; rtl::OUString sPassword; std::vector<ScMyTableData*> aTableVec; ScMyMatrixRangeList aMatrixRangeList; com::sun::star::table::CellAddress aRealCellPos; sal_Int32 nCurrentColStylePos; sal_Int16 nCurrentDrawPage; sal_Int16 nCurrentXShapes; sal_Int32 nTableCount; sal_Int32 nCurrentSheet; sal_Bool bProtection; sal_Bool IsMerged (const com::sun::star::uno::Reference <com::sun::star::table::XCellRange>& xCellRange, const sal_Int32 nCol, const sal_Int32 nRow, com::sun::star::table::CellRangeAddress& aCellAddress) const; void UnMerge(); void DoMerge(sal_Int32 nCount = -1); void InsertRow(); void NewRow(); void InsertColumn(); void NewColumn(sal_Bool bIsCovered); public: ScMyTables(ScXMLImport& rImport); ~ScMyTables(); void NewSheet(const rtl::OUString& sTableName, const rtl::OUString& sStyleName, const sal_Bool bProtection, const rtl::OUString& sPassword); void AddRow(); void SetRowStyle(const rtl::OUString& rCellStyleName); void CloseRow(); void AddColumn(sal_Bool bIsCovered); void NewTable(sal_Int32 nTempSpannedCols); void UpdateRowHeights(); void ResizeShapes() { aResizeShapes.ResizeShapes(); } void DeleteTable(); com::sun::star::table::CellAddress GetRealCellPos(); void AddColCount(sal_Int32 nTempColCount); void AddColStyle(const sal_Int32 nRepeat, const rtl::OUString& rCellStyleName); rtl::OUString GetCurrentSheetName() const { return sCurrentSheetName; } sal_Int32 GetCurrentSheet() const { return nCurrentSheet; } sal_Int32 GetCurrentColumn() const { return aTableVec[nTableCount - 1]->GetColCount(); } sal_Int32 GetCurrentRow() const { return aTableVec[nTableCount - 1]->GetRow(); } ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet > GetCurrentXSheet() { return xCurrentSheet; } ::com::sun::star::uno::Reference< ::com::sun::star::table::XCellRange > GetCurrentXCellRange() { return xCurrentCellRange; } ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage > GetCurrentXDrawPage(); ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > GetCurrentXShapes(); sal_Bool HasDrawPage(); sal_Bool HasXShapes(); void AddShape(com::sun::star::uno::Reference <com::sun::star::drawing::XShape>& rShape, rtl::OUString* pRangeList, com::sun::star::table::CellAddress& rStartAddress, com::sun::star::table::CellAddress& rEndAddress, sal_Int32 nEndX, sal_Int32 nEndY); void AddMatrixRange(sal_Int32 nStartColumn, sal_Int32 nStartRow, sal_Int32 nEndColumn, sal_Int32 nEndRow, const rtl::OUString& rFormula); sal_Bool IsPartOfMatrix(sal_Int32 nColumn, sal_Int32 nRow); void SetMatrix(const com::sun::star::table::CellRangeAddress& rRange, const rtl::OUString& rFormula); }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.27.116); FILE MERGED 2005/09/05 15:03:45 rt 1.27.116.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlsubti.hxx,v $ * * $Revision: 1.28 $ * * last change: $Author: rt $ $Date: 2005-09-08 20:14:16 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_XMLSUBTI_HXX #define SC_XMLSUBTI_HXX #ifndef _XMLOFF_XMLICTXT_HXX #include <xmloff/xmlictxt.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _COM_SUN_STAR_SHEET_XSPREADSHEET_HPP_ #include <com/sun/star/sheet/XSpreadsheet.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_ #include <com/sun/star/drawing/XDrawPage.hpp> #endif #ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_ #include <com/sun/star/table/CellAddress.hpp> #endif #ifndef _COM_SUN_STAR_TABLE_XCELLRANGE_HPP_ #include <com/sun/star/table/XCellRange.hpp> #endif #ifndef _COM_SUN_STAR_TABLE_CELLRANGEADDRESS_HPP_ #include <com/sun/star/table/CellRangeAddress.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef __SGI_STL_VECTOR #include <vector> #endif #include <list> #ifndef _SC_XMLTABLESHAPERESIZER_HXX #include "XMLTableShapeResizer.hxx" #endif class ScXMLImport; typedef std::vector<sal_Int32> ScMysalIntVec; typedef std::list<sal_Int32> ScMysalIntList; const ScMysalIntVec::size_type nDefaultRowCount = 20; const ScMysalIntVec::size_type nDefaultColCount = 20; const ScMysalIntVec::size_type nDefaultTabCount = 10; class ScMyTableData { private: com::sun::star::table::CellAddress aTableCellPos; ScMysalIntVec nColsPerCol; ScMysalIntVec nRealCols; ScMysalIntVec nRowsPerRow; ScMysalIntVec nRealRows; sal_Int32 nSpannedCols; sal_Int32 nColCount; sal_Int32 nSubTableSpanned; ScMysalIntList nChangedCols; public: ScMyTableData(sal_Int32 nSheet = -1, sal_Int32 nCol = -1, sal_Int32 nRow = -1); ~ScMyTableData(); com::sun::star::table::CellAddress GetCellPos() const { return aTableCellPos; } sal_Int32 GetRow() const { return aTableCellPos.Row; } sal_Int32 GetColumn() const { return aTableCellPos.Column; } void AddRow(); void AddColumn(); void SetFirstColumn() { aTableCellPos.Column = -1; } sal_Int32 FindNextCol(const sal_Int32 nIndex) const; sal_Int32 GetColsPerCol(const sal_Int32 nIndex) const { return nColsPerCol[nIndex]; } void SetColsPerCol(const sal_Int32 nIndex, sal_Int32 nValue = 1) { nColsPerCol[nIndex] = nValue; } sal_Int32 GetRealCols(const sal_Int32 nIndex, const sal_Bool bIsNormal = sal_True) const; void SetRealCols(const sal_Int32 nIndex, const sal_Int32 nValue) { nRealCols[nIndex] = nValue; } sal_Int32 GetRowsPerRow(const sal_Int32 nIndex) const { return nRowsPerRow[nIndex]; } void SetRowsPerRow(const sal_Int32 nIndex, const sal_Int32 nValue = 1) { nRowsPerRow[nIndex] = nValue; } sal_Int32 GetRealRows(const sal_Int32 nIndex) const { return nIndex < 0 ? 0 : nRealRows[nIndex]; } void SetRealRows(const sal_Int32 nIndex, const sal_Int32 nValue) { nRealRows[nIndex] = nValue; } sal_Int32 GetSpannedCols() const { return nSpannedCols; } void SetSpannedCols(const sal_Int32 nTempSpannedCols) { nSpannedCols = nTempSpannedCols; } sal_Int32 GetColCount() const { return nColCount; } void SetColCount(const sal_Int32 nTempColCount) { nColCount = nTempColCount; } sal_Int32 GetSubTableSpanned() const { return nSubTableSpanned; } void SetSubTableSpanned(const sal_Int32 nValue) { nSubTableSpanned = nValue; } sal_Int32 GetChangedCols(const sal_Int32 nFromIndex, const sal_Int32 nToIndex) const; void SetChangedCols(const sal_Int32 nValue); }; //******************************************************************************************************************************* struct ScMatrixRange { rtl::OUString sFormula; com::sun::star::table::CellRangeAddress aRange; ScMatrixRange(const com::sun::star::table::CellRangeAddress& rRange, const rtl::OUString& rFormula) : aRange(rRange), sFormula(rFormula) { } }; class ScMyTables { private: typedef std::list<ScMatrixRange> ScMyMatrixRangeList; ScXMLImport& rImport; ScMyShapeResizer aResizeShapes; ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet > xCurrentSheet; ::com::sun::star::uno::Reference< ::com::sun::star::table::XCellRange > xCurrentCellRange; ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage > xDrawPage; ::com::sun::star::uno::Reference < ::com::sun::star::drawing::XShapes > xShapes; rtl::OUString sCurrentSheetName; rtl::OUString sPassword; std::vector<ScMyTableData*> aTableVec; ScMyMatrixRangeList aMatrixRangeList; com::sun::star::table::CellAddress aRealCellPos; sal_Int32 nCurrentColStylePos; sal_Int16 nCurrentDrawPage; sal_Int16 nCurrentXShapes; sal_Int32 nTableCount; sal_Int32 nCurrentSheet; sal_Bool bProtection; sal_Bool IsMerged (const com::sun::star::uno::Reference <com::sun::star::table::XCellRange>& xCellRange, const sal_Int32 nCol, const sal_Int32 nRow, com::sun::star::table::CellRangeAddress& aCellAddress) const; void UnMerge(); void DoMerge(sal_Int32 nCount = -1); void InsertRow(); void NewRow(); void InsertColumn(); void NewColumn(sal_Bool bIsCovered); public: ScMyTables(ScXMLImport& rImport); ~ScMyTables(); void NewSheet(const rtl::OUString& sTableName, const rtl::OUString& sStyleName, const sal_Bool bProtection, const rtl::OUString& sPassword); void AddRow(); void SetRowStyle(const rtl::OUString& rCellStyleName); void CloseRow(); void AddColumn(sal_Bool bIsCovered); void NewTable(sal_Int32 nTempSpannedCols); void UpdateRowHeights(); void ResizeShapes() { aResizeShapes.ResizeShapes(); } void DeleteTable(); com::sun::star::table::CellAddress GetRealCellPos(); void AddColCount(sal_Int32 nTempColCount); void AddColStyle(const sal_Int32 nRepeat, const rtl::OUString& rCellStyleName); rtl::OUString GetCurrentSheetName() const { return sCurrentSheetName; } sal_Int32 GetCurrentSheet() const { return nCurrentSheet; } sal_Int32 GetCurrentColumn() const { return aTableVec[nTableCount - 1]->GetColCount(); } sal_Int32 GetCurrentRow() const { return aTableVec[nTableCount - 1]->GetRow(); } ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet > GetCurrentXSheet() { return xCurrentSheet; } ::com::sun::star::uno::Reference< ::com::sun::star::table::XCellRange > GetCurrentXCellRange() { return xCurrentCellRange; } ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage > GetCurrentXDrawPage(); ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > GetCurrentXShapes(); sal_Bool HasDrawPage(); sal_Bool HasXShapes(); void AddShape(com::sun::star::uno::Reference <com::sun::star::drawing::XShape>& rShape, rtl::OUString* pRangeList, com::sun::star::table::CellAddress& rStartAddress, com::sun::star::table::CellAddress& rEndAddress, sal_Int32 nEndX, sal_Int32 nEndY); void AddMatrixRange(sal_Int32 nStartColumn, sal_Int32 nStartRow, sal_Int32 nEndColumn, sal_Int32 nEndRow, const rtl::OUString& rFormula); sal_Bool IsPartOfMatrix(sal_Int32 nColumn, sal_Int32 nRow); void SetMatrix(const com::sun::star::table::CellRangeAddress& rRange, const rtl::OUString& rFormula); }; #endif <|endoftext|>
<commit_before>//===--- ModuleAssistant.cpp - Module map generation manager -*- C++ -*---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===---------------------------------------------------------------------===// // // This file defines the module generation entry point function, // createModuleMap, a Module class for representing a module, // and various implementation functions for doing the underlying // work, described below. // // The "Module" class represents a module, with members for storing the module // name, associated header file names, and sub-modules, and an "output" // function that recursively writes the module definitions. // // The "createModuleMap" function implements the top-level logic of the // assistant mode. It calls a loadModuleDescriptions function to walk // the header list passed to it and creates a tree of Module objects // representing the module hierarchy, represented by a "Module" object, // the "RootModule". This root module may or may not represent an actual // module in the module map, depending on the "--root-module" option passed // to modularize. It then calls a writeModuleMap function to set up the // module map file output and walk the module tree, outputting the module // map file using a stream obtained and managed by an // llvm::tool_output_file object. // //===---------------------------------------------------------------------===// #include "Modularize.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/ToolOutputFile.h" #include <vector> // Local definitions: namespace { // Internal class definitions: // Represents a module. class Module { public: Module(llvm::StringRef Name); Module(); ~Module(); bool output(llvm::raw_fd_ostream &OS, int Indent); Module *findSubModule(llvm::StringRef SubName); public: std::string Name; std::vector<std::string> HeaderFileNames; std::vector<Module *> SubModules; }; } // end anonymous namespace. // Module functions: // Constructors. Module::Module(llvm::StringRef Name) : Name(Name) {} Module::Module() {} // Destructor. Module::~Module() { // Free submodules. while (SubModules.size()) { Module *last = SubModules.back(); SubModules.pop_back(); delete last; } } // Write a module hierarchy to the given output stream. bool Module::output(llvm::raw_fd_ostream &OS, int Indent) { // If this is not the nameless root module, start a module definition. if (Name.size() != 0) { OS.indent(Indent); OS << "module " << Name << " {\n"; Indent += 2; } // Output submodules. for (std::vector<Module *>::iterator I = SubModules.begin(), E = SubModules.end(); I != E; ++I) { if (!(*I)->output(OS, Indent)) return false; } // Output header files. for (std::vector<std::string>::iterator I = HeaderFileNames.begin(), E = HeaderFileNames.end(); I != E; ++I) { OS.indent(Indent); OS << "header \"" << *I << "\"\n"; } // If this module has header files, output export directive. if (HeaderFileNames.size() != 0) { OS.indent(Indent); OS << "export *\n"; } // If this is not the nameless root module, close the module definition. if (Name.size() != 0) { Indent -= 2; OS.indent(Indent); OS << "}\n"; } return true; } // Lookup a sub-module. Module *Module::findSubModule(llvm::StringRef SubName) { for (std::vector<Module *>::iterator I = SubModules.begin(), E = SubModules.end(); I != E; ++I) { if ((*I)->Name == SubName) return *I; } return 0; } // Implementation functions: // Reserved keywords in module.map syntax. // Keep in sync with keywords in module map parser in Lex/ModuleMap.cpp, // such as in ModuleMapParser::consumeToken(). static const char *ReservedNames[] = { "config_macros", "export", "module", "conflict", "framework", "requires", "exclude", "header", "private", "explicit", "link", "umbrella", "extern", "use", 0 // Flag end. }; // Convert module name to a non keyword. // Prepends a '_' to the name if and only if the name is a keyword. static std::string ensureNoCollisionWithReservedName(llvm::StringRef MightBeReservedName) { std::string SafeName = MightBeReservedName; for (int Index = 0; ReservedNames[Index] != 0; ++Index) { if (MightBeReservedName == ReservedNames[Index]) { SafeName.insert(0, "_"); break; } } return SafeName; } // Add one module, given a header file path. static bool addModuleDescription(Module *RootModule, llvm::StringRef HeaderFilePath, llvm::StringRef HeaderPrefix, DependencyMap &Dependencies) { Module *CurrentModule = RootModule; DependentsVector &FileDependents = Dependencies[HeaderFilePath]; std::string FilePath; // Strip prefix. if (HeaderFilePath.startswith(HeaderPrefix)) FilePath = HeaderFilePath.substr(HeaderPrefix.size() + 1); else FilePath = HeaderFilePath; int Count = FileDependents.size(); // Headers that go into modules must not depend on other files being // included first. If there are any dependents, warn user and omit. if (Count != 0) { llvm::errs() << "warning: " << FilePath << " depends on other headers being included first," " meaning the module.map won't compile." " This header will be omitted from the module map.\n"; return true; } // Make canonical. std::replace(FilePath.begin(), FilePath.end(), '\\', '/'); // Insert module into tree, using subdirectories as submodules. for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(FilePath), E = llvm::sys::path::end(FilePath); I != E; ++I) { if ((*I)[0] == '.') continue; std::string Stem = llvm::sys::path::stem(*I); Stem = ensureNoCollisionWithReservedName(Stem); Module *SubModule = CurrentModule->findSubModule(Stem); if (SubModule == 0) { SubModule = new Module(Stem); CurrentModule->SubModules.push_back(SubModule); } CurrentModule = SubModule; } // Add header file name to headers. CurrentModule->HeaderFileNames.push_back(FilePath); return true; } // Create the internal module tree representation. static Module *loadModuleDescriptions( llvm::StringRef RootModuleName, llvm::ArrayRef<std::string> HeaderFileNames, DependencyMap &Dependencies, llvm::StringRef HeaderPrefix) { // Create root module. Module *RootModule = new Module(RootModuleName); llvm::SmallString<256> CurrentDirectory; llvm::sys::fs::current_path(CurrentDirectory); // If no header prefix, use current directory. if (HeaderPrefix.size() == 0) HeaderPrefix = CurrentDirectory; // Walk the header file names and output the module map. for (llvm::ArrayRef<std::string>::iterator I = HeaderFileNames.begin(), E = HeaderFileNames.end(); I != E; ++I) { // Add as a module. if (!addModuleDescription(RootModule, *I, HeaderPrefix, Dependencies)) return NULL; } return RootModule; } // Kick off the writing of the module map. static bool writeModuleMap(llvm::StringRef ModuleMapPath, llvm::StringRef HeaderPrefix, Module *RootModule) { llvm::SmallString<256> HeaderDirectory(ModuleMapPath); llvm::sys::path::remove_filename(HeaderDirectory); llvm::SmallString<256> FilePath; // Get the module map file path to be used. if ((HeaderDirectory.size() == 0) && (HeaderPrefix.size() != 0)) { FilePath = HeaderPrefix; // Prepend header file name prefix if it's not absolute. llvm::sys::path::append(FilePath, ModuleMapPath); llvm::sys::path::native(FilePath); } else { FilePath = ModuleMapPath; llvm::sys::path::native(FilePath); } // Set up module map output file. std::string Error; llvm::tool_output_file Out(FilePath.c_str(), Error); if (!Error.empty()) { llvm::errs() << Argv0 << ": error opening " << FilePath << ":" << Error << "\n"; return false; } // Get output stream from tool output buffer/manager. llvm::raw_fd_ostream &OS = Out.os(); // Output file comment. OS << "// " << ModuleMapPath << "\n"; OS << "// Generated by: " << CommandLine << "\n\n"; // Write module hierarchy from internal representation. if (!RootModule->output(OS, 0)) return false; // Tell tool_output_file that we want to keep the file. Out.keep(); return true; } // Global functions: // Module map generation entry point. bool createModuleMap(llvm::StringRef ModuleMapPath, llvm::ArrayRef<std::string> HeaderFileNames, DependencyMap &Dependencies, llvm::StringRef HeaderPrefix, llvm::StringRef RootModuleName) { // Load internal representation of modules. llvm::OwningPtr<Module> RootModule(loadModuleDescriptions( RootModuleName, HeaderFileNames, Dependencies, HeaderPrefix)); if (!RootModule.get()) return false; // Write module map file. return writeModuleMap(ModuleMapPath, HeaderPrefix, RootModule.get()); } <commit_msg>clang-tools-extra/modularize: Compare Paths to Prefix as natively-canonicalized form.<commit_after>//===--- ModuleAssistant.cpp - Module map generation manager -*- C++ -*---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===---------------------------------------------------------------------===// // // This file defines the module generation entry point function, // createModuleMap, a Module class for representing a module, // and various implementation functions for doing the underlying // work, described below. // // The "Module" class represents a module, with members for storing the module // name, associated header file names, and sub-modules, and an "output" // function that recursively writes the module definitions. // // The "createModuleMap" function implements the top-level logic of the // assistant mode. It calls a loadModuleDescriptions function to walk // the header list passed to it and creates a tree of Module objects // representing the module hierarchy, represented by a "Module" object, // the "RootModule". This root module may or may not represent an actual // module in the module map, depending on the "--root-module" option passed // to modularize. It then calls a writeModuleMap function to set up the // module map file output and walk the module tree, outputting the module // map file using a stream obtained and managed by an // llvm::tool_output_file object. // //===---------------------------------------------------------------------===// #include "Modularize.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/ToolOutputFile.h" #include <vector> // Local definitions: namespace { // Internal class definitions: // Represents a module. class Module { public: Module(llvm::StringRef Name); Module(); ~Module(); bool output(llvm::raw_fd_ostream &OS, int Indent); Module *findSubModule(llvm::StringRef SubName); public: std::string Name; std::vector<std::string> HeaderFileNames; std::vector<Module *> SubModules; }; } // end anonymous namespace. // Module functions: // Constructors. Module::Module(llvm::StringRef Name) : Name(Name) {} Module::Module() {} // Destructor. Module::~Module() { // Free submodules. while (SubModules.size()) { Module *last = SubModules.back(); SubModules.pop_back(); delete last; } } // Write a module hierarchy to the given output stream. bool Module::output(llvm::raw_fd_ostream &OS, int Indent) { // If this is not the nameless root module, start a module definition. if (Name.size() != 0) { OS.indent(Indent); OS << "module " << Name << " {\n"; Indent += 2; } // Output submodules. for (std::vector<Module *>::iterator I = SubModules.begin(), E = SubModules.end(); I != E; ++I) { if (!(*I)->output(OS, Indent)) return false; } // Output header files. for (std::vector<std::string>::iterator I = HeaderFileNames.begin(), E = HeaderFileNames.end(); I != E; ++I) { OS.indent(Indent); OS << "header \"" << *I << "\"\n"; } // If this module has header files, output export directive. if (HeaderFileNames.size() != 0) { OS.indent(Indent); OS << "export *\n"; } // If this is not the nameless root module, close the module definition. if (Name.size() != 0) { Indent -= 2; OS.indent(Indent); OS << "}\n"; } return true; } // Lookup a sub-module. Module *Module::findSubModule(llvm::StringRef SubName) { for (std::vector<Module *>::iterator I = SubModules.begin(), E = SubModules.end(); I != E; ++I) { if ((*I)->Name == SubName) return *I; } return 0; } // Implementation functions: // Reserved keywords in module.map syntax. // Keep in sync with keywords in module map parser in Lex/ModuleMap.cpp, // such as in ModuleMapParser::consumeToken(). static const char *ReservedNames[] = { "config_macros", "export", "module", "conflict", "framework", "requires", "exclude", "header", "private", "explicit", "link", "umbrella", "extern", "use", 0 // Flag end. }; // Convert module name to a non keyword. // Prepends a '_' to the name if and only if the name is a keyword. static std::string ensureNoCollisionWithReservedName(llvm::StringRef MightBeReservedName) { std::string SafeName = MightBeReservedName; for (int Index = 0; ReservedNames[Index] != 0; ++Index) { if (MightBeReservedName == ReservedNames[Index]) { SafeName.insert(0, "_"); break; } } return SafeName; } // Add one module, given a header file path. static bool addModuleDescription(Module *RootModule, llvm::StringRef HeaderFilePath, llvm::StringRef HeaderPrefix, DependencyMap &Dependencies) { Module *CurrentModule = RootModule; DependentsVector &FileDependents = Dependencies[HeaderFilePath]; std::string FilePath; // Strip prefix. // HeaderFilePath should be compared to natively-canonicalized Prefix. llvm::SmallString<256> NativePath, NativePrefix; llvm::sys::path::native(HeaderFilePath, NativePath); llvm::sys::path::native(HeaderPrefix, NativePrefix); if (NativePath.startswith(NativePrefix)) FilePath = NativePath.substr(NativePrefix.size() + 1); else FilePath = HeaderFilePath; int Count = FileDependents.size(); // Headers that go into modules must not depend on other files being // included first. If there are any dependents, warn user and omit. if (Count != 0) { llvm::errs() << "warning: " << FilePath << " depends on other headers being included first," " meaning the module.map won't compile." " This header will be omitted from the module map.\n"; return true; } // Make canonical. std::replace(FilePath.begin(), FilePath.end(), '\\', '/'); // Insert module into tree, using subdirectories as submodules. for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(FilePath), E = llvm::sys::path::end(FilePath); I != E; ++I) { if ((*I)[0] == '.') continue; std::string Stem = llvm::sys::path::stem(*I); Stem = ensureNoCollisionWithReservedName(Stem); Module *SubModule = CurrentModule->findSubModule(Stem); if (SubModule == 0) { SubModule = new Module(Stem); CurrentModule->SubModules.push_back(SubModule); } CurrentModule = SubModule; } // Add header file name to headers. CurrentModule->HeaderFileNames.push_back(FilePath); return true; } // Create the internal module tree representation. static Module *loadModuleDescriptions( llvm::StringRef RootModuleName, llvm::ArrayRef<std::string> HeaderFileNames, DependencyMap &Dependencies, llvm::StringRef HeaderPrefix) { // Create root module. Module *RootModule = new Module(RootModuleName); llvm::SmallString<256> CurrentDirectory; llvm::sys::fs::current_path(CurrentDirectory); // If no header prefix, use current directory. if (HeaderPrefix.size() == 0) HeaderPrefix = CurrentDirectory; // Walk the header file names and output the module map. for (llvm::ArrayRef<std::string>::iterator I = HeaderFileNames.begin(), E = HeaderFileNames.end(); I != E; ++I) { // Add as a module. if (!addModuleDescription(RootModule, *I, HeaderPrefix, Dependencies)) return NULL; } return RootModule; } // Kick off the writing of the module map. static bool writeModuleMap(llvm::StringRef ModuleMapPath, llvm::StringRef HeaderPrefix, Module *RootModule) { llvm::SmallString<256> HeaderDirectory(ModuleMapPath); llvm::sys::path::remove_filename(HeaderDirectory); llvm::SmallString<256> FilePath; // Get the module map file path to be used. if ((HeaderDirectory.size() == 0) && (HeaderPrefix.size() != 0)) { FilePath = HeaderPrefix; // Prepend header file name prefix if it's not absolute. llvm::sys::path::append(FilePath, ModuleMapPath); llvm::sys::path::native(FilePath); } else { FilePath = ModuleMapPath; llvm::sys::path::native(FilePath); } // Set up module map output file. std::string Error; llvm::tool_output_file Out(FilePath.c_str(), Error); if (!Error.empty()) { llvm::errs() << Argv0 << ": error opening " << FilePath << ":" << Error << "\n"; return false; } // Get output stream from tool output buffer/manager. llvm::raw_fd_ostream &OS = Out.os(); // Output file comment. OS << "// " << ModuleMapPath << "\n"; OS << "// Generated by: " << CommandLine << "\n\n"; // Write module hierarchy from internal representation. if (!RootModule->output(OS, 0)) return false; // Tell tool_output_file that we want to keep the file. Out.keep(); return true; } // Global functions: // Module map generation entry point. bool createModuleMap(llvm::StringRef ModuleMapPath, llvm::ArrayRef<std::string> HeaderFileNames, DependencyMap &Dependencies, llvm::StringRef HeaderPrefix, llvm::StringRef RootModuleName) { // Load internal representation of modules. llvm::OwningPtr<Module> RootModule(loadModuleDescriptions( RootModuleName, HeaderFileNames, Dependencies, HeaderPrefix)); if (!RootModule.get()) return false; // Write module map file. return writeModuleMap(ModuleMapPath, HeaderPrefix, RootModule.get()); } <|endoftext|>
<commit_before>/* MicroFlo - Flow-Based Programming for microcontrollers * Copyright (c) 2013 Jon Nordby <jononor@gmail.com> * MicroFlo may be freely distributed under the MIT license * * Note: Arduino is under the LGPL license. */ #include "microflo.h" #include <Arduino.h> static const int MAX_EXTERNAL_INTERRUPTS = 3; struct InterruptHandler { IOInterruptFunction func; void *user; }; static InterruptHandler externalInterruptHandlers[MAX_EXTERNAL_INTERRUPTS]; static uint8_t InterruptModeToArduino(IO::Interrupt::Mode mode) { switch (mode) { case IO::Interrupt::OnChange: return CHANGE; case IO::Interrupt::OnLow: return LOW; case IO::Interrupt::OnHigh: return HIGH; case IO::Interrupt::OnRisingEdge: return RISING; case IO::Interrupt::OnFallingEdge: return FALLING; } } class ArduinoIO : public IO { public: // ... Arduino interrupt API is stupid and does not provide the callback with context static void externalInterrupt0() { IOInterruptFunction f = externalInterruptHandlers[0].func; if (f) { f(externalInterruptHandlers[0].user); } } static void externalInterrupt1() { IOInterruptFunction f = externalInterruptHandlers[1].func; if (f) { f(externalInterruptHandlers[1].user); } } static void externalInterrupt2() { IOInterruptFunction f = externalInterruptHandlers[2].func; if (f) { f(externalInterruptHandlers[2].user); } } public: ArduinoIO() {} ~ArduinoIO() {} // Serial // TODO: support multiple serial devices virtual void SerialBegin(uint8_t serialDevice, int baudrate) { Serial.begin(baudrate); } virtual long SerialDataAvailable(uint8_t serialDevice) { return Serial.available(); } virtual unsigned char SerialRead(uint8_t serialDevice) { return Serial.read(); } virtual void SerialWrite(uint8_t serialDevice, unsigned char b) { Serial.write(b); } // Pin config virtual void PinSetMode(MicroFlo::PinId pin, IO::PinMode mode) { if (mode == IO::InputPin) { pinMode(pin, INPUT); } else if (mode == IO::OutputPin) { pinMode(pin, OUTPUT); } } virtual void PinSetPullup(MicroFlo::PinId pin, IO::PullupMode mode) { if (mode == IO::PullNone) { digitalWrite(pin, LOW); } else if (mode == IO::PullUp) { digitalWrite(pin, HIGH); } else { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } } // Digital virtual void DigitalWrite(MicroFlo::PinId pin, bool val) { digitalWrite(pin, val); } virtual bool DigitalRead(MicroFlo::PinId pin) { return digitalRead(pin); } // Analog virtual long AnalogRead(MicroFlo::PinId pin) { return analogRead(pin); } virtual void PwmWrite(MicroFlo::PinId pin, long dutyPercent) { analogWrite(pin, (dutyPercent*255)/100); // normalize to [0..255] } // Timer virtual long TimerCurrentMs() { return millis(); } virtual void AttachExternalInterrupt(uint8_t interrupt, IO::Interrupt::Mode mode, IOInterruptFunction func, void *user) { externalInterruptHandlers[interrupt].func = func; externalInterruptHandlers[interrupt].user = user; uint8_t m = InterruptModeToArduino(mode); if (interrupt == 0) { attachInterrupt(interrupt, externalInterrupt0, m); } else if (interrupt == 1) { attachInterrupt(interrupt, externalInterrupt1, m); } else if (interrupt == 2) { attachInterrupt(interrupt, externalInterrupt2, m); } } }; <commit_msg>Arduino: Fix compile warning<commit_after>/* MicroFlo - Flow-Based Programming for microcontrollers * Copyright (c) 2013 Jon Nordby <jononor@gmail.com> * MicroFlo may be freely distributed under the MIT license * * Note: Arduino is under the LGPL license. */ #include "microflo.h" #include <Arduino.h> static const int MAX_EXTERNAL_INTERRUPTS = 3; struct InterruptHandler { IOInterruptFunction func; void *user; }; static InterruptHandler externalInterruptHandlers[MAX_EXTERNAL_INTERRUPTS]; static uint8_t InterruptModeToArduino(IO::Interrupt::Mode mode) { switch (mode) { case IO::Interrupt::OnChange: return CHANGE; case IO::Interrupt::OnLow: return LOW; case IO::Interrupt::OnHigh: return HIGH; case IO::Interrupt::OnRisingEdge: return RISING; case IO::Interrupt::OnFallingEdge: return FALLING; } // ERROR return CHANGE; } class ArduinoIO : public IO { public: // ... Arduino interrupt API is stupid and does not provide the callback with context static void externalInterrupt0() { IOInterruptFunction f = externalInterruptHandlers[0].func; if (f) { f(externalInterruptHandlers[0].user); } } static void externalInterrupt1() { IOInterruptFunction f = externalInterruptHandlers[1].func; if (f) { f(externalInterruptHandlers[1].user); } } static void externalInterrupt2() { IOInterruptFunction f = externalInterruptHandlers[2].func; if (f) { f(externalInterruptHandlers[2].user); } } public: ArduinoIO() {} ~ArduinoIO() {} // Serial // TODO: support multiple serial devices virtual void SerialBegin(uint8_t serialDevice, int baudrate) { Serial.begin(baudrate); } virtual long SerialDataAvailable(uint8_t serialDevice) { return Serial.available(); } virtual unsigned char SerialRead(uint8_t serialDevice) { return Serial.read(); } virtual void SerialWrite(uint8_t serialDevice, unsigned char b) { Serial.write(b); } // Pin config virtual void PinSetMode(MicroFlo::PinId pin, IO::PinMode mode) { if (mode == IO::InputPin) { pinMode(pin, INPUT); } else if (mode == IO::OutputPin) { pinMode(pin, OUTPUT); } } virtual void PinSetPullup(MicroFlo::PinId pin, IO::PullupMode mode) { if (mode == IO::PullNone) { digitalWrite(pin, LOW); } else if (mode == IO::PullUp) { digitalWrite(pin, HIGH); } else { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } } // Digital virtual void DigitalWrite(MicroFlo::PinId pin, bool val) { digitalWrite(pin, val); } virtual bool DigitalRead(MicroFlo::PinId pin) { return digitalRead(pin); } // Analog virtual long AnalogRead(MicroFlo::PinId pin) { return analogRead(pin); } virtual void PwmWrite(MicroFlo::PinId pin, long dutyPercent) { analogWrite(pin, (dutyPercent*255)/100); // normalize to [0..255] } // Timer virtual long TimerCurrentMs() { return millis(); } virtual void AttachExternalInterrupt(uint8_t interrupt, IO::Interrupt::Mode mode, IOInterruptFunction func, void *user) { externalInterruptHandlers[interrupt].func = func; externalInterruptHandlers[interrupt].user = user; uint8_t m = InterruptModeToArduino(mode); if (interrupt == 0) { attachInterrupt(interrupt, externalInterrupt0, m); } else if (interrupt == 1) { attachInterrupt(interrupt, externalInterrupt1, m); } else if (interrupt == 2) { attachInterrupt(interrupt, externalInterrupt2, m); } } }; <|endoftext|>
<commit_before>#include "Session.h" #include <string> #include <SmurffCpp/Version.h> #include <SmurffCpp/Utils/omp_util.h> #include <SmurffCpp/Utils/Distribution.h> #include <SmurffCpp/Utils/MatrixUtils.h> #include <SmurffCpp/Utils/counters.h> #include <SmurffCpp/Utils/Error.h> #include <SmurffCpp/DataMatrices/DataCreator.h> #include <SmurffCpp/Priors/PriorFactory.h> #include <SmurffCpp/result.h> using namespace smurff; void Session::setFromRootPath(std::string rootPath) { // assign config m_rootFile = std::make_shared<RootFile>(rootPath); m_rootFile->restoreConfig(m_config); m_config.validate(); //base functionality setFromBase(); } void Session::setFromConfig(const Config& cfg) { // assign config cfg.validate(); m_config = cfg; m_rootFile = std::make_shared<RootFile>(m_config.getSavePrefix(), m_config.getSaveExtension()); m_rootFile->saveConfig(m_config); //base functionality setFromBase(); //flush record about options.ini m_rootFile->flushLast(); } void Session::setFromBase() { std::shared_ptr<Session> this_session = shared_from_this(); // initialize pred if (m_config.getClassify()) m_pred->setThreshold(m_config.getThreshold()); if (m_config.getTest()) m_pred->set(m_config.getTest()); // initialize data data_ptr = m_config.getTrain()->create(std::make_shared<DataCreator>(this_session)); // initialize priors std::shared_ptr<IPriorFactory> priorFactory = this->create_prior_factory(); for (std::size_t i = 0; i < m_config.getPriorTypes().size(); i++) this->addPrior(priorFactory->create_prior(this_session, i)); } void Session::init() { //init omp threads_init(); //initialize random generator initRng(); //initialize train matrix (centring and noise model) data()->init(); //initialize model (samples) m_model->init(m_config.getNumLatent(), data()->dim(), m_config.getModelInitType()); //initialize priors for(auto &p : m_priors) p->init(); //write header to status file if (m_config.getCsvStatus().size()) { auto f = fopen(m_config.getCsvStatus().c_str(), "w"); fprintf(f, "phase;iter;phase_len;globmean_rmse;colmean_rmse;rmse_avg;rmse_1samp;train_rmse;auc_avg;auc_1samp;U0;U1;elapsed\n"); fclose(f); } //write info to console if (m_config.getVerbose()) info(std::cout, ""); //restore session (model, priors) bool resume = restore(m_iter); //print session status to console if (m_config.getVerbose()) { printStatus(0, resume, m_iter); printf(" ====== Sampling (burning phase) ====== \n"); } //restore will either start from initial iteration (-1) that should be printed with printStatus //or it will start with last iteration that was previously saved //in any case - we have to move to next iteration m_iter++; //go to next iteration is_init = true; } void Session::run() { init(); while (m_iter < m_config.getBurnin() + m_config.getNSamples()) step(); } void Session::step() { THROWERROR_ASSERT(is_init); if (m_config.getVerbose() && m_iter == m_config.getBurnin()) { printf(" ====== Burn-in complete, averaging samples ====== \n"); } auto starti = tick(); BaseSession::step(); auto endi = tick(); //WARNING: update is an expensive operation because of sort (when calculating AUC) m_pred->update(m_model, m_iter < m_config.getBurnin()); printStatus(endi - starti, false, m_iter); save(m_iter); m_iter++; } std::ostream& Session::info(std::ostream &os, std::string indent) { os << indent << name << " {\n"; BaseSession::info(os, indent); os << indent << " Version: " << smurff::SMURFF_VERSION << "\n" ; os << indent << " Iterations: " << m_config.getBurnin() << " burnin + " << m_config.getNSamples() << " samples\n"; if (m_config.getSaveFreq() != 0) { if (m_config.getSaveFreq() > 0) { os << indent << " Save model: every " << m_config.getSaveFreq() << " iteration\n"; } else { os << indent << " Save model after last iteration\n"; } os << indent << " Save prefix: " << m_config.getSavePrefix() << "\n"; os << indent << " Save extension: " << m_config.getSaveExtension() << "\n"; } else { os << indent << " Save model: never\n"; } os << indent << "}\n"; return os; } void Session::save(int iteration) const { //do not save if 'never save' mode is selected if (!m_config.getSaveFreq()) return; int isample = iteration - m_config.getBurnin() + 1; //save if burnin if (isample <= 0) { int iburnin = iteration + 1; //remove previous iteration m_rootFile->removeBurninStepFile(iburnin - 1); //save this iteration std::shared_ptr<StepFile> stepFile = m_rootFile->createBurninStepFile(iburnin); saveInternal(stepFile); } else { //save_freq > 0: check modulo if (m_config.getSaveFreq() > 0 && ((isample + 1) % m_config.getSaveFreq()) != 0) //do not save if not a save iteration return; //save_freq < 0: save last iter if (m_config.getSaveFreq() < 0 && isample < m_config.getNSamples()) //do not save if (final model) mode is selected and not a final iteration return; //save this iteration std::shared_ptr<StepFile> stepFile = m_rootFile->createSampleStepFile(isample); saveInternal(stepFile); } } void Session::saveInternal(std::shared_ptr<StepFile> stepFile) const { if (m_config.getVerbose()) printf("-- Saving model, predictions,... into '%s'.\n", stepFile->getStepFileName().c_str()); BaseSession::save(stepFile); //flush last item in a root file m_rootFile->flushLast(); } bool Session::restore(int& iteration) { std::shared_ptr<StepFile> stepFile = m_rootFile->openLastStepFile(); if (!stepFile) { //if there is nothing to restore - start from initial iteration iteration = -1; return false; } else { if (m_config.getVerbose()) printf("-- Restoring model, predictions,... from '%s'.\n", stepFile->getStepFileName().c_str()); BaseSession::restore(stepFile); //restore last iteration index if (stepFile->getBurnin()) { iteration = stepFile->getIsample() - 1; //restore original state } else { iteration = stepFile->getIsample() + m_config.getBurnin() - 1; //restore original state } return true; } } void Session::printStatus(double elapsedi, bool resume, int iteration) { if(!m_config.getVerbose()) return; double snorm0 = m_model->U(0).norm(); double snorm1 = m_model->U(1).norm(); auto nnz_per_sec = (data()->nnz()) / elapsedi; auto samples_per_sec = (m_model->nsamples()) / elapsedi; std::string resumeString = resume ? "Continue from " : std::string(); std::string phase; int i, from; if (iteration < 0) { phase = "Initial"; i = iteration + 1; from = 0; } else if (iteration < m_config.getBurnin()) { phase = "Burnin"; i = iteration + 1; from = m_config.getBurnin(); } else { phase = "Sample"; i = iteration - m_config.getBurnin() + 1; from = m_config.getNSamples(); } printf("%s%s %3d/%3d: RMSE: %.4f (1samp: %.4f)", resumeString.c_str(), phase.c_str(), i, from, m_pred->rmse_avg, m_pred->rmse_1sample); if (m_config.getClassify()) printf(" AUC:%.4f (1samp: %.4f)", m_pred->auc_avg, m_pred->auc_1sample); printf(" U:[%1.2e, %1.2e] [took: %0.1fs]\n", snorm0, snorm1, elapsedi); // avoid computing train_rmse twice double train_rmse = NAN; if (m_config.getVerbose() > 1) { train_rmse = data()->train_rmse(m_model); printf(" RMSE train: %.4f\n", train_rmse); printf(" Priors:\n"); for(const auto &p : m_priors) p->status(std::cout, " "); printf(" Model:\n"); m_model->status(std::cout, " "); printf(" Noise:\n"); data()->status(std::cout, " "); } if (m_config.getVerbose() > 2) { printf(" Compute Performance: %.0f samples/sec, %.0f nnz/sec\n", samples_per_sec, nnz_per_sec); } if (m_config.getCsvStatus().size()) { // train_rmse is printed as NAN, unless verbose > 1 auto f = fopen(m_config.getCsvStatus().c_str(), "a"); fprintf(f, "%s;%d;%d;%.4f;%.4f;%.4f;%.4f;:%.4f;%1.2e;%1.2e;%0.1f\n", phase.c_str(), i, from, m_pred->rmse_avg, m_pred->rmse_1sample, train_rmse, m_pred->auc_1sample, m_pred->auc_avg, snorm0, snorm1, elapsedi); fclose(f); } } void Session::initRng() { //init random generator if (m_config.getRandomSeedSet()) init_bmrng(m_config.getRandomSeed()); else init_bmrng(); } std::shared_ptr<IPriorFactory> Session::create_prior_factory() const { return std::make_shared<PriorFactory>(); }<commit_msg>fix bug where results were saved each N iteration incorrectly (wrong iteration was saved)<commit_after>#include "Session.h" #include <string> #include <SmurffCpp/Version.h> #include <SmurffCpp/Utils/omp_util.h> #include <SmurffCpp/Utils/Distribution.h> #include <SmurffCpp/Utils/MatrixUtils.h> #include <SmurffCpp/Utils/counters.h> #include <SmurffCpp/Utils/Error.h> #include <SmurffCpp/DataMatrices/DataCreator.h> #include <SmurffCpp/Priors/PriorFactory.h> #include <SmurffCpp/result.h> using namespace smurff; void Session::setFromRootPath(std::string rootPath) { // assign config m_rootFile = std::make_shared<RootFile>(rootPath); m_rootFile->restoreConfig(m_config); m_config.validate(); //base functionality setFromBase(); } void Session::setFromConfig(const Config& cfg) { // assign config cfg.validate(); m_config = cfg; m_rootFile = std::make_shared<RootFile>(m_config.getSavePrefix(), m_config.getSaveExtension()); m_rootFile->saveConfig(m_config); //base functionality setFromBase(); //flush record about options.ini m_rootFile->flushLast(); } void Session::setFromBase() { std::shared_ptr<Session> this_session = shared_from_this(); // initialize pred if (m_config.getClassify()) m_pred->setThreshold(m_config.getThreshold()); if (m_config.getTest()) m_pred->set(m_config.getTest()); // initialize data data_ptr = m_config.getTrain()->create(std::make_shared<DataCreator>(this_session)); // initialize priors std::shared_ptr<IPriorFactory> priorFactory = this->create_prior_factory(); for (std::size_t i = 0; i < m_config.getPriorTypes().size(); i++) this->addPrior(priorFactory->create_prior(this_session, i)); } void Session::init() { //init omp threads_init(); //initialize random generator initRng(); //initialize train matrix (centring and noise model) data()->init(); //initialize model (samples) m_model->init(m_config.getNumLatent(), data()->dim(), m_config.getModelInitType()); //initialize priors for(auto &p : m_priors) p->init(); //write header to status file if (m_config.getCsvStatus().size()) { auto f = fopen(m_config.getCsvStatus().c_str(), "w"); fprintf(f, "phase;iter;phase_len;globmean_rmse;colmean_rmse;rmse_avg;rmse_1samp;train_rmse;auc_avg;auc_1samp;U0;U1;elapsed\n"); fclose(f); } //write info to console if (m_config.getVerbose()) info(std::cout, ""); //restore session (model, priors) bool resume = restore(m_iter); //print session status to console if (m_config.getVerbose()) { printStatus(0, resume, m_iter); printf(" ====== Sampling (burning phase) ====== \n"); } //restore will either start from initial iteration (-1) that should be printed with printStatus //or it will start with last iteration that was previously saved //in any case - we have to move to next iteration m_iter++; //go to next iteration is_init = true; } void Session::run() { init(); while (m_iter < m_config.getBurnin() + m_config.getNSamples()) step(); } void Session::step() { THROWERROR_ASSERT(is_init); if (m_config.getVerbose() && m_iter == m_config.getBurnin()) { printf(" ====== Burn-in complete, averaging samples ====== \n"); } auto starti = tick(); BaseSession::step(); auto endi = tick(); //WARNING: update is an expensive operation because of sort (when calculating AUC) m_pred->update(m_model, m_iter < m_config.getBurnin()); printStatus(endi - starti, false, m_iter); save(m_iter); m_iter++; } std::ostream& Session::info(std::ostream &os, std::string indent) { os << indent << name << " {\n"; BaseSession::info(os, indent); os << indent << " Version: " << smurff::SMURFF_VERSION << "\n" ; os << indent << " Iterations: " << m_config.getBurnin() << " burnin + " << m_config.getNSamples() << " samples\n"; if (m_config.getSaveFreq() != 0) { if (m_config.getSaveFreq() > 0) { os << indent << " Save model: every " << m_config.getSaveFreq() << " iteration\n"; } else { os << indent << " Save model after last iteration\n"; } os << indent << " Save prefix: " << m_config.getSavePrefix() << "\n"; os << indent << " Save extension: " << m_config.getSaveExtension() << "\n"; } else { os << indent << " Save model: never\n"; } os << indent << "}\n"; return os; } void Session::save(int iteration) const { //do not save if 'never save' mode is selected if (!m_config.getSaveFreq()) return; int isample = iteration - m_config.getBurnin() + 1; //save if burnin if (isample <= 0) { int iburnin = iteration + 1; //remove previous iteration m_rootFile->removeBurninStepFile(iburnin - 1); //save this iteration std::shared_ptr<StepFile> stepFile = m_rootFile->createBurninStepFile(iburnin); saveInternal(stepFile); } else { //save_freq > 0: check modulo if (m_config.getSaveFreq() > 0 && (isample % m_config.getSaveFreq()) != 0) //do not save if not a save iteration return; //save_freq < 0: save last iter if (m_config.getSaveFreq() < 0 && isample < m_config.getNSamples()) //do not save if (final model) mode is selected and not a final iteration return; //save this iteration std::shared_ptr<StepFile> stepFile = m_rootFile->createSampleStepFile(isample); saveInternal(stepFile); } } void Session::saveInternal(std::shared_ptr<StepFile> stepFile) const { if (m_config.getVerbose()) printf("-- Saving model, predictions,... into '%s'.\n", stepFile->getStepFileName().c_str()); BaseSession::save(stepFile); //flush last item in a root file m_rootFile->flushLast(); } bool Session::restore(int& iteration) { std::shared_ptr<StepFile> stepFile = m_rootFile->openLastStepFile(); if (!stepFile) { //if there is nothing to restore - start from initial iteration iteration = -1; return false; } else { if (m_config.getVerbose()) printf("-- Restoring model, predictions,... from '%s'.\n", stepFile->getStepFileName().c_str()); BaseSession::restore(stepFile); //restore last iteration index if (stepFile->getBurnin()) { iteration = stepFile->getIsample() - 1; //restore original state } else { iteration = stepFile->getIsample() + m_config.getBurnin() - 1; //restore original state } return true; } } void Session::printStatus(double elapsedi, bool resume, int iteration) { if(!m_config.getVerbose()) return; double snorm0 = m_model->U(0).norm(); double snorm1 = m_model->U(1).norm(); auto nnz_per_sec = (data()->nnz()) / elapsedi; auto samples_per_sec = (m_model->nsamples()) / elapsedi; std::string resumeString = resume ? "Continue from " : std::string(); std::string phase; int i, from; if (iteration < 0) { phase = "Initial"; i = iteration + 1; from = 0; } else if (iteration < m_config.getBurnin()) { phase = "Burnin"; i = iteration + 1; from = m_config.getBurnin(); } else { phase = "Sample"; i = iteration - m_config.getBurnin() + 1; from = m_config.getNSamples(); } printf("%s%s %3d/%3d: RMSE: %.4f (1samp: %.4f)", resumeString.c_str(), phase.c_str(), i, from, m_pred->rmse_avg, m_pred->rmse_1sample); if (m_config.getClassify()) printf(" AUC:%.4f (1samp: %.4f)", m_pred->auc_avg, m_pred->auc_1sample); printf(" U:[%1.2e, %1.2e] [took: %0.1fs]\n", snorm0, snorm1, elapsedi); // avoid computing train_rmse twice double train_rmse = NAN; if (m_config.getVerbose() > 1) { train_rmse = data()->train_rmse(m_model); printf(" RMSE train: %.4f\n", train_rmse); printf(" Priors:\n"); for(const auto &p : m_priors) p->status(std::cout, " "); printf(" Model:\n"); m_model->status(std::cout, " "); printf(" Noise:\n"); data()->status(std::cout, " "); } if (m_config.getVerbose() > 2) { printf(" Compute Performance: %.0f samples/sec, %.0f nnz/sec\n", samples_per_sec, nnz_per_sec); } if (m_config.getCsvStatus().size()) { // train_rmse is printed as NAN, unless verbose > 1 auto f = fopen(m_config.getCsvStatus().c_str(), "a"); fprintf(f, "%s;%d;%d;%.4f;%.4f;%.4f;%.4f;:%.4f;%1.2e;%1.2e;%0.1f\n", phase.c_str(), i, from, m_pred->rmse_avg, m_pred->rmse_1sample, train_rmse, m_pred->auc_1sample, m_pred->auc_avg, snorm0, snorm1, elapsedi); fclose(f); } } void Session::initRng() { //init random generator if (m_config.getRandomSeedSet()) init_bmrng(m_config.getRandomSeed()); else init_bmrng(); } std::shared_ptr<IPriorFactory> Session::create_prior_factory() const { return std::make_shared<PriorFactory>(); }<|endoftext|>
<commit_before>// 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 "base/at_exit.h" #include "base/message_loop.h" #include "base/scoped_nsautorelease_pool.h" #include "gpu/command_buffer/common/command_buffer_mock.h" #include "gpu/command_buffer/service/context_group.h" #include "gpu/command_buffer/service/gpu_processor.h" #include "gpu/command_buffer/service/gles2_cmd_decoder.h" #include "gpu/command_buffer/service/gles2_cmd_decoder_mock.h" #include "gpu/command_buffer/service/mocks.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/gmock/include/gmock/gmock.h" using testing::_; using testing::DoAll; using testing::Invoke; using testing::NiceMock; using testing::Return; using testing::SetArgumentPointee; using testing::StrictMock; namespace gpu { const size_t kRingBufferSize = 1024; const size_t kRingBufferEntries = kRingBufferSize / sizeof(CommandBufferEntry); class GPUProcessorTest : public testing::Test { protected: virtual void SetUp() { shared_memory_.reset(new ::base::SharedMemory); shared_memory_->Create(std::wstring(), false, false, kRingBufferSize); shared_memory_->Map(kRingBufferSize); buffer_ = static_cast<int32*>(shared_memory_->memory()); shared_memory_buffer_.ptr = buffer_; shared_memory_buffer_.size = kRingBufferSize; memset(buffer_, 0, kRingBufferSize); command_buffer_.reset(new MockCommandBuffer); ON_CALL(*command_buffer_.get(), GetRingBuffer()) .WillByDefault(Return(shared_memory_buffer_)); CommandBuffer::State default_state; default_state.size = kRingBufferEntries; ON_CALL(*command_buffer_.get(), GetState()) .WillByDefault(Return(default_state)); async_api_.reset(new StrictMock<AsyncAPIMock>); decoder_ = new gles2::MockGLES2Decoder(&group_); parser_ = new CommandParser(buffer_, kRingBufferEntries, 0, kRingBufferEntries, 0, async_api_.get()); processor_.reset(new GPUProcessor(command_buffer_.get(), decoder_, parser_, 2)); } virtual void TearDown() { // Ensure that any unexpected tasks posted by the GPU processor are executed // in order to fail the test. MessageLoop::current()->RunAllPending(); } error::Error GetError() { return command_buffer_->GetState().error; } base::ScopedNSAutoreleasePool autorelease_pool_; base::AtExitManager at_exit_manager; MessageLoop message_loop; scoped_ptr<MockCommandBuffer> command_buffer_; scoped_ptr<base::SharedMemory> shared_memory_; Buffer shared_memory_buffer_; int32* buffer_; gles2::ContextGroup group_; gles2::MockGLES2Decoder* decoder_; CommandParser* parser_; scoped_ptr<AsyncAPIMock> async_api_; scoped_ptr<GPUProcessor> processor_; }; // TODO(apatrick): This test is broken on linux. TEST_F(GPUProcessorTest, DISABLED_ProcessorDoesNothingIfRingBufferIsEmpty) { CommandBuffer::State state; state.put_offset = 0; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*command_buffer_, SetGetOffset(0)); EXPECT_CALL(*command_buffer_, SetParseError(_)) .Times(0); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, ProcessesOneCommand) { CommandHeader* header = reinterpret_cast<CommandHeader*>(&buffer_[0]); header[0].command = 7; header[0].size = 2; buffer_[1] = 123; CommandBuffer::State state; state.put_offset = 2; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*command_buffer_, SetGetOffset(2)); EXPECT_CALL(*async_api_, DoCommand(7, 1, &buffer_[0])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*command_buffer_, SetParseError(_)) .Times(0); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, ProcessesTwoCommands) { CommandHeader* header = reinterpret_cast<CommandHeader*>(&buffer_[0]); header[0].command = 7; header[0].size = 2; buffer_[1] = 123; header[2].command = 8; header[2].size = 1; CommandBuffer::State state; state.put_offset = 3; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*command_buffer_, SetGetOffset(3)); EXPECT_CALL(*async_api_, DoCommand(7, 1, &buffer_[0])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*async_api_, DoCommand(8, 0, &buffer_[2])) .WillOnce(Return(error::kNoError)); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, ProcessorSetsTheGLContext) { EXPECT_CALL(*decoder_, MakeCurrent()) .WillOnce(Return(true)); CommandBuffer::State state; state.put_offset = 0; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*command_buffer_, SetGetOffset(0)); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, PostsTaskToFinishRemainingCommands) { CommandHeader* header = reinterpret_cast<CommandHeader*>(&buffer_[0]); header[0].command = 7; header[0].size = 2; buffer_[1] = 123; header[2].command = 8; header[2].size = 1; header[3].command = 9; header[3].size = 1; CommandBuffer::State state; state.put_offset = 4; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*async_api_, DoCommand(7, 1, &buffer_[0])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*async_api_, DoCommand(8, 0, &buffer_[2])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*command_buffer_, SetGetOffset(3)); processor_->ProcessCommands(); // ProcessCommands is called a second time when the pending task is run. state.put_offset = 4; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*async_api_, DoCommand(9, 0, &buffer_[3])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*command_buffer_, SetGetOffset(4)); MessageLoop::current()->RunAllPending(); } TEST_F(GPUProcessorTest, SetsErrorCodeOnCommandBuffer) { CommandHeader* header = reinterpret_cast<CommandHeader*>(&buffer_[0]); header[0].command = 7; header[0].size = 1; CommandBuffer::State state; state.put_offset = 1; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*async_api_, DoCommand(7, 0, &buffer_[0])) .WillOnce(Return( error::kUnknownCommand)); EXPECT_CALL(*command_buffer_, SetParseError(error::kUnknownCommand)); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, ProcessCommandsDoesNothingAfterError) { CommandBuffer::State state; state.error = error::kGenericError; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); processor_->ProcessCommands(); } TEST_F(GPUProcessorTest, CanGetAddressOfSharedMemory) { EXPECT_CALL(*command_buffer_.get(), GetTransferBuffer(7)) .WillOnce(Return(shared_memory_buffer_)); EXPECT_EQ(&buffer_[0], processor_->GetSharedMemoryBuffer(7).ptr); } ACTION_P2(SetPointee, address, value) { *address = value; } TEST_F(GPUProcessorTest, CanGetSizeOfSharedMemory) { EXPECT_CALL(*command_buffer_.get(), GetTransferBuffer(7)) .WillOnce(Return(shared_memory_buffer_)); EXPECT_EQ(kRingBufferSize, processor_->GetSharedMemoryBuffer(7).size); } TEST_F(GPUProcessorTest, SetTokenForwardsToCommandBuffer) { EXPECT_CALL(*command_buffer_, SetToken(7)); processor_->set_token(7); } } // namespace gpu <commit_msg>Disable more GPU tests.<commit_after>// 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 "base/at_exit.h" #include "base/message_loop.h" #include "base/scoped_nsautorelease_pool.h" #include "gpu/command_buffer/common/command_buffer_mock.h" #include "gpu/command_buffer/service/context_group.h" #include "gpu/command_buffer/service/gpu_processor.h" #include "gpu/command_buffer/service/gles2_cmd_decoder.h" #include "gpu/command_buffer/service/gles2_cmd_decoder_mock.h" #include "gpu/command_buffer/service/mocks.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/gmock/include/gmock/gmock.h" using testing::_; using testing::DoAll; using testing::Invoke; using testing::NiceMock; using testing::Return; using testing::SetArgumentPointee; using testing::StrictMock; namespace gpu { const size_t kRingBufferSize = 1024; const size_t kRingBufferEntries = kRingBufferSize / sizeof(CommandBufferEntry); class GPUProcessorTest : public testing::Test { protected: virtual void SetUp() { shared_memory_.reset(new ::base::SharedMemory); shared_memory_->Create(std::wstring(), false, false, kRingBufferSize); shared_memory_->Map(kRingBufferSize); buffer_ = static_cast<int32*>(shared_memory_->memory()); shared_memory_buffer_.ptr = buffer_; shared_memory_buffer_.size = kRingBufferSize; memset(buffer_, 0, kRingBufferSize); command_buffer_.reset(new MockCommandBuffer); ON_CALL(*command_buffer_.get(), GetRingBuffer()) .WillByDefault(Return(shared_memory_buffer_)); CommandBuffer::State default_state; default_state.size = kRingBufferEntries; ON_CALL(*command_buffer_.get(), GetState()) .WillByDefault(Return(default_state)); async_api_.reset(new StrictMock<AsyncAPIMock>); decoder_ = new gles2::MockGLES2Decoder(&group_); parser_ = new CommandParser(buffer_, kRingBufferEntries, 0, kRingBufferEntries, 0, async_api_.get()); processor_.reset(new GPUProcessor(command_buffer_.get(), decoder_, parser_, 2)); } virtual void TearDown() { // Ensure that any unexpected tasks posted by the GPU processor are executed // in order to fail the test. MessageLoop::current()->RunAllPending(); } error::Error GetError() { return command_buffer_->GetState().error; } base::ScopedNSAutoreleasePool autorelease_pool_; base::AtExitManager at_exit_manager; MessageLoop message_loop; scoped_ptr<MockCommandBuffer> command_buffer_; scoped_ptr<base::SharedMemory> shared_memory_; Buffer shared_memory_buffer_; int32* buffer_; gles2::ContextGroup group_; gles2::MockGLES2Decoder* decoder_; CommandParser* parser_; scoped_ptr<AsyncAPIMock> async_api_; scoped_ptr<GPUProcessor> processor_; }; // TODO(apatrick): This test is broken on linux. TEST_F(GPUProcessorTest, DISABLED_ProcessorDoesNothingIfRingBufferIsEmpty) { CommandBuffer::State state; state.put_offset = 0; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*command_buffer_, SetGetOffset(0)); EXPECT_CALL(*command_buffer_, SetParseError(_)) .Times(0); processor_->ProcessCommands(); } // TODO(apatrick): This test is broken on linux. TEST_F(GPUProcessorTest, DISABLED_ProcessesOneCommand) { CommandHeader* header = reinterpret_cast<CommandHeader*>(&buffer_[0]); header[0].command = 7; header[0].size = 2; buffer_[1] = 123; CommandBuffer::State state; state.put_offset = 2; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*command_buffer_, SetGetOffset(2)); EXPECT_CALL(*async_api_, DoCommand(7, 1, &buffer_[0])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*command_buffer_, SetParseError(_)) .Times(0); processor_->ProcessCommands(); } // TODO(apatrick): This test is broken on linux. TEST_F(GPUProcessorTest, DISABLED_ProcessesTwoCommands) { CommandHeader* header = reinterpret_cast<CommandHeader*>(&buffer_[0]); header[0].command = 7; header[0].size = 2; buffer_[1] = 123; header[2].command = 8; header[2].size = 1; CommandBuffer::State state; state.put_offset = 3; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*command_buffer_, SetGetOffset(3)); EXPECT_CALL(*async_api_, DoCommand(7, 1, &buffer_[0])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*async_api_, DoCommand(8, 0, &buffer_[2])) .WillOnce(Return(error::kNoError)); processor_->ProcessCommands(); } // TODO(apatrick): This test is broken on linux. TEST_F(GPUProcessorTest, DISABLED_ProcessorSetsTheGLContext) { EXPECT_CALL(*decoder_, MakeCurrent()) .WillOnce(Return(true)); CommandBuffer::State state; state.put_offset = 0; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*command_buffer_, SetGetOffset(0)); processor_->ProcessCommands(); } // TODO(apatrick): This test is broken on linux. TEST_F(GPUProcessorTest, DISABLED_PostsTaskToFinishRemainingCommands) { CommandHeader* header = reinterpret_cast<CommandHeader*>(&buffer_[0]); header[0].command = 7; header[0].size = 2; buffer_[1] = 123; header[2].command = 8; header[2].size = 1; header[3].command = 9; header[3].size = 1; CommandBuffer::State state; state.put_offset = 4; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*async_api_, DoCommand(7, 1, &buffer_[0])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*async_api_, DoCommand(8, 0, &buffer_[2])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*command_buffer_, SetGetOffset(3)); processor_->ProcessCommands(); // ProcessCommands is called a second time when the pending task is run. state.put_offset = 4; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*async_api_, DoCommand(9, 0, &buffer_[3])) .WillOnce(Return(error::kNoError)); EXPECT_CALL(*command_buffer_, SetGetOffset(4)); MessageLoop::current()->RunAllPending(); } // TODO(apatrick): This test is broken on linux. TEST_F(GPUProcessorTest, DISABLED_SetsErrorCodeOnCommandBuffer) { CommandHeader* header = reinterpret_cast<CommandHeader*>(&buffer_[0]); header[0].command = 7; header[0].size = 1; CommandBuffer::State state; state.put_offset = 1; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); EXPECT_CALL(*async_api_, DoCommand(7, 0, &buffer_[0])) .WillOnce(Return( error::kUnknownCommand)); EXPECT_CALL(*command_buffer_, SetParseError(error::kUnknownCommand)); processor_->ProcessCommands(); } // TODO(apatrick): This test is broken on linux. TEST_F(GPUProcessorTest, DISABLED_ProcessCommandsDoesNothingAfterError) { CommandBuffer::State state; state.error = error::kGenericError; EXPECT_CALL(*command_buffer_, GetState()) .WillOnce(Return(state)); processor_->ProcessCommands(); } // TODO(apatrick): This test is broken on linux. TEST_F(GPUProcessorTest, DISABLED_CanGetAddressOfSharedMemory) { EXPECT_CALL(*command_buffer_.get(), GetTransferBuffer(7)) .WillOnce(Return(shared_memory_buffer_)); EXPECT_EQ(&buffer_[0], processor_->GetSharedMemoryBuffer(7).ptr); } ACTION_P2(SetPointee, address, value) { *address = value; } // TODO(apatrick): This test is broken on linux. TEST_F(GPUProcessorTest, DISABLED_CanGetSizeOfSharedMemory) { EXPECT_CALL(*command_buffer_.get(), GetTransferBuffer(7)) .WillOnce(Return(shared_memory_buffer_)); EXPECT_EQ(kRingBufferSize, processor_->GetSharedMemoryBuffer(7).size); } // TODO(apatrick): This test is broken on linux. TEST_F(GPUProcessorTest, DISABLED_SetTokenForwardsToCommandBuffer) { EXPECT_CALL(*command_buffer_, SetToken(7)); processor_->set_token(7); } } // namespace gpu <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/app/atom_main.h" #include <stdlib.h> #include <string.h> #if defined(OS_WIN) #include <stdio.h> #include <io.h> #include <fcntl.h> #include <windows.h> #include <shellapi.h> #include "atom/app/atom_main_delegate.h" #include "atom/common/crash_reporter/win/crash_service_main.h" #include "base/environment.h" #include "content/public/app/startup_helper_win.h" #include "sandbox/win/src/sandbox_types.h" #include "ui/gfx/win/dpi.h" #elif defined(OS_LINUX) // defined(OS_WIN) #include "atom/app/atom_main_delegate.h" // NOLINT #include "content/public/app/content_main.h" #else // defined(OS_LINUX) #include "atom/app/atom_library_main.h" #endif // defined(OS_MACOSX) // Declaration of node::Start. namespace node { int Start(int argc, char *argv[]); } #if defined(OS_WIN) int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) { int argc = 0; wchar_t** wargv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); scoped_ptr<base::Environment> env(base::Environment::Create()); // Make output work in console if we are not in cygiwn. std::string os; if (env->GetVar("OS", &os) && os != "cygwin") { AttachConsole(ATTACH_PARENT_PROCESS); FILE* dontcare; freopen_s(&dontcare, "CON", "w", stdout); freopen_s(&dontcare, "CON", "w", stderr); freopen_s(&dontcare, "CON", "r", stdin); } std::string node_indicator, crash_service_indicator; if (env->GetVar("ATOM_SHELL_INTERNAL_RUN_AS_NODE", &node_indicator) && node_indicator == "1") { // Convert argv to to UTF8 char** argv = new char*[argc]; for (int i = 0; i < argc; i++) { // Compute the size of the required buffer DWORD size = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, NULL, 0, NULL, NULL); if (size == 0) { // This should never happen. fprintf(stderr, "Could not convert arguments to utf8."); exit(1); } // Do the actual conversion argv[i] = new char[size]; DWORD result = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, argv[i], size, NULL, NULL); if (result == 0) { // This should never happen. fprintf(stderr, "Could not convert arguments to utf8."); exit(1); } } // Now that conversion is done, we can finally start. return node::Start(argc, argv); } else if (env->GetVar("ATOM_SHELL_INTERNAL_CRASH_SERVICE", &crash_service_indicator) && crash_service_indicator == "1") { return crash_service::Main(cmd); } sandbox::SandboxInterfaceInfo sandbox_info = {0}; content::InitializeSandboxInfo(&sandbox_info); atom::AtomMainDelegate delegate; // Now chrome relies on a regkey to enable high dpi support. gfx::EnableHighDPISupport(); content::ContentMainParams params(&delegate); params.instance = instance; params.sandbox_info = &sandbox_info; return content::ContentMain(params); } #elif defined(OS_LINUX) // defined(OS_WIN) int main(int argc, const char* argv[]) { char* node_indicator = getenv("ATOM_SHELL_INTERNAL_RUN_AS_NODE"); if (node_indicator != NULL && strcmp(node_indicator, "1") == 0) return node::Start(argc, const_cast<char**>(argv)); atom::AtomMainDelegate delegate; content::ContentMainParams params(&delegate); params.argc = argc; params.argv = argv; return content::ContentMain(params); } #else // defined(OS_LINUX) int main(int argc, const char* argv[]) { char* node_indicator = getenv("ATOM_SHELL_INTERNAL_RUN_AS_NODE"); if (node_indicator != NULL && strcmp(node_indicator, "1") == 0) { AtomInitializeICU(); return node::Start(argc, const_cast<char**>(argv)); } return AtomMain(argc, argv); } #endif // defined(OS_MACOSX) <commit_msg>linux,win: Initalize ICU for node mode<commit_after>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/app/atom_main.h" #include <stdlib.h> #include <string.h> #if defined(OS_WIN) #include <stdio.h> #include <io.h> #include <fcntl.h> #include <windows.h> #include <shellapi.h> #include "atom/app/atom_main_delegate.h" #include "atom/common/crash_reporter/win/crash_service_main.h" #include "base/environment.h" #include "content/public/app/startup_helper_win.h" #include "sandbox/win/src/sandbox_types.h" #include "ui/gfx/win/dpi.h" #elif defined(OS_LINUX) // defined(OS_WIN) #include "atom/app/atom_main_delegate.h" // NOLINT #include "content/public/app/content_main.h" #else // defined(OS_LINUX) #include "atom/app/atom_library_main.h" #endif // defined(OS_MACOSX) #include "base/i18n/icu_util.h" // Declaration of node::Start. namespace node { int Start(int argc, char *argv[]); } #if defined(OS_WIN) int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) { int argc = 0; wchar_t** wargv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); scoped_ptr<base::Environment> env(base::Environment::Create()); // Make output work in console if we are not in cygiwn. std::string os; if (env->GetVar("OS", &os) && os != "cygwin") { AttachConsole(ATTACH_PARENT_PROCESS); FILE* dontcare; freopen_s(&dontcare, "CON", "w", stdout); freopen_s(&dontcare, "CON", "w", stderr); freopen_s(&dontcare, "CON", "r", stdin); } std::string node_indicator, crash_service_indicator; if (env->GetVar("ATOM_SHELL_INTERNAL_RUN_AS_NODE", &node_indicator) && node_indicator == "1") { // Convert argv to to UTF8 char** argv = new char*[argc]; for (int i = 0; i < argc; i++) { // Compute the size of the required buffer DWORD size = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, NULL, 0, NULL, NULL); if (size == 0) { // This should never happen. fprintf(stderr, "Could not convert arguments to utf8."); exit(1); } // Do the actual conversion argv[i] = new char[size]; DWORD result = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, argv[i], size, NULL, NULL); if (result == 0) { // This should never happen. fprintf(stderr, "Could not convert arguments to utf8."); exit(1); } } // Now that conversion is done, we can finally start. base::i18n::InitializeICU(); return node::Start(argc, argv); } else if (env->GetVar("ATOM_SHELL_INTERNAL_CRASH_SERVICE", &crash_service_indicator) && crash_service_indicator == "1") { return crash_service::Main(cmd); } sandbox::SandboxInterfaceInfo sandbox_info = {0}; content::InitializeSandboxInfo(&sandbox_info); atom::AtomMainDelegate delegate; // Now chrome relies on a regkey to enable high dpi support. gfx::EnableHighDPISupport(); content::ContentMainParams params(&delegate); params.instance = instance; params.sandbox_info = &sandbox_info; return content::ContentMain(params); } #elif defined(OS_LINUX) // defined(OS_WIN) int main(int argc, const char* argv[]) { char* node_indicator = getenv("ATOM_SHELL_INTERNAL_RUN_AS_NODE"); if (node_indicator != NULL && strcmp(node_indicator, "1") == 0) { base::i18n::InitializeICU(); return node::Start(argc, const_cast<char**>(argv)); } atom::AtomMainDelegate delegate; content::ContentMainParams params(&delegate); params.argc = argc; params.argv = argv; return content::ContentMain(params); } #else // defined(OS_LINUX) int main(int argc, const char* argv[]) { char* node_indicator = getenv("ATOM_SHELL_INTERNAL_RUN_AS_NODE"); if (node_indicator != NULL && strcmp(node_indicator, "1") == 0) { AtomInitializeICU(); return node::Start(argc, const_cast<char**>(argv)); } return AtomMain(argc, argv); } #endif // defined(OS_MACOSX) <|endoftext|>
<commit_before>#pragma once #include <Geometry2d/Point.hpp> #include <Geometry2d/CompositeShape.hpp> #include <SystemState.hpp> #include <QColor> #include <QString> namespace Planning { /** * @brief Abstract class representing a motion path */ class Path { public: /** * A path describes the position and velocity a robot should be at for a * particular time interval. This method evalates the path at a given time and * returns the target position and velocity of the robot. * * @param[in] t Time (in seconds) since the robot started the path * @param[out] targetPosOut The position the robot would ideally be at at the given time * @param[out] targetVelOut The target velocity of the robot at the given time * @return true if the path is valid at time @t, false if you've gone past the end */ virtual bool evaluate(float t, Geometry2d::Point &targetPosOut, Geometry2d::Point &targetVelOut) const=0; /** * Returns true if the path hits an obstacle * * @param[in] shape The obstacles on the field * @param[in] startTime The time on the path to start checking from * @return true if it hits an obstacle, otherwise false */ virtual bool hit(const Geometry2d::CompositeShape &shape, float startTime = 0) const=0; /** * Draws the path * * @param[in] state The SystemState to draw the path on * @param[in] color The color the path should be drawn * @param[in] layer The layer to draw the path on */ virtual void draw(SystemState * const state, const QColor &color = Qt::black, const QString &layer = "Motion") const =0; /** * Returns how long it would take for the entire path to be traversed * * @return The time from start to path completion or infinity if it never stops */ virtual float getDuration() const=0; /** * Returns a subPath * * @param[in] startTime The startTime for from which the subPath should be taken. * @param[in] endTime The endTime from which the subPath should be taken. If it is greater than the duration fo the path, it should go to the end of the path. * @return A unique_ptr to the new subPath */ virtual std::unique_ptr<Path> subPath(float startTime = 0, float endTime = std::numeric_limits<float>::infinity()) const=0; /** * Returns the destination point of the path if it has one */ virtual boost::optional<Geometry2d::Point> destination() const=0; /** * Returns a deep copy of the Path */ virtual std::unique_ptr<Path> clone() const=0; }; }<commit_msg>virtual destructor for Path to silence warning<commit_after>#pragma once #include <Geometry2d/Point.hpp> #include <Geometry2d/CompositeShape.hpp> #include <SystemState.hpp> #include <QColor> #include <QString> namespace Planning { /** * @brief Abstract class representing a motion path */ class Path { public: virtual ~Path() {} /** * A path describes the position and velocity a robot should be at for a * particular time interval. This method evalates the path at a given time and * returns the target position and velocity of the robot. * * @param[in] t Time (in seconds) since the robot started the path * @param[out] targetPosOut The position the robot would ideally be at at the given time * @param[out] targetVelOut The target velocity of the robot at the given time * @return true if the path is valid at time @t, false if you've gone past the end */ virtual bool evaluate(float t, Geometry2d::Point &targetPosOut, Geometry2d::Point &targetVelOut) const=0; /** * Returns true if the path hits an obstacle * * @param[in] shape The obstacles on the field * @param[in] startTime The time on the path to start checking from * @return true if it hits an obstacle, otherwise false */ virtual bool hit(const Geometry2d::CompositeShape &shape, float startTime = 0) const=0; /** * Draws the path * * @param[in] state The SystemState to draw the path on * @param[in] color The color the path should be drawn * @param[in] layer The layer to draw the path on */ virtual void draw(SystemState * const state, const QColor &color = Qt::black, const QString &layer = "Motion") const =0; /** * Returns how long it would take for the entire path to be traversed * * @return The time from start to path completion or infinity if it never stops */ virtual float getDuration() const=0; /** * Returns a subPath * * @param[in] startTime The startTime for from which the subPath should be taken. * @param[in] endTime The endTime from which the subPath should be taken. If it is greater than the duration fo the path, it should go to the end of the path. * @return A unique_ptr to the new subPath */ virtual std::unique_ptr<Path> subPath(float startTime = 0, float endTime = std::numeric_limits<float>::infinity()) const=0; /** * Returns the destination point of the path if it has one */ virtual boost::optional<Geometry2d::Point> destination() const=0; /** * Returns a deep copy of the Path */ virtual std::unique_ptr<Path> clone() const=0; }; } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ /** \file mitkdump.cpp \brief Commandline application to see what DICOMFileReaderSelector would produce from a set of files. Usage: \verbatim mitkdump [-v] file1 [... fileN] -v output more details on commandline fileN DICOM file \endverbatim The application will ask a DICOMFileReaderSelector to analyze the files given as file1 .. fileN. Once the reader with the least number of files is selected, this result is printed to commandline. If the "-v" flag is used (as a first parameter), the output will contain details about filenames, which can make the output considerably harder to read. Output is also written to a log file of name "%gt;datetime-stamp%lt;_dir_&gt;directory-name&lt;.mitkdump */ #include "mitkDICOMFileReaderSelector.h" using mitk::DICOMTag; std::string buildDateString() { std::time_t rawtime; std::tm* timeinfo; char buffer [80]; std::time(&rawtime); timeinfo = std::localtime(&rawtime); std::strftime(buffer,80,"%Y%m%d-%H%M%S",timeinfo); return std::string(buffer); } void gen_random(char *s, const int len) { static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for (int i = 0; i < len; ++i) { s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } s[len] = 0; } std::string gen_random(const int len) { char retval[len]; gen_random(retval, len); return std::string(retval); } std::string removeUnsafeChars(const std::string& str) { std::string retval; for(std::string::const_iterator it = str.begin(); it != str.end(); ++it) { const char& c = *it; if ( (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == '.') || (c == '-') || (c == '_') ) { retval += c; } } return retval; } std::string extractDirString(const std::string& dirString) { std::string wholeprefix = dirString.substr(0, dirString.find_last_of("/\\")); std::string lastDirectoryPart = wholeprefix.substr(wholeprefix.find_last_of("/\\")+1); std::string cleanLastDirectoryPart = removeUnsafeChars(lastDirectoryPart); if (!cleanLastDirectoryPart.empty()) { return cleanLastDirectoryPart; } else { std::stringstream emptydirname; emptydirname << "noname_" << gen_random(6); return emptydirname.str(); } } int main(int argc, char* argv[]) { bool fileDetails(false); bool loadimage(false); int firstFileIndex = 1; // see if we got the '-v' flag to output file details if (argc > 1 && std::string(argv[firstFileIndex]) == "-v") { fileDetails = true; ++firstFileIndex; } // see if we got the '-l' flag if (argc > 1 && std::string(argv[firstFileIndex]) == "-l") { loadimage = true; ++firstFileIndex; } // analyze files from argv mitk::StringList inputFiles; for (int a = firstFileIndex; a < argc; ++a) { inputFiles.push_back( std::string(argv[a]) ); } mitk::DICOMFileReaderSelector::Pointer configSelector = mitk::DICOMFileReaderSelector::New(); configSelector->LoadBuiltIn3DConfigs(); // a set of compiled in ressources with standard configurations that work well configSelector->SetInputFiles( inputFiles ); mitk::DICOMFileReader::Pointer reader = configSelector->GetFirstReaderWithMinimumNumberOfOutputImages(); if (reader.IsNull()) { MITK_ERROR << "Could not configure any DICOM reader.. Exiting..."; return EXIT_FAILURE; } // output best reader result MITK_INFO << "---- Best reader configuration '" << reader->GetConfigurationLabel() << "'"; if (fileDetails) { reader->PrintOutputs(std::cout, fileDetails); } // construct the name of a log file std::string datestring = buildDateString();; std::string dirString = extractDirString(argv[firstFileIndex]); std::string logfilename = datestring + "_dir_" + dirString + ".mitkdump"; MITK_INFO << "Logfile " << logfilename; // write output to file for later analysis std::ofstream fs; fs.open(logfilename.c_str()); reader->PrintOutputs( fs, true); // always verbose in log file fs.close(); if (loadimage) { MITK_INFO << "Loading..."; reader->LoadImages(); mitk::Image::Pointer image = reader->GetOutput(0).GetMitkImage(); MITK_INFO << "---- Output image:"; mitk::Geometry3D::Pointer geo3D = image->GetGeometry(); if (geo3D.IsNotNull()) { mitk::SlicedGeometry3D::Pointer sg = dynamic_cast<mitk::SlicedGeometry3D*>(geo3D.GetPointer()); if (sg.IsNotNull()) { unsigned int nos = sg->GetSlices(); mitk::Geometry2D::Pointer first = sg->GetGeometry2D(0); mitk::Geometry2D::Pointer last = sg->GetGeometry2D(nos-1); mitk::Point3D firstOrigin = first->GetOrigin(); mitk::Point3D lastOrigin = last->GetOrigin(); MITK_INFO << "Geometry says: First slice at " << firstOrigin << ", last slice at " << lastOrigin; mitk::StringLookupTableProperty::Pointer sliceLocations = dynamic_cast<mitk::StringLookupTableProperty*>( image->GetProperty("dicom.image.0020.1041").GetPointer() ); if (sliceLocations.IsNotNull()) { std::string firstSliceLocation = sliceLocations->GetValue().GetTableValue(0); std::string lastSliceLocation = sliceLocations->GetValue().GetTableValue(nos-1); MITK_INFO << "Image properties says: first slice location at " << firstSliceLocation << ", last slice location at " << lastSliceLocation; } mitk::StringLookupTableProperty::Pointer instanceNumbers = dynamic_cast<mitk::StringLookupTableProperty*>( image->GetProperty("dicom.image.0020.0013").GetPointer() ); if (instanceNumbers.IsNotNull()) { std::string firstInstanceNumber = instanceNumbers->GetValue().GetTableValue(0); std::string lastInstanceNumber = instanceNumbers->GetValue().GetTableValue(nos-1); MITK_INFO << "Image properties says: first instance number at " << firstInstanceNumber << ", last instance number at " << lastInstanceNumber; } } } MITK_INFO << "---- End of output"; } // if we got so far, everything is fine return EXIT_SUCCESS; } <commit_msg>Compile on Windows and fix error<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ /** \file mitkdump.cpp \brief Commandline application to see what DICOMFileReaderSelector would produce from a set of files. Usage: \verbatim mitkdump [-v] file1 [... fileN] -v output more details on commandline fileN DICOM file \endverbatim The application will ask a DICOMFileReaderSelector to analyze the files given as file1 .. fileN. Once the reader with the least number of files is selected, this result is printed to commandline. If the "-v" flag is used (as a first parameter), the output will contain details about filenames, which can make the output considerably harder to read. Output is also written to a log file of name "%gt;datetime-stamp%lt;_dir_&gt;directory-name&lt;.mitkdump */ #include "mitkDICOMFileReaderSelector.h" using mitk::DICOMTag; std::string buildDateString() { std::time_t rawtime; std::tm* timeinfo; char buffer [80]; std::time(&rawtime); timeinfo = std::localtime(&rawtime); std::strftime(buffer,80,"%Y%m%d-%H%M%S",timeinfo); return std::string(buffer); } void gen_random(char *s, const int len) { static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for (int i = 0; i < len; ++i) { s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } s[len] = 0; } std::string gen_random(const int len) { if (len < 1) { return std::string(""); } else { char retval[len]; gen_random(retval, len); return std::string(retval); } } std::string removeUnsafeChars(const std::string& str) { std::string retval; for(std::string::const_iterator it = str.begin(); it != str.end(); ++it) { const char& c = *it; if ( (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == '.') || (c == '-') || (c == '_') ) { retval += c; } } return retval; } std::string extractDirString(const std::string& dirString) { std::string wholeprefix = dirString.substr(0, dirString.find_last_of("/\\")); std::string lastDirectoryPart = wholeprefix.substr(wholeprefix.find_last_of("/\\")+1); std::string cleanLastDirectoryPart = removeUnsafeChars(lastDirectoryPart); if (!cleanLastDirectoryPart.empty()) { return cleanLastDirectoryPart; } else { std::stringstream emptydirname; emptydirname << "noname_" << gen_random(6); return emptydirname.str(); } } int main(int argc, char* argv[]) { bool fileDetails(false); bool loadimage(false); int firstFileIndex = 1; // see if we got the '-v' flag to output file details if (argc > 1 && std::string(argv[firstFileIndex]) == "-v") { fileDetails = true; ++firstFileIndex; } // see if we got the '-l' flag if (argc > 1 && std::string(argv[firstFileIndex]) == "-l") { loadimage = true; ++firstFileIndex; } // analyze files from argv mitk::StringList inputFiles; for (int a = firstFileIndex; a < argc; ++a) { inputFiles.push_back( std::string(argv[a]) ); } mitk::DICOMFileReaderSelector::Pointer configSelector = mitk::DICOMFileReaderSelector::New(); configSelector->LoadBuiltIn3DConfigs(); // a set of compiled in ressources with standard configurations that work well configSelector->SetInputFiles( inputFiles ); mitk::DICOMFileReader::Pointer reader = configSelector->GetFirstReaderWithMinimumNumberOfOutputImages(); if (reader.IsNull()) { MITK_ERROR << "Could not configure any DICOM reader.. Exiting..."; return EXIT_FAILURE; } // output best reader result MITK_INFO << "---- Best reader configuration '" << reader->GetConfigurationLabel() << "'"; if (fileDetails) { reader->PrintOutputs(std::cout, fileDetails); } // construct the name of a log file std::string datestring = buildDateString();; std::string dirString = extractDirString(argv[firstFileIndex]); std::string logfilename = datestring + "_dir_" + dirString + ".mitkdump"; MITK_INFO << "Logfile " << logfilename; // write output to file for later analysis std::ofstream fs; fs.open(logfilename.c_str()); reader->PrintOutputs( fs, true); // always verbose in log file fs.close(); if (loadimage) { MITK_INFO << "Loading..."; reader->LoadImages(); mitk::Image::Pointer image = reader->GetOutput(0).GetMitkImage(); MITK_INFO << "---- Output image:"; mitk::Geometry3D::Pointer geo3D = image->GetGeometry(); if (geo3D.IsNotNull()) { mitk::SlicedGeometry3D::Pointer sg = dynamic_cast<mitk::SlicedGeometry3D*>(geo3D.GetPointer()); if (sg.IsNotNull()) { unsigned int nos = sg->GetSlices(); mitk::Geometry2D::Pointer first = sg->GetGeometry2D(0); mitk::Geometry2D::Pointer last = sg->GetGeometry2D(nos-1); mitk::Point3D firstOrigin = first->GetOrigin(); mitk::Point3D lastOrigin = last->GetOrigin(); MITK_INFO << "Geometry says: First slice at " << firstOrigin << ", last slice at " << lastOrigin; mitk::StringLookupTableProperty::Pointer sliceLocations = dynamic_cast<mitk::StringLookupTableProperty*>( image->GetProperty("dicom.image.0020.1041").GetPointer() ); if (sliceLocations.IsNotNull()) { std::string firstSliceLocation = sliceLocations->GetValue().GetTableValue(0); std::string lastSliceLocation = sliceLocations->GetValue().GetTableValue(nos-1); MITK_INFO << "Image properties says: first slice location at " << firstSliceLocation << ", last slice location at " << lastSliceLocation; } mitk::StringLookupTableProperty::Pointer instanceNumbers = dynamic_cast<mitk::StringLookupTableProperty*>( image->GetProperty("dicom.image.0020.0013").GetPointer() ); if (instanceNumbers.IsNotNull()) { std::string firstInstanceNumber = instanceNumbers->GetValue().GetTableValue(0); std::string lastInstanceNumber = instanceNumbers->GetValue().GetTableValue(nos-1); MITK_INFO << "Image properties says: first instance number at " << firstInstanceNumber << ", last instance number at " << lastInstanceNumber; } } } MITK_INFO << "---- End of output"; } // if we got so far, everything is fine return EXIT_SUCCESS; } <|endoftext|>
<commit_before> #include <string> #include <sstream> #include <fstream> #include <iterator> #include <vector> #include <map> #include <utility> #include <functional> #include <algorithm> #include <limits> #include <time.h> #include <omp.h> #include <boost/program_options.hpp> #include "tools.hpp" namespace b_po = boost::program_options; // 3-column float with col1 = x-val, col2 = y-val, col3 = density // addressed by [row*3+col] with n_rows = n_bins^2 std::vector<float> calculate_density_histogram(const std::vector<float>& dens, const std::string& projections, std::pair<std::size_t, std::size_t> dims, std::size_t n_bins) { auto coords_tuple = read_coords<float>(projections, {dims.first, dims.second}); std::vector<float> coords = std::get<0>(coords_tuple); std::size_t n_rows = std::get<1>(coords_tuple); auto X = [&](std::size_t i) { return coords[i*2]; }; auto Y = [&](std::size_t i) { return coords[i*2 + 1]; }; float x_min = X(0); float x_max = X(0); float y_min = Y(0); float y_max = Y(0); for (std::size_t i=1; i < n_rows; ++i) { auto mm = std::minmax({X(i), x_min, x_max}); x_min = mm.first; x_max = mm.second; mm = std::minmax({Y(i), y_min, y_max}); y_min = mm.first; y_max = mm.second; } float dx = (x_max - x_min) / n_bins; float dy = (y_max - y_min) / n_bins; // setup bins std::vector<float> hist(3*n_bins*n_bins); // addressing shortcuts auto HX = [&](std::size_t i, std::size_t j) -> float& {return hist[(i*n_bins+j)*3];}; auto HY = [&](std::size_t i, std::size_t j) -> float& {return hist[(i*n_bins+j)*3+1];}; auto HZ = [&](std::size_t i, std::size_t j) -> float& {return hist[(i*n_bins+j)*3+2];}; for (std::size_t i=0; i < n_bins; ++i) { for (std::size_t j=0; j < n_bins; ++j) { HX(i,j) = x_min + i*dx; HY(i,j) = y_min + j*dy; } } // sort data into bins for (std::size_t i_frame=0; i_frame < n_rows; ++i_frame) { std::size_t i_xbin = n_bins-1; std::size_t i_ybin = n_bins-1; // find index for x-bin for (std::size_t ix=0; ix < n_bins-1; ++ix) { float x_val = coords[i_frame*2]; if (HX(ix,0) < x_val && x_val < HX(ix+1,0)) { i_xbin = ix; break; } } // find index for y-bin for (std::size_t iy=0; iy < n_bins-1; ++iy) { float y_val = coords[i_frame*2+1]; if (HY(i_xbin,iy) < y_val && y_val < HY(i_xbin,iy+1)) { i_ybin = iy; break; } } // add density to histogram HZ(i_xbin, i_ybin) += dens[i_frame]; } return hist; } std::vector<float> calculate_densities(const std::vector<std::size_t>& pops) { const std::size_t n_frames = pops.size(); std::vector<float> dens(n_frames); float max_pop = (float) ( * std::max_element(pops.begin(), pops.end())); for (std::size_t i=0; i < n_frames; ++i) { dens[i] = (float) pops[i] / max_pop; } return dens; } std::vector<std::size_t> calculate_populations(const std::string& neighborhood, const std::string& projections) { std::size_t n_frames = 0; // read projections linewise to determine number of frames { std::string line; std::ifstream ifs(projections); while (ifs.good()) { std::getline(ifs, line); if ( ! line.empty()) { ++n_frames; } } } // set initial population = 1 for every frame // (i.e. the frame itself is in population) std::vector<std::size_t> pops(n_frames, 1); // read neighborhood info and calculate populations { std::ifstream ifs(neighborhood); std::size_t buf; while (ifs.good()) { // from ifs >> buf; ++pops[buf]; // to ifs >> buf; ++pops[buf]; // next line ifs.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } } return pops; } std::vector<std::size_t> density_clustering(std::vector<float> dens, float density_threshold, float density_radius) { using Density = std::pair<std::size_t, float>; std::vector<Density> density_heap; // sort according to density: highest to lowest std::make_heap(density_heap.begin(), density_heap.end(), [](const Density& d1, const Density& d2) -> bool {return d1.second > d2.second;}); for (std::size_t i=0; i < dens.size(); ++i) { density_heap.push_back({i, dens[i]}); std::push_heap(density_heap.begin(), density_heap.end()); } //TODO } int main(int argc, char* argv[]) { b_po::variables_map var_map; b_po::options_description desc (std::string(argv[0]).append( "\n\n" "output: populations of frame environment\n" "\n" "options")); desc.add_options() ("help,h", "show this help") ("input,i", b_po::value<std::string>()->required(), "projected data") ("neighborhood,N", b_po::value<std::string>()->required(), "neighborhood info") ("population,p", b_po::bool_switch()->default_value(false), "print populations instead of densities") ("histogram,H", b_po::bool_switch()->default_value(false), "print histogram data for densities") ("nbins", b_po::value<int>()->default_value(200), "#bins for histogram (default: 200)") ("density-clustering,C", b_po::value<float>(), "print clustering given by density threshold"); try { b_po::positional_options_description p; p.add("input", -1); b_po::store(b_po::command_line_parser(argc, argv).options(desc).positional(p).run(), var_map); b_po::notify(var_map); } catch (b_po::error& e) { if ( ! var_map.count("help")) { std::cout << "\n" << e.what() << "\n\n" << std::endl; } std::cout << desc << std::endl; return 2; } if (var_map.count("help")) { std::cout << desc << std::endl; return 1; } //// std::vector<std::size_t> pops = calculate_populations(var_map["neighborhood"].as<std::string>(), var_map["input"].as<std::string>()); if (var_map["population"].as<bool>()) { for (std::size_t i=0; i < pops.size(); ++i) { std::cout << i << " " << pops[i] << "\n"; } } else if (var_map["histogram"].as<bool>()) { std::vector<float> dens = calculate_densities(pops); int n_bins = var_map["nbins"].as<int>(); std::vector<float> hist = calculate_density_histogram(dens, var_map["input"].as<std::string>(), {0,1}, n_bins); for (std::size_t i=0; i < hist.size() / 3; ++i) { std::cout << hist[i*3] << " " << hist[i*3+1] << " " << hist[i*3+2] << "\n"; } } else if (var_map.count("density-clustering")) { std::vector<std::size_t> clusters = density_clustering(calculate_densities(pops), var_map["density_clustering"].as<float>()); } else { std::vector<float> dens = calculate_densities(pops); for (std::size_t i=0; i < dens.size(); ++i) { std::cout << i << " " << dens[i] << "\n"; } } return 0; } <commit_msg>more on clustering<commit_after> #include <string> #include <sstream> #include <fstream> #include <iterator> #include <vector> #include <map> #include <utility> #include <functional> #include <algorithm> #include <limits> #include <time.h> #include <omp.h> #include <boost/program_options.hpp> #include "tools.hpp" namespace b_po = boost::program_options; // 3-column float with col1 = x-val, col2 = y-val, col3 = density // addressed by [row*3+col] with n_rows = n_bins^2 std::vector<float> calculate_density_histogram(const std::vector<float>& dens, const std::string& projections, std::pair<std::size_t, std::size_t> dims, std::size_t n_bins) { auto coords_tuple = read_coords<float>(projections, {dims.first, dims.second}); std::vector<float> coords = std::get<0>(coords_tuple); std::size_t n_rows = std::get<1>(coords_tuple); auto X = [&](std::size_t i) { return coords[i*2]; }; auto Y = [&](std::size_t i) { return coords[i*2 + 1]; }; float x_min = X(0); float x_max = X(0); float y_min = Y(0); float y_max = Y(0); for (std::size_t i=1; i < n_rows; ++i) { auto mm = std::minmax({X(i), x_min, x_max}); x_min = mm.first; x_max = mm.second; mm = std::minmax({Y(i), y_min, y_max}); y_min = mm.first; y_max = mm.second; } float dx = (x_max - x_min) / n_bins; float dy = (y_max - y_min) / n_bins; // setup bins std::vector<float> hist(3*n_bins*n_bins); // addressing shortcuts auto HX = [&](std::size_t i, std::size_t j) -> float& {return hist[(i*n_bins+j)*3];}; auto HY = [&](std::size_t i, std::size_t j) -> float& {return hist[(i*n_bins+j)*3+1];}; auto HZ = [&](std::size_t i, std::size_t j) -> float& {return hist[(i*n_bins+j)*3+2];}; for (std::size_t i=0; i < n_bins; ++i) { for (std::size_t j=0; j < n_bins; ++j) { HX(i,j) = x_min + i*dx; HY(i,j) = y_min + j*dy; } } // sort data into bins for (std::size_t i_frame=0; i_frame < n_rows; ++i_frame) { std::size_t i_xbin = n_bins-1; std::size_t i_ybin = n_bins-1; // find index for x-bin for (std::size_t ix=0; ix < n_bins-1; ++ix) { float x_val = coords[i_frame*2]; if (HX(ix,0) < x_val && x_val < HX(ix+1,0)) { i_xbin = ix; break; } } // find index for y-bin for (std::size_t iy=0; iy < n_bins-1; ++iy) { float y_val = coords[i_frame*2+1]; if (HY(i_xbin,iy) < y_val && y_val < HY(i_xbin,iy+1)) { i_ybin = iy; break; } } // add density to histogram HZ(i_xbin, i_ybin) += dens[i_frame]; } return hist; } std::vector<float> calculate_densities(const std::vector<std::size_t>& pops) { const std::size_t n_frames = pops.size(); std::vector<float> dens(n_frames); float max_pop = (float) ( * std::max_element(pops.begin(), pops.end())); for (std::size_t i=0; i < n_frames; ++i) { dens[i] = (float) pops[i] / max_pop; } return dens; } std::vector<std::size_t> calculate_populations(const std::string& neighborhood, const std::string& projections) { std::size_t n_frames = 0; // read projections linewise to determine number of frames { std::string line; std::ifstream ifs(projections); while (ifs.good()) { std::getline(ifs, line); if ( ! line.empty()) { ++n_frames; } } } // set initial population = 1 for every frame // (i.e. the frame itself is in population) std::vector<std::size_t> pops(n_frames, 1); // read neighborhood info and calculate populations { std::ifstream ifs(neighborhood); std::size_t buf; while (ifs.good()) { // from ifs >> buf; ++pops[buf]; // to ifs >> buf; ++pops[buf]; // next line ifs.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } } return pops; } std::vector<std::size_t> density_clustering(std::vector<float> dens, float density_threshold, float density_radius, std::string coords_file) { using Density = std::pair<std::size_t, float>; std::vector<Density> density_sorted; for (std::size_t i=0; i < dens.size(); ++i) { density_sorted.push_back({i, dens[i]}); } // sort for density: highest to lowest std::sort(density_sorted.begin(), density_sorted.end(), [] (const Density& d1, const Density& d2) -> bool {return d1.second > d2.second;}); auto coords_tuple = read_coords(coords_file); std::vector<float>& coords = std::get<0>(coords_tuple); std::size_t n_rows = std::get<1>(coords_tuple); std::size_t n_cols = std::get<2>(coords_tuple); // cluster structure? std::vector<std::size_t> clusters; std::size_t last_frame_below_threshold; // for all frames: // if frame.density < threshold: // put into queue // for all frames in queue: // find mindist to frames in clusters // if mindist < radius: // assign to cluster // else: // make new cluster } int main(int argc, char* argv[]) { b_po::variables_map var_map; b_po::options_description desc (std::string(argv[0]).append( "\n\n" "output: populations of frame environment\n" "\n" "options")); desc.add_options() ("help,h", "show this help") ("input,i", b_po::value<std::string>()->required(), "projected data") ("neighborhood,N", b_po::value<std::string>()->required(), "neighborhood info") ("population,p", b_po::bool_switch()->default_value(false), "print populations instead of densities") ("histogram,H", b_po::bool_switch()->default_value(false), "print histogram data for densities") ("nbins", b_po::value<int>()->default_value(200), "#bins for histogram (default: 200)") ("density-clustering,C", b_po::value<float>(), "print clustering given by density threshold"); try { b_po::positional_options_description p; p.add("input", -1); b_po::store(b_po::command_line_parser(argc, argv).options(desc).positional(p).run(), var_map); b_po::notify(var_map); } catch (b_po::error& e) { if ( ! var_map.count("help")) { std::cout << "\n" << e.what() << "\n\n" << std::endl; } std::cout << desc << std::endl; return 2; } if (var_map.count("help")) { std::cout << desc << std::endl; return 1; } //// std::vector<std::size_t> pops = calculate_populations(var_map["neighborhood"].as<std::string>(), var_map["input"].as<std::string>()); if (var_map["population"].as<bool>()) { for (std::size_t i=0; i < pops.size(); ++i) { std::cout << i << " " << pops[i] << "\n"; } } else if (var_map["histogram"].as<bool>()) { std::vector<float> dens = calculate_densities(pops); int n_bins = var_map["nbins"].as<int>(); std::vector<float> hist = calculate_density_histogram(dens, var_map["input"].as<std::string>(), {0,1}, n_bins); for (std::size_t i=0; i < hist.size() / 3; ++i) { std::cout << hist[i*3] << " " << hist[i*3+1] << " " << hist[i*3+2] << "\n"; } } else if (var_map.count("density-clustering")) { std::vector<std::size_t> clusters = density_clustering(calculate_densities(pops), var_map["density_clustering"].as<float>(), var_map["radius"].as<float>(), var_map["input"].as<std::string>()); } else { std::vector<float> dens = calculate_densities(pops); for (std::size_t i=0; i < dens.size(); ++i) { std::cout << i << " " << dens[i] << "\n"; } } return 0; } <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the Avogadro project. Copyright 2012-2014 Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 <QtGui/QOffscreenSurface> #include <QtGui/QOpenGLContext> #include <QtGui/QSurfaceFormat> #include <QtWidgets/QApplication> #include <QtWidgets/QMessageBox> #include "mainwindow.h" #ifdef Q_OS_MAC void removeMacSpecificMenuItems(); #endif #ifdef Avogadro_ENABLE_RPC #include "rpclistener.h" #endif int main(int argc, char* argv[]) { #ifdef Q_OS_MAC // call some Objective-C++ removeMacSpecificMenuItems(); // Native Mac applications do not have icons in the menus QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif QCoreApplication::setOrganizationName("OpenChemistry"); QCoreApplication::setOrganizationDomain("openchemistry.org"); QCoreApplication::setApplicationName("Avogadro"); #ifdef Q_OS_WIN // We need to ensure desktop OpenGL is loaded for our rendering. QApplication::setAttribute(Qt::AA_UseDesktopOpenGL); #endif QApplication app(argc, argv); // Check for valid OpenGL support. auto offscreen = new QOffscreenSurface; offscreen->create(); auto context = new QOpenGLContext; context->create(); context->makeCurrent(offscreen); bool contextIsValid = context->isValid(); delete context; delete offscreen; if (!contextIsValid) { QMessageBox::information(0, "Avogadro", "This system does not support OpenGL!"); return 1; } // Use high-resolution (e.g., 2x) icons if available app.setAttribute(Qt::AA_UseHighDpiPixmaps); // Set up the default format for our GL contexts. QSurfaceFormat defaultFormat = QSurfaceFormat::defaultFormat(); defaultFormat.setSamples(4); // defaultFormat.setAlphaBufferSize(8); QSurfaceFormat::setDefaultFormat(defaultFormat); QStringList fileNames; bool disableSettings = false; #ifdef QTTESTING QString testFile; bool testExit = true; #endif QStringList args = QCoreApplication::arguments(); for (QStringList::const_iterator it = args.constBegin() + 1; it != args.constEnd(); ++it) { if (*it == "--test-file" && it + 1 != args.constEnd()) { #ifdef QTTESTING testFile = *(++it); #else qWarning("Avogadro called with --test-file but testing is disabled."); return EXIT_FAILURE; #endif } else if (*it == "--test-no-exit") { #ifdef QTTESTING testExit = false; #else qWarning("Avogadro called with --test-no-exit but testing is disabled."); return EXIT_FAILURE; #endif } else if (*it == "--disable-settings") { disableSettings = true; } else if (it->startsWith("-")) { qWarning("Unknown command line option '%s'", qPrintable(*it)); return EXIT_FAILURE; } else { // Assume it is a file name. fileNames << *it; } } Avogadro::MainWindow* window = new Avogadro::MainWindow(fileNames, disableSettings); #ifdef QTTESTING window->playTest(testFile, testExit); #endif window->show(); #ifdef Avogadro_ENABLE_RPC // create rpc listener Avogadro::RpcListener listener; listener.start(); #endif return app.exec(); } <commit_msg>Add support for finding translations (qt_* qtbase_* and avogadrolibs*)<commit_after>/****************************************************************************** This source file is part of the Avogadro project. Copyright 2012-2014 Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 <QtGui/QOffscreenSurface> #include <QtGui/QOpenGLContext> #include <QtGui/QSurfaceFormat> #include <QtWidgets/QApplication> #include <QtWidgets/QMessageBox> #include <QtCore/QLibraryInfo> #include <QtCore/QTranslator> #include <QtCore/QProcess> #include <QtCore/QDebug> #include "mainwindow.h" #ifdef Q_OS_MAC void removeMacSpecificMenuItems(); #endif #ifdef Avogadro_ENABLE_RPC #include "rpclistener.h" #endif int main(int argc, char* argv[]) { #ifdef Q_OS_MAC // call some Objective-C++ removeMacSpecificMenuItems(); // Native Mac applications do not have icons in the menus QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif QCoreApplication::setOrganizationName("OpenChemistry"); QCoreApplication::setOrganizationDomain("openchemistry.org"); QCoreApplication::setApplicationName("Avogadro"); #ifdef Q_OS_WIN // We need to ensure desktop OpenGL is loaded for our rendering. QApplication::setAttribute(Qt::AA_UseDesktopOpenGL); #endif QApplication app(argc, argv); // Before we do much else, load translations // This ensures help messages and debugging info will be translated QStringList translationPaths; // check environment variable and local paths foreach (const QString &variable, QProcess::systemEnvironment()) { QStringList split1 = variable.split('='); if (split1[0] == "AVOGADRO_TRANSLATIONS") { foreach (const QString &path, split1[1].split(':')) translationPaths << path; } } translationPaths << QCoreApplication::applicationDirPath() + "/../share/avogadro/i18n/"; // Load Qt translations first qDebug() << "Locale: " << QLocale::system().name(); bool tryLoadingQtTranslations = false; QTranslator qtTranslator(0); if (qtTranslator.load(QLocale::system(), "qt", "_", QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { qDebug() << " translation success"; app.installTranslator(&qtTranslator); } else // check other paths tryLoadingQtTranslations = true; QTranslator qtBaseTranslator(0); qDebug() << QLibraryInfo::location(QLibraryInfo::TranslationsPath); if (qtTranslator.load(QLocale::system(), "qtbase", "_", QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { qDebug() << " translation success"; app.installTranslator(&qtTranslator); } // TODO: need to separate avogadrolibs from app QTranslator avoTranslator(0); foreach (const QString &translationPath, translationPaths) { // We can't find the normal Qt translations (maybe we're in a "bundle"?) if (tryLoadingQtTranslations) { if (qtTranslator.load(QLocale::system(), "qt", "_", translationPath)) { app.installTranslator(&qtTranslator); tryLoadingQtTranslations = false; // already loaded } if (qtBaseTranslator.load(QLocale::system(), "qtbase", "_", translationPath)) { app.installTranslator(&qtBaseTranslator); } } if (avoTranslator.load(QLocale::system(), "avogadrolibs", "_", translationPath)) { app.installTranslator(&avoTranslator); qDebug() << "Translation successfully loaded."; } } // Check for valid OpenGL support. auto offscreen = new QOffscreenSurface; offscreen->create(); auto context = new QOpenGLContext; context->create(); context->makeCurrent(offscreen); bool contextIsValid = context->isValid(); delete context; delete offscreen; if (!contextIsValid) { QMessageBox::information(0, QCoreApplication::translate("main.cpp", "Avogadro"), QCoreApplication::translate("main.cpp", "This system does not support OpenGL.")); return 1; } // Use high-resolution (e.g., 2x) icons if available app.setAttribute(Qt::AA_UseHighDpiPixmaps); // Set up the default format for our GL contexts. QSurfaceFormat defaultFormat = QSurfaceFormat::defaultFormat(); defaultFormat.setSamples(4); // defaultFormat.setAlphaBufferSize(8); QSurfaceFormat::setDefaultFormat(defaultFormat); QStringList fileNames; bool disableSettings = false; #ifdef QTTESTING QString testFile; bool testExit = true; #endif QStringList args = QCoreApplication::arguments(); for (QStringList::const_iterator it = args.constBegin() + 1; it != args.constEnd(); ++it) { if (*it == "--test-file" && it + 1 != args.constEnd()) { #ifdef QTTESTING testFile = *(++it); #else qWarning("Avogadro called with --test-file but testing is disabled."); return EXIT_FAILURE; #endif } else if (*it == "--test-no-exit") { #ifdef QTTESTING testExit = false; #else qWarning("Avogadro called with --test-no-exit but testing is disabled."); return EXIT_FAILURE; #endif } else if (*it == "--disable-settings") { disableSettings = true; } else if (it->startsWith("-")) { qWarning("Unknown command line option '%s'", qPrintable(*it)); return EXIT_FAILURE; } else { // Assume it is a file name. fileNames << *it; } } Avogadro::MainWindow* window = new Avogadro::MainWindow(fileNames, disableSettings); #ifdef QTTESTING window->playTest(testFile, testExit); #endif window->show(); #ifdef Avogadro_ENABLE_RPC // create rpc listener Avogadro::RpcListener listener; listener.start(); #endif return app.exec(); } <|endoftext|>
<commit_before>/* COPYRIGHT (c) 2014 Umut Acar, Arthur Chargueraud, and Michael * Rainey * All rights reserved. * * \file graph.hpp * \brief Graph algorithms * */ #include <atomic> #include <vector> #include <algorithm> #include <fstream> #include <iostream> #include <istream> #include <ostream> #include <sstream> #include "sparray.hpp" #ifndef _MINICOURSE_GRAPH_H_ #define _MINICOURSE_GRAPH_H_ /***********************************************************************/ /*---------------------------------------------------------------------*/ /* Edge-list representation of graphs */ using vtxid_type = value_type; // convention: first component source vertex id, second target using edge_type = std::pair<vtxid_type, vtxid_type>; using edgelist = std::deque<edge_type>; edge_type mk_edge(vtxid_type source, vtxid_type dest) { return std::make_pair(source, dest); } long get_nb_vertices_of_edgelist(const edgelist& edges) { long nb = 0; for (long i = 0; i < edges.size(); i++) nb = std::max(nb, std::max(edges[i].first, edges[i].second)); return nb+1; } std::ostream& operator<<(std::ostream& out, const edge_type& edge) { out << edge.first << " -> " << edge.second << ";\n"; return out; } std::ostream& output_directed_dot(std::ostream& out, const edgelist& edges) { out << "digraph {\n"; for (long i = 0; i < edges.size(); ++i) out << edges[i]; return out << "}"; } std::ostream& operator<<(std::ostream& out, const edgelist& edges) { return output_directed_dot(out, edges); } /*---------------------------------------------------------------------*/ /* Adjacency-list representation of graphs */ using neighbor_list = const value_type*; class adjlist { private: class Deleter { public: void operator()(char* ptr) { free(ptr); } }; std::unique_ptr<char[], Deleter> ptr; long nb_offsets = 0l; // == nb_vertices+1 long nb_edges = 0l; vtxid_type* start_offsets; vtxid_type* start_edgelists; void check(vtxid_type v) const { assert(v >= 0l); assert(v < nb_offsets-1); } long alloc() { long nb_cells_allocated = nb_offsets + nb_edges;; char* p = (char*)my_malloc<vtxid_type>(nb_cells_allocated); assert(nb_cells_allocated==0l || p != nullptr); ptr.reset(p); start_offsets = (vtxid_type*)p; start_edgelists = &start_offsets[nb_offsets]; return nb_cells_allocated; } void from_edgelist(const edgelist& edges) { long nb_vertices = get_nb_vertices_of_edgelist(edges); nb_offsets = nb_vertices + 1; nb_edges = edges.size(); alloc(); sparray degrees = sparray(nb_vertices); for (vtxid_type i = 0; i < nb_vertices; i++) degrees[i] = 0; for (long i = 0; i < edges.size(); i++) { edge_type e = edges[i]; degrees[e.first]++; } start_offsets[0] = 0; for (vtxid_type i = 1; i < nb_offsets; i++) start_offsets[i] = start_offsets[i - 1] + degrees[i - 1]; for (vtxid_type i = 0; i < nb_vertices; i++) degrees[i] = 0; for (long i = 0; i < edges.size(); i++) { edge_type e = edges[i]; vtxid_type cnt = degrees[e.first]; start_edgelists[start_offsets[e.first] + cnt] = e.second; degrees[e.first]++; } } const uint64_t GRAPH_TYPE_ADJLIST = 0xdeadbeef; const uint64_t GRAPH_TYPE_EDGELIST = 0xba5eba11; const int bits_per_byte = 8; const int graph_file_header_sz = 5; public: adjlist(long nb_vertices = 0, long nb_edges = 0) : nb_offsets(nb_vertices+1), nb_edges(nb_edges) { if (nb_vertices > 0) alloc(); } adjlist(const edgelist& edges) { from_edgelist(edges); } adjlist(std::initializer_list<edge_type> edges_init) { edgelist edges; for (auto it = edges_init.begin(); it != edges_init.end(); it++) edges.push_back(*it); from_edgelist(edges); } // To disable copy semantics, we disable: adjlist(const adjlist& other); // 1. copy constructor adjlist& operator=(const adjlist& other); // 2. assign-by-copy operator adjlist& operator=(adjlist&& other) { // todo: make sure that the following does not create a memory leak ptr = std::move(other.ptr); nb_offsets = std::move(other.nb_offsets); nb_edges = std::move(other.nb_edges); start_offsets = std::move(other.start_offsets); start_edgelists = std::move(other.start_edgelists); return *this; } long get_nb_vertices() const { return nb_offsets-1l; } long get_nb_edges() const { return nb_edges; } long get_out_degree_of(vtxid_type v) const { check(v); return start_offsets[v+1] - start_offsets[v]; } neighbor_list get_neighbors_of(vtxid_type v) const { check(v); return &start_edgelists[start_offsets[v]]; } void load_from_file(std::string fname) { std::ifstream in(fname, std::ifstream::binary); uint64_t graph_type; int nbbits; long nb_vertices; bool is_symmetric; uint64_t header[graph_file_header_sz]; in.read((char*)header, sizeof(header)); graph_type = header[0]; nbbits = int(header[1]); assert(nbbits == 64); nb_vertices = long(header[2]); nb_offsets = nb_vertices + 1; nb_edges = long(header[3]); long nb_cells_alloced = alloc(); long nb_bytes_allocated = nb_cells_alloced * sizeof(vtxid_type); is_symmetric = bool(header[4]); if (graph_type != GRAPH_TYPE_ADJLIST) pasl::util::atomic::fatal([] { std::cerr << "Bogus graph type." << std::endl; }); if (sizeof(vtxid_type) * 8 < nbbits) pasl::util::atomic::fatal([] { std::cerr << "Incompatible graph file." << std::endl; }); in.seekg (0, in.end); long contents_szb = long(in.tellg()) - sizeof(header); assert(contents_szb == nb_bytes_allocated); in.seekg (sizeof(header), in.beg); in.read (ptr.get(), contents_szb); in.close(); } }; std::ostream& output_directed_dot(std::ostream& out, const adjlist& graph) { out << "digraph {\n"; for (long i = 0; i < graph.get_nb_vertices(); ++i) { for (vtxid_type j = 0; j < graph.get_out_degree_of(i); j++) { neighbor_list neighbors = graph.get_neighbors_of(i); out << i << " -> " << neighbors[j] << ";\n"; } } return out << "}"; } std::ostream& operator<<(std::ostream& out, const adjlist& graph) { return output_directed_dot(out, graph); } using adjlist_ref = adjlist&; using const_adjlist_ref = const adjlist&; /*---------------------------------------------------------------------*/ /* Sequential BFS */ using distance_type = value_type; const distance_type dist_unknown = -1l; sparray bfs_seq(const_adjlist_ref graph, vtxid_type source) { long nb_vertices = graph.get_nb_vertices(); sparray dists = sparray(nb_vertices); for (long i = 0; i < nb_vertices; i++) dists[i] = dist_unknown; sparray frontiers[2]; frontiers[0] = sparray(nb_vertices); frontiers[1] = sparray(nb_vertices); long frontier_sizes[2]; frontier_sizes[0] = 0; frontier_sizes[1] = 0; vtxid_type cur = 0; // either 0 or 1, depending on parity of dist vtxid_type nxt = 1; // either 1 or 0, depending on parity of dist vtxid_type dist = 0; dists[source] = 0; frontiers[cur][frontier_sizes[cur]++] = source; while (frontier_sizes[cur] > 0) { long nb = frontier_sizes[cur]; for (vtxid_type ix = 0; ix < nb; ix++) { vtxid_type vertex = frontiers[cur][ix]; vtxid_type degree = graph.get_out_degree_of(vertex); neighbor_list neighbors = graph.get_neighbors_of(vertex); for (vtxid_type edge = 0; edge < degree; edge++) { vtxid_type other = neighbors[edge]; if (dists[other] != dist_unknown) continue; dists[other] = dist+1; if (graph.get_out_degree_of(other) > 0) frontiers[nxt][frontier_sizes[nxt]++] = other; } } frontier_sizes[cur] = 0; cur = 1 - cur; nxt = 1 - nxt; dist++; } return dists; } /*---------------------------------------------------------------------*/ /* Ligra */ const value_type not_a_vertexid = -1l; template <class Func> sparray vertex_map(const Func& f, const sparray& vertices) { return filter(f, vertices); } loop_controller_type process_neighbors_contr("process_neighbors"); template <class Update, class Cond, class Emit> void process_neighbors(const Update& update, const Cond& cond, const Emit& emit, const_adjlist_ref graph, long dist, long src) { neighbor_list neighbors = graph.get_neighbors_of(src); long degree = graph.get_out_degree_of(src); par::parallel_for(process_neighbors_contr, 0l, degree, [&] (long j) { vtxid_type dst = neighbors[j]; vtxid_type r = (cond(dst) and update(src, dst, dist)) ? dst : not_a_vertexid; emit(j, r); }); } sparray extract_vertexids(const sparray& vs) { return filter([] (vtxid_type v) { return v != not_a_vertexid; }, vs); } sparray get_out_degrees_of(const_adjlist_ref graph, const sparray& vs) { return map([&] (vtxid_type v) { return graph.get_out_degree_of(v); }, vs); } loop_controller_type edge_map_contr("edge_map"); template <class Update, class Cond> sparray edge_map(const Update& update, const Cond& cond, const_adjlist_ref graph, const sparray& in_frontier, long dist) { scan_excl_result offsets = prefix_sums_excl(get_out_degrees_of(graph, in_frontier)); long m = in_frontier.size(); long n = offsets.total; auto weight = [&] (long lo, long hi) { long u = (hi == m) ? n : offsets.partials[hi]; return u - offsets.partials[lo]; }; sparray out_frontier = sparray(n); par::parallel_for(edge_map_contr, weight, 0l, m, [&] (long i) { vtxid_type src = in_frontier[i]; long offset = offsets.partials[i]; auto emit = [&] (value_type j, vtxid_type r) { out_frontier[offset+j] = r; }; process_neighbors(update, cond, emit, graph, dist, src); }); return extract_vertexids(out_frontier); } /*---------------------------------------------------------------------*/ /* Parallel BFS */ loop_controller_type bfs_par_init_contr("bfs_init"); sparray bfs_par(const_adjlist_ref graph, vtxid_type source) { long n = graph.get_nb_vertices(); std::atomic<value_type>* atomic_dists = my_malloc<std::atomic<vtxid_type>>(n); par::parallel_for(bfs_par_init_contr, 0l, n, [&] (long i) { atomic_dists[i].store(dist_unknown); }); atomic_dists[source].store(0); auto update = [&] (vtxid_type src, vtxid_type dst, value_type dist) { long u = dist_unknown; return atomic_dists[dst].compare_exchange_strong(u, dist); }; auto cond = [&] (vtxid_type other) { return atomic_dists[other].load() == dist_unknown; }; sparray cur_frontier = { source }; long dist = 0; while (cur_frontier.size() > 0) { dist++; cur_frontier = edge_map(update, cond, graph, cur_frontier, dist); } sparray dists = tabulate([&] (long i) { return atomic_dists[i].load(); }, n); free(atomic_dists); return dists; } sparray bfs(const_adjlist_ref graph, vtxid_type source) { #ifdef SEQUENTIAL_BASELINE return bfs_seq(graph, source); #else return bfs_par(graph, source); #endif } /***********************************************************************/ #endif /*! _MINICOURSE_GRAPH_H_ */ <commit_msg>Fusion optimization for BFS<commit_after>/* COPYRIGHT (c) 2014 Umut Acar, Arthur Chargueraud, and Michael * Rainey * All rights reserved. * * \file graph.hpp * \brief Graph algorithms * */ #include <atomic> #include <vector> #include <algorithm> #include <fstream> #include <iostream> #include <istream> #include <ostream> #include <sstream> #include "sparray.hpp" #ifndef _MINICOURSE_GRAPH_H_ #define _MINICOURSE_GRAPH_H_ /***********************************************************************/ /*---------------------------------------------------------------------*/ /* Edge-list representation of graphs */ using vtxid_type = value_type; // convention: first component source vertex id, second target using edge_type = std::pair<vtxid_type, vtxid_type>; using edgelist = std::deque<edge_type>; edge_type mk_edge(vtxid_type source, vtxid_type dest) { return std::make_pair(source, dest); } long get_nb_vertices_of_edgelist(const edgelist& edges) { long nb = 0; for (long i = 0; i < edges.size(); i++) nb = std::max(nb, std::max(edges[i].first, edges[i].second)); return nb+1; } std::ostream& operator<<(std::ostream& out, const edge_type& edge) { out << edge.first << " -> " << edge.second << ";\n"; return out; } std::ostream& output_directed_dot(std::ostream& out, const edgelist& edges) { out << "digraph {\n"; for (long i = 0; i < edges.size(); ++i) out << edges[i]; return out << "}"; } std::ostream& operator<<(std::ostream& out, const edgelist& edges) { return output_directed_dot(out, edges); } /*---------------------------------------------------------------------*/ /* Adjacency-list representation of graphs */ using neighbor_list = const value_type*; class adjlist { private: class Deleter { public: void operator()(char* ptr) { free(ptr); } }; std::unique_ptr<char[], Deleter> ptr; long nb_offsets = 0l; // == nb_vertices+1 long nb_edges = 0l; vtxid_type* start_offsets; vtxid_type* start_edgelists; void check(vtxid_type v) const { assert(v >= 0l); assert(v < nb_offsets-1); } long alloc() { long nb_cells_allocated = nb_offsets + nb_edges;; char* p = (char*)my_malloc<vtxid_type>(nb_cells_allocated); assert(nb_cells_allocated==0l || p != nullptr); ptr.reset(p); start_offsets = (vtxid_type*)p; start_edgelists = &start_offsets[nb_offsets]; return nb_cells_allocated; } void from_edgelist(const edgelist& edges) { long nb_vertices = get_nb_vertices_of_edgelist(edges); nb_offsets = nb_vertices + 1; nb_edges = edges.size(); alloc(); sparray degrees = sparray(nb_vertices); for (vtxid_type i = 0; i < nb_vertices; i++) degrees[i] = 0; for (long i = 0; i < edges.size(); i++) { edge_type e = edges[i]; degrees[e.first]++; } start_offsets[0] = 0; for (vtxid_type i = 1; i < nb_offsets; i++) start_offsets[i] = start_offsets[i - 1] + degrees[i - 1]; for (vtxid_type i = 0; i < nb_vertices; i++) degrees[i] = 0; for (long i = 0; i < edges.size(); i++) { edge_type e = edges[i]; vtxid_type cnt = degrees[e.first]; start_edgelists[start_offsets[e.first] + cnt] = e.second; degrees[e.first]++; } } const uint64_t GRAPH_TYPE_ADJLIST = 0xdeadbeef; const uint64_t GRAPH_TYPE_EDGELIST = 0xba5eba11; const int bits_per_byte = 8; const int graph_file_header_sz = 5; public: adjlist(long nb_vertices = 0, long nb_edges = 0) : nb_offsets(nb_vertices+1), nb_edges(nb_edges) { if (nb_vertices > 0) alloc(); } adjlist(const edgelist& edges) { from_edgelist(edges); } adjlist(std::initializer_list<edge_type> edges_init) { edgelist edges; for (auto it = edges_init.begin(); it != edges_init.end(); it++) edges.push_back(*it); from_edgelist(edges); } // To disable copy semantics, we disable: adjlist(const adjlist& other); // 1. copy constructor adjlist& operator=(const adjlist& other); // 2. assign-by-copy operator adjlist& operator=(adjlist&& other) { // todo: make sure that the following does not create a memory leak ptr = std::move(other.ptr); nb_offsets = std::move(other.nb_offsets); nb_edges = std::move(other.nb_edges); start_offsets = std::move(other.start_offsets); start_edgelists = std::move(other.start_edgelists); return *this; } long get_nb_vertices() const { return nb_offsets-1l; } long get_nb_edges() const { return nb_edges; } long get_out_degree_of(vtxid_type v) const { check(v); return start_offsets[v+1] - start_offsets[v]; } neighbor_list get_neighbors_of(vtxid_type v) const { check(v); return &start_edgelists[start_offsets[v]]; } void load_from_file(std::string fname) { std::ifstream in(fname, std::ifstream::binary); uint64_t graph_type; int nbbits; long nb_vertices; bool is_symmetric; uint64_t header[graph_file_header_sz]; in.read((char*)header, sizeof(header)); graph_type = header[0]; nbbits = int(header[1]); assert(nbbits == 64); nb_vertices = long(header[2]); nb_offsets = nb_vertices + 1; nb_edges = long(header[3]); long nb_cells_alloced = alloc(); long nb_bytes_allocated = nb_cells_alloced * sizeof(vtxid_type); is_symmetric = bool(header[4]); if (graph_type != GRAPH_TYPE_ADJLIST) pasl::util::atomic::fatal([] { std::cerr << "Bogus graph type." << std::endl; }); if (sizeof(vtxid_type) * 8 < nbbits) pasl::util::atomic::fatal([] { std::cerr << "Incompatible graph file." << std::endl; }); in.seekg (0, in.end); long contents_szb = long(in.tellg()) - sizeof(header); assert(contents_szb == nb_bytes_allocated); in.seekg (sizeof(header), in.beg); in.read (ptr.get(), contents_szb); in.close(); } }; std::ostream& output_directed_dot(std::ostream& out, const adjlist& graph) { out << "digraph {\n"; for (long i = 0; i < graph.get_nb_vertices(); ++i) { for (vtxid_type j = 0; j < graph.get_out_degree_of(i); j++) { neighbor_list neighbors = graph.get_neighbors_of(i); out << i << " -> " << neighbors[j] << ";\n"; } } return out << "}"; } std::ostream& operator<<(std::ostream& out, const adjlist& graph) { return output_directed_dot(out, graph); } using adjlist_ref = adjlist&; using const_adjlist_ref = const adjlist&; /*---------------------------------------------------------------------*/ /* Sequential BFS */ using distance_type = value_type; const distance_type dist_unknown = -1l; sparray bfs_seq(const_adjlist_ref graph, vtxid_type source) { long nb_vertices = graph.get_nb_vertices(); sparray dists = sparray(nb_vertices); for (long i = 0; i < nb_vertices; i++) dists[i] = dist_unknown; sparray frontiers[2]; frontiers[0] = sparray(nb_vertices); frontiers[1] = sparray(nb_vertices); long frontier_sizes[2]; frontier_sizes[0] = 0; frontier_sizes[1] = 0; vtxid_type cur = 0; // either 0 or 1, depending on parity of dist vtxid_type nxt = 1; // either 1 or 0, depending on parity of dist vtxid_type dist = 0; dists[source] = 0; frontiers[cur][frontier_sizes[cur]++] = source; while (frontier_sizes[cur] > 0) { long nb = frontier_sizes[cur]; for (vtxid_type ix = 0; ix < nb; ix++) { vtxid_type vertex = frontiers[cur][ix]; vtxid_type degree = graph.get_out_degree_of(vertex); neighbor_list neighbors = graph.get_neighbors_of(vertex); for (vtxid_type edge = 0; edge < degree; edge++) { vtxid_type other = neighbors[edge]; if (dists[other] != dist_unknown) continue; dists[other] = dist+1; if (graph.get_out_degree_of(other) > 0) frontiers[nxt][frontier_sizes[nxt]++] = other; } } frontier_sizes[cur] = 0; cur = 1 - cur; nxt = 1 - nxt; dist++; } return dists; } /*---------------------------------------------------------------------*/ /* Ligra */ const value_type not_a_vertexid = -1l; template <class Func> sparray vertex_map(const Func& f, const sparray& vertices) { return filter(f, vertices); } loop_controller_type process_neighbors_contr("process_neighbors"); template <class Update, class Cond, class Emit> void process_neighbors(const Update& update, const Cond& cond, const Emit& emit, const_adjlist_ref graph, long dist, long src) { neighbor_list neighbors = graph.get_neighbors_of(src); long degree = graph.get_out_degree_of(src); par::parallel_for(process_neighbors_contr, 0l, degree, [&] (long j) { vtxid_type dst = neighbors[j]; vtxid_type r = (cond(dst) and update(src, dst, dist)) ? dst : not_a_vertexid; emit(j, r); }); } sparray extract_vertexids(const sparray& vs) { return filter([] (vtxid_type v) { return v != not_a_vertexid; }, vs); } sparray get_out_degrees_of(const_adjlist_ref graph, const sparray& vs) { return map([&] (vtxid_type v) { return graph.get_out_degree_of(v); }, vs); } loop_controller_type edge_map_contr("edge_map"); template <class Update, class Cond> sparray edge_map(const Update& update, const Cond& cond, const_adjlist_ref graph, const sparray& in_frontier, long dist) { /* scan_excl_result offsets = prefix_sums_excl(get_out_degrees_of(graph, in_frontier)); */ auto get_outdegree_fct = [&] (vtxid_type v) { return graph.get_out_degree_of(v); }; scan_excl_result offsets = scan_excl(plus_fct, get_outdegree_fct, 0l, in_frontier); long m = in_frontier.size(); long n = offsets.total; auto weight = [&] (long lo, long hi) { long u = (hi == m) ? n : offsets.partials[hi]; return u - offsets.partials[lo]; }; sparray out_frontier = sparray(n); par::parallel_for(edge_map_contr, weight, 0l, m, [&] (long i) { vtxid_type src = in_frontier[i]; long offset = offsets.partials[i]; auto emit = [&] (value_type j, vtxid_type r) { out_frontier[offset+j] = r; }; process_neighbors(update, cond, emit, graph, dist, src); }); return extract_vertexids(out_frontier); } /*---------------------------------------------------------------------*/ /* Parallel BFS */ loop_controller_type bfs_par_init_contr("bfs_init"); sparray bfs_par(const_adjlist_ref graph, vtxid_type source) { long n = graph.get_nb_vertices(); std::atomic<value_type>* atomic_dists = my_malloc<std::atomic<vtxid_type>>(n); par::parallel_for(bfs_par_init_contr, 0l, n, [&] (long i) { atomic_dists[i].store(dist_unknown); }); atomic_dists[source].store(0); auto update = [&] (vtxid_type src, vtxid_type dst, value_type dist) { long u = dist_unknown; return atomic_dists[dst].compare_exchange_strong(u, dist); }; auto cond = [&] (vtxid_type other) { return atomic_dists[other].load() == dist_unknown; }; sparray cur_frontier = { source }; long dist = 0; while (cur_frontier.size() > 0) { dist++; cur_frontier = edge_map(update, cond, graph, cur_frontier, dist); } sparray dists = tabulate([&] (long i) { return atomic_dists[i].load(); }, n); free(atomic_dists); return dists; } sparray bfs(const_adjlist_ref graph, vtxid_type source) { #ifdef SEQUENTIAL_BASELINE return bfs_seq(graph, source); #else return bfs_par(graph, source); #endif } /***********************************************************************/ #endif /*! _MINICOURSE_GRAPH_H_ */ <|endoftext|>
<commit_before>// Copyright 2014 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 "sky/engine/bindings/builtin_natives.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "base/bind.h" #include "base/logging.h" #include "base/macros.h" #include "base/time/time.h" #include "dart/runtime/include/dart_api.h" #include "sky/engine/bindings/builtin.h" #include "sky/engine/core/dom/Microtask.h" #include "sky/engine/core/script/dom_dart_state.h" #include "sky/engine/tonic/dart_api_scope.h" #include "sky/engine/tonic/dart_builtin.h" #include "sky/engine/tonic/dart_error.h" #include "sky/engine/tonic/dart_invoke.h" #include "sky/engine/tonic/dart_isolate_scope.h" #include "sky/engine/tonic/dart_state.h" #include "sky/engine/tonic/dart_timer_heap.h" #include "sky/engine/tonic/dart_value.h" #include "sky/engine/wtf/text/WTFString.h" #if defined(OS_ANDROID) #include <android/log.h> #endif namespace blink { #define REGISTER_FUNCTION(name, count) \ { "" #name, name, count }, #define DECLARE_FUNCTION(name, count) \ extern void name(Dart_NativeArguments args); // Lists the native functions implementing basic functionality in // the Mojo embedder dart, such as printing, and file I/O. #define BUILTIN_NATIVE_LIST(V) \ V(Logger_PrintString, 1) \ V(ScheduleMicrotask, 1) \ V(GetBaseURLString, 0) \ V(Timer_create, 3) \ V(Timer_cancel, 1) BUILTIN_NATIVE_LIST(DECLARE_FUNCTION); static struct NativeEntries { const char* name; Dart_NativeFunction function; int argument_count; } BuiltinEntries[] = {BUILTIN_NATIVE_LIST(REGISTER_FUNCTION)}; Dart_NativeFunction BuiltinNatives::NativeLookup(Dart_Handle name, int argument_count, bool* auto_setup_scope) { const char* function_name = nullptr; Dart_Handle result = Dart_StringToCString(name, &function_name); DART_CHECK_VALID(result); DCHECK(function_name != nullptr); DCHECK(auto_setup_scope != nullptr); *auto_setup_scope = true; size_t num_entries = arraysize(BuiltinEntries); for (size_t i = 0; i < num_entries; i++) { const struct NativeEntries& entry = BuiltinEntries[i]; if (!strcmp(function_name, entry.name) && (entry.argument_count == argument_count)) { return entry.function; } } return nullptr; } const uint8_t* BuiltinNatives::NativeSymbol(Dart_NativeFunction native_function) { size_t num_entries = arraysize(BuiltinEntries); for (size_t i = 0; i < num_entries; i++) { const struct NativeEntries& entry = BuiltinEntries[i]; if (entry.function == native_function) { return reinterpret_cast<const uint8_t*>(entry.name); } } return nullptr; } static Dart_Handle GetClosure(Dart_Handle builtin_library, const char* name) { Dart_Handle getter_name = ToDart(name); Dart_Handle closure = Dart_Invoke(builtin_library, getter_name, 0, nullptr); DART_CHECK_VALID(closure); return closure; } static void InitDartInternal(Dart_Handle builtin_library, BuiltinNatives::IsolateType isolate_type) { Dart_Handle print = GetClosure(builtin_library, "_getPrintClosure"); Dart_Handle timer = GetClosure(builtin_library, "_getCreateTimerClosure"); Dart_Handle internal_library = DartBuiltin::LookupLibrary("dart:_internal"); DART_CHECK_VALID(Dart_SetField( internal_library, ToDart("_printClosure"), print)); if (isolate_type == BuiltinNatives::MainIsolate) { Dart_Handle vm_hooks_name = ToDart("VMLibraryHooks"); Dart_Handle vm_hooks = Dart_GetClass(internal_library, vm_hooks_name); DART_CHECK_VALID(vm_hooks); Dart_Handle timer_name = ToDart("timerFactory"); DART_CHECK_VALID(Dart_SetField(vm_hooks, timer_name, timer)); } else { CHECK(isolate_type == BuiltinNatives::DartIOIsolate); Dart_Handle io_lib = DartBuiltin::LookupLibrary("dart:io"); Dart_Handle setup_hooks = Dart_NewStringFromCString("_setupHooks"); DART_CHECK_VALID(Dart_Invoke(io_lib, setup_hooks, 0, NULL)); Dart_Handle isolate_lib = DartBuiltin::LookupLibrary("dart:isolate"); DART_CHECK_VALID(Dart_Invoke(isolate_lib, setup_hooks, 0, NULL)); } } static void InitDartCore(Dart_Handle builtin, BuiltinNatives::IsolateType isolate_type) { Dart_Handle get_base_url = GetClosure(builtin, "_getGetBaseURLClosure"); Dart_Handle core_library = DartBuiltin::LookupLibrary("dart:core"); DART_CHECK_VALID(Dart_SetField(core_library, ToDart("_uriBaseClosure"), get_base_url)); } static void InitDartAsync(Dart_Handle builtin_library, BuiltinNatives::IsolateType isolate_type) { Dart_Handle schedule_microtask; if (isolate_type == BuiltinNatives::MainIsolate) { schedule_microtask = GetClosure(builtin_library, "_getScheduleMicrotaskClosure"); } else { CHECK(isolate_type == BuiltinNatives::DartIOIsolate); Dart_Handle isolate_lib = DartBuiltin::LookupLibrary("dart:isolate"); Dart_Handle method_name = Dart_NewStringFromCString("_getIsolateScheduleImmediateClosure"); schedule_microtask = Dart_Invoke(isolate_lib, method_name, 0, NULL); } Dart_Handle async_library = DartBuiltin::LookupLibrary("dart:async"); Dart_Handle set_schedule_microtask = ToDart("_setScheduleImmediateClosure"); DART_CHECK_VALID(Dart_Invoke(async_library, set_schedule_microtask, 1, &schedule_microtask)); } void BuiltinNatives::Init(IsolateType isolate_type) { Dart_Handle builtin = Builtin::LoadAndCheckLibrary(Builtin::kBuiltinLibrary); DART_CHECK_VALID(builtin); InitDartInternal(builtin, isolate_type); InitDartCore(builtin, isolate_type); InitDartAsync(builtin, isolate_type); } // Implementation of native functions which are used for some // test/debug functionality in standalone dart mode. void Logger_PrintString(Dart_NativeArguments args) { intptr_t length = 0; uint8_t* chars = nullptr; Dart_Handle str = Dart_GetNativeArgument(args, 0); Dart_Handle result = Dart_StringToUTF8(str, &chars, &length); if (Dart_IsError(result)) { Dart_PropagateError(result); } else { // Uses fwrite to support printing NUL bytes. fwrite(chars, 1, length, stdout); fputs("\n", stdout); #if defined(OS_ANDROID) // In addition to writing to the stdout, write to the logcat so that the // message is discoverable when running on an unrooted device. __android_log_print(ANDROID_LOG_INFO, "sky", "%.*s", length, chars); #endif } } static void ExecuteMicrotask(base::WeakPtr<DartState> dart_state, RefPtr<DartValue> callback) { if (!dart_state) return; DartIsolateScope scope(dart_state->isolate()); DartApiScope api_scope; DartInvokeAppClosure(callback->dart_value(), 0, nullptr); } void ScheduleMicrotask(Dart_NativeArguments args) { Dart_Handle closure = Dart_GetNativeArgument(args, 0); if (LogIfError(closure) || !Dart_IsClosure(closure)) return; DartState* dart_state = DartState::Current(); CHECK(dart_state); Microtask::enqueueMicrotask(base::Bind(&ExecuteMicrotask, dart_state->GetWeakPtr(), DartValue::Create(dart_state, closure))); } void GetBaseURLString(Dart_NativeArguments args) { String url = DOMDartState::Current()->url(); Dart_SetReturnValue(args, StringToDart(DartState::Current(), url)); } void Timer_create(Dart_NativeArguments args) { int64_t milliseconds = 0; DART_CHECK_VALID(Dart_GetNativeIntegerArgument(args, 0, &milliseconds)); Dart_Handle closure = Dart_GetNativeArgument(args, 1); DART_CHECK_VALID(closure); CHECK(Dart_IsClosure(closure)); bool repeating = false; DART_CHECK_VALID(Dart_GetNativeBooleanArgument(args, 2, &repeating)); DartState* state = DartState::Current(); CHECK(state); std::unique_ptr<DartTimerHeap::Task> task = std::unique_ptr<DartTimerHeap::Task>(new DartTimerHeap::Task); task->closure.Set(state, closure); task->delay = base::TimeDelta::FromMilliseconds(milliseconds); task->repeating = repeating; int timer_id = state->timer_heap().Add(std::move(task)); Dart_SetIntegerReturnValue(args, timer_id); } void Timer_cancel(Dart_NativeArguments args) { int64_t timer_id = 0; DART_CHECK_VALID(Dart_GetNativeIntegerArgument(args, 0, &timer_id)); DartState* state = DartState::Current(); CHECK(state); state->timer_heap().Remove(timer_id); } } // namespace blink <commit_msg>Make Dart |print| calls show up when running on Mac and iOS.<commit_after>// Copyright 2014 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 "sky/engine/bindings/builtin_natives.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "base/bind.h" #include "base/logging.h" #include "base/macros.h" #include "base/time/time.h" #include "dart/runtime/include/dart_api.h" #include "sky/engine/bindings/builtin.h" #include "sky/engine/core/dom/Microtask.h" #include "sky/engine/core/script/dom_dart_state.h" #include "sky/engine/tonic/dart_api_scope.h" #include "sky/engine/tonic/dart_builtin.h" #include "sky/engine/tonic/dart_error.h" #include "sky/engine/tonic/dart_invoke.h" #include "sky/engine/tonic/dart_isolate_scope.h" #include "sky/engine/tonic/dart_state.h" #include "sky/engine/tonic/dart_timer_heap.h" #include "sky/engine/tonic/dart_value.h" #include "sky/engine/wtf/text/WTFString.h" #if defined(OS_ANDROID) #include <android/log.h> #endif #if __APPLE__ #include <syslog.h> #endif namespace blink { #define REGISTER_FUNCTION(name, count) \ { "" #name, name, count }, #define DECLARE_FUNCTION(name, count) \ extern void name(Dart_NativeArguments args); // Lists the native functions implementing basic functionality in // the Mojo embedder dart, such as printing, and file I/O. #define BUILTIN_NATIVE_LIST(V) \ V(Logger_PrintString, 1) \ V(ScheduleMicrotask, 1) \ V(GetBaseURLString, 0) \ V(Timer_create, 3) \ V(Timer_cancel, 1) BUILTIN_NATIVE_LIST(DECLARE_FUNCTION); static struct NativeEntries { const char* name; Dart_NativeFunction function; int argument_count; } BuiltinEntries[] = {BUILTIN_NATIVE_LIST(REGISTER_FUNCTION)}; Dart_NativeFunction BuiltinNatives::NativeLookup(Dart_Handle name, int argument_count, bool* auto_setup_scope) { const char* function_name = nullptr; Dart_Handle result = Dart_StringToCString(name, &function_name); DART_CHECK_VALID(result); DCHECK(function_name != nullptr); DCHECK(auto_setup_scope != nullptr); *auto_setup_scope = true; size_t num_entries = arraysize(BuiltinEntries); for (size_t i = 0; i < num_entries; i++) { const struct NativeEntries& entry = BuiltinEntries[i]; if (!strcmp(function_name, entry.name) && (entry.argument_count == argument_count)) { return entry.function; } } return nullptr; } const uint8_t* BuiltinNatives::NativeSymbol(Dart_NativeFunction native_function) { size_t num_entries = arraysize(BuiltinEntries); for (size_t i = 0; i < num_entries; i++) { const struct NativeEntries& entry = BuiltinEntries[i]; if (entry.function == native_function) { return reinterpret_cast<const uint8_t*>(entry.name); } } return nullptr; } static Dart_Handle GetClosure(Dart_Handle builtin_library, const char* name) { Dart_Handle getter_name = ToDart(name); Dart_Handle closure = Dart_Invoke(builtin_library, getter_name, 0, nullptr); DART_CHECK_VALID(closure); return closure; } static void InitDartInternal(Dart_Handle builtin_library, BuiltinNatives::IsolateType isolate_type) { Dart_Handle print = GetClosure(builtin_library, "_getPrintClosure"); Dart_Handle timer = GetClosure(builtin_library, "_getCreateTimerClosure"); Dart_Handle internal_library = DartBuiltin::LookupLibrary("dart:_internal"); DART_CHECK_VALID(Dart_SetField( internal_library, ToDart("_printClosure"), print)); if (isolate_type == BuiltinNatives::MainIsolate) { Dart_Handle vm_hooks_name = ToDart("VMLibraryHooks"); Dart_Handle vm_hooks = Dart_GetClass(internal_library, vm_hooks_name); DART_CHECK_VALID(vm_hooks); Dart_Handle timer_name = ToDart("timerFactory"); DART_CHECK_VALID(Dart_SetField(vm_hooks, timer_name, timer)); } else { CHECK(isolate_type == BuiltinNatives::DartIOIsolate); Dart_Handle io_lib = DartBuiltin::LookupLibrary("dart:io"); Dart_Handle setup_hooks = Dart_NewStringFromCString("_setupHooks"); DART_CHECK_VALID(Dart_Invoke(io_lib, setup_hooks, 0, NULL)); Dart_Handle isolate_lib = DartBuiltin::LookupLibrary("dart:isolate"); DART_CHECK_VALID(Dart_Invoke(isolate_lib, setup_hooks, 0, NULL)); } } static void InitDartCore(Dart_Handle builtin, BuiltinNatives::IsolateType isolate_type) { Dart_Handle get_base_url = GetClosure(builtin, "_getGetBaseURLClosure"); Dart_Handle core_library = DartBuiltin::LookupLibrary("dart:core"); DART_CHECK_VALID(Dart_SetField(core_library, ToDart("_uriBaseClosure"), get_base_url)); } static void InitDartAsync(Dart_Handle builtin_library, BuiltinNatives::IsolateType isolate_type) { Dart_Handle schedule_microtask; if (isolate_type == BuiltinNatives::MainIsolate) { schedule_microtask = GetClosure(builtin_library, "_getScheduleMicrotaskClosure"); } else { CHECK(isolate_type == BuiltinNatives::DartIOIsolate); Dart_Handle isolate_lib = DartBuiltin::LookupLibrary("dart:isolate"); Dart_Handle method_name = Dart_NewStringFromCString("_getIsolateScheduleImmediateClosure"); schedule_microtask = Dart_Invoke(isolate_lib, method_name, 0, NULL); } Dart_Handle async_library = DartBuiltin::LookupLibrary("dart:async"); Dart_Handle set_schedule_microtask = ToDart("_setScheduleImmediateClosure"); DART_CHECK_VALID(Dart_Invoke(async_library, set_schedule_microtask, 1, &schedule_microtask)); } void BuiltinNatives::Init(IsolateType isolate_type) { Dart_Handle builtin = Builtin::LoadAndCheckLibrary(Builtin::kBuiltinLibrary); DART_CHECK_VALID(builtin); InitDartInternal(builtin, isolate_type); InitDartCore(builtin, isolate_type); InitDartAsync(builtin, isolate_type); } // Implementation of native functions which are used for some // test/debug functionality in standalone dart mode. void Logger_PrintString(Dart_NativeArguments args) { intptr_t length = 0; uint8_t* chars = nullptr; Dart_Handle str = Dart_GetNativeArgument(args, 0); Dart_Handle result = Dart_StringToUTF8(str, &chars, &length); if (Dart_IsError(result)) { Dart_PropagateError(result); } else { // Uses fwrite to support printing NUL bytes. fwrite(chars, 1, length, stdout); fputs("\n", stdout); #if defined(OS_ANDROID) // In addition to writing to the stdout, write to the logcat so that the // message is discoverable when running on an unrooted device. __android_log_print(ANDROID_LOG_INFO, "sky", "%.*s", length, chars); #elif __APPLE__ syslog(LOG_WARNING, "sky: %.*s", (int)length, chars); #endif } } static void ExecuteMicrotask(base::WeakPtr<DartState> dart_state, RefPtr<DartValue> callback) { if (!dart_state) return; DartIsolateScope scope(dart_state->isolate()); DartApiScope api_scope; DartInvokeAppClosure(callback->dart_value(), 0, nullptr); } void ScheduleMicrotask(Dart_NativeArguments args) { Dart_Handle closure = Dart_GetNativeArgument(args, 0); if (LogIfError(closure) || !Dart_IsClosure(closure)) return; DartState* dart_state = DartState::Current(); CHECK(dart_state); Microtask::enqueueMicrotask(base::Bind(&ExecuteMicrotask, dart_state->GetWeakPtr(), DartValue::Create(dart_state, closure))); } void GetBaseURLString(Dart_NativeArguments args) { String url = DOMDartState::Current()->url(); Dart_SetReturnValue(args, StringToDart(DartState::Current(), url)); } void Timer_create(Dart_NativeArguments args) { int64_t milliseconds = 0; DART_CHECK_VALID(Dart_GetNativeIntegerArgument(args, 0, &milliseconds)); Dart_Handle closure = Dart_GetNativeArgument(args, 1); DART_CHECK_VALID(closure); CHECK(Dart_IsClosure(closure)); bool repeating = false; DART_CHECK_VALID(Dart_GetNativeBooleanArgument(args, 2, &repeating)); DartState* state = DartState::Current(); CHECK(state); std::unique_ptr<DartTimerHeap::Task> task = std::unique_ptr<DartTimerHeap::Task>(new DartTimerHeap::Task); task->closure.Set(state, closure); task->delay = base::TimeDelta::FromMilliseconds(milliseconds); task->repeating = repeating; int timer_id = state->timer_heap().Add(std::move(task)); Dart_SetIntegerReturnValue(args, timer_id); } void Timer_cancel(Dart_NativeArguments args) { int64_t timer_id = 0; DART_CHECK_VALID(Dart_GetNativeIntegerArgument(args, 0, &timer_id)); DartState* state = DartState::Current(); CHECK(state); state->timer_heap().Remove(timer_id); } } // namespace blink <|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * BP3Writer.cpp * * Created on: Dec 19, 2016 * Author: William F Godoy godoywf@ornl.gov */ #include "BP3Writer.h" #include "BP3Writer.tcc" #include "adios2/ADIOSMPI.h" #include "adios2/ADIOSMacros.h" #include "adios2/core/IO.h" #include "adios2/helper/adiosFunctions.h" //CheckIndexRange #include "adios2/toolkit/transport/file/FileFStream.h" namespace adios2 { namespace core { namespace engine { BP3Writer::BP3Writer(IO &io, const std::string &name, const Mode mode, MPI_Comm mpiComm) : Engine("BP3", io, name, mode, mpiComm), m_BP3Serializer(mpiComm, m_DebugMode), m_FileDataManager(mpiComm, m_DebugMode), m_FileMetadataManager(mpiComm, m_DebugMode) { m_IO.m_ReadStreaming = false; m_EndMessage = " in call to IO Open BPFileWriter " + m_Name + "\n"; Init(); } StepStatus BP3Writer::BeginStep(StepMode mode, const float timeoutSeconds) { m_BP3Serializer.m_DeferredVariables.clear(); m_BP3Serializer.m_DeferredVariablesDataSize = 0; m_IO.m_ReadStreaming = false; return StepStatus::OK; } size_t BP3Writer::CurrentStep() const { return m_BP3Serializer.m_MetadataSet.CurrentStep; } void BP3Writer::PerformPuts() { if (m_BP3Serializer.m_DeferredVariables.empty()) { return; } m_BP3Serializer.ResizeBuffer(m_BP3Serializer.m_DeferredVariablesDataSize, "in call to PerformPuts"); for (const std::string &variableName : m_BP3Serializer.m_DeferredVariables) { const std::string type = m_IO.InquireVariableType(variableName); if (type == "compound") { // not supported } #define declare_template_instantiation(T) \ else if (type == helper::GetType<T>()) \ { \ Variable<T> &variable = FindVariable<T>( \ variableName, "in call to PerformPuts, EndStep or Close"); \ PerformPutCommon(variable); \ } ADIOS2_FOREACH_PRIMITIVE_STDTYPE_1ARG(declare_template_instantiation) #undef declare_template_instantiation } m_BP3Serializer.m_DeferredVariables.clear(); } void BP3Writer::EndStep() { if (m_BP3Serializer.m_DeferredVariables.size() > 0) { PerformPuts(); } // true: advances step m_BP3Serializer.SerializeData(m_IO, true); const size_t currentStep = CurrentStep(); const size_t flushStepsCount = m_BP3Serializer.m_FlushStepsCount; if (currentStep % flushStepsCount == 0) { Flush(); } } void BP3Writer::Flush(const int transportIndex) { DoFlush(false, transportIndex); m_BP3Serializer.ResetBuffer(m_BP3Serializer.m_Data); if (m_BP3Serializer.m_CollectiveMetadata) { WriteCollectiveMetadataFile(); } } // PRIVATE void BP3Writer::Init() { InitParameters(); InitTransports(); InitBPBuffer(); } #define declare_type(T) \ void BP3Writer::DoPut(Variable<T> &variable, \ typename Variable<T>::Span &span, \ const size_t bufferID) \ { \ return PutCommon(variable, span, bufferID); \ } ADIOS2_FOREACH_PRIMITIVE_STDTYPE_1ARG(declare_type) #undef declare_type #define declare_type(T) \ void BP3Writer::DoPutSync(Variable<T> &variable, const T *data) \ { \ PutSyncCommon(variable, variable.SetBlockInfo(data, CurrentStep())); \ variable.m_BlocksInfo.clear(); \ } \ void BP3Writer::DoPutDeferred(Variable<T> &variable, const T *data) \ { \ PutDeferredCommon(variable, data); \ } ADIOS2_FOREACH_STDTYPE_1ARG(declare_type) #undef declare_type void BP3Writer::InitParameters() { m_BP3Serializer.InitParameters(m_IO.m_Parameters); } void BP3Writer::InitTransports() { // TODO need to add support for aggregators here later if (m_IO.m_TransportsParameters.empty()) { Params defaultTransportParameters; defaultTransportParameters["transport"] = "File"; m_IO.m_TransportsParameters.push_back(defaultTransportParameters); } // only consumers will interact with transport managers std::vector<std::string> bpSubStreamNames; if (m_BP3Serializer.m_Aggregator.m_IsConsumer) { // Names passed to IO AddTransport option with key "Name" const std::vector<std::string> transportsNames = m_FileDataManager.GetFilesBaseNames(m_Name, m_IO.m_TransportsParameters); // /path/name.bp.dir/name.bp.rank bpSubStreamNames = m_BP3Serializer.GetBPSubStreamNames(transportsNames); } m_BP3Serializer.ProfilerStart("mkdir"); m_FileDataManager.MkDirsBarrier(bpSubStreamNames, m_BP3Serializer.m_NodeLocal); m_BP3Serializer.ProfilerStop("mkdir"); if (m_BP3Serializer.m_Aggregator.m_IsConsumer) { m_FileDataManager.OpenFiles(bpSubStreamNames, m_OpenMode, m_IO.m_TransportsParameters, m_BP3Serializer.m_Profiler.IsActive); } } void BP3Writer::InitBPBuffer() { if (m_OpenMode == Mode::Append) { throw std::invalid_argument( "ADIOS2: OpenMode Append hasn't been implemented, yet"); // TODO: Get last pg timestep and update timestep counter in } else { m_BP3Serializer.PutProcessGroupIndex( m_IO.m_Name, m_IO.m_HostLanguage, m_FileDataManager.GetTransportsTypes()); } } void BP3Writer::DoFlush(const bool isFinal, const int transportIndex) { if (m_BP3Serializer.m_Aggregator.m_IsActive) { AggregateWriteData(isFinal, transportIndex); } else { WriteData(isFinal, transportIndex); } } void BP3Writer::DoClose(const int transportIndex) { if (m_BP3Serializer.m_DeferredVariables.size() > 0) { PerformPuts(); } DoFlush(true, transportIndex); if (m_BP3Serializer.m_Aggregator.m_IsConsumer) { m_FileDataManager.CloseFiles(transportIndex); } if (m_BP3Serializer.m_CollectiveMetadata && m_FileDataManager.AllTransportsClosed()) { WriteCollectiveMetadataFile(true); } if (m_BP3Serializer.m_Profiler.IsActive && m_FileDataManager.AllTransportsClosed()) { WriteProfilingJSONFile(); } } void BP3Writer::WriteProfilingJSONFile() { auto transportTypes = m_FileDataManager.GetTransportsTypes(); auto transportProfilers = m_FileDataManager.GetTransportsProfilers(); auto transportTypesMD = m_FileMetadataManager.GetTransportsTypes(); auto transportProfilersMD = m_FileMetadataManager.GetTransportsProfilers(); transportTypes.insert(transportTypes.end(), transportTypesMD.begin(), transportTypesMD.end()); transportProfilers.insert(transportProfilers.end(), transportProfilersMD.begin(), transportProfilersMD.end()); const std::string lineJSON(m_BP3Serializer.GetRankProfilingJSON( transportTypes, transportProfilers) + ",\n"); const std::vector<char> profilingJSON( m_BP3Serializer.AggregateProfilingJSON(lineJSON)); if (m_BP3Serializer.m_RankMPI == 0) { transport::FileFStream profilingJSONStream(m_MPIComm, m_DebugMode); auto bpBaseNames = m_BP3Serializer.GetBPBaseNames({m_Name}); profilingJSONStream.Open(bpBaseNames[0] + "/profiling.json", Mode::Write); profilingJSONStream.Write(profilingJSON.data(), profilingJSON.size()); profilingJSONStream.Close(); } } void BP3Writer::WriteCollectiveMetadataFile(const bool isFinal) { m_BP3Serializer.AggregateCollectiveMetadata( m_MPIComm, m_BP3Serializer.m_Metadata, true); if (m_BP3Serializer.m_RankMPI == 0) { // first init metadata files const std::vector<std::string> transportsNames = m_FileMetadataManager.GetFilesBaseNames( m_Name, m_IO.m_TransportsParameters); const std::vector<std::string> bpMetadataFileNames = m_BP3Serializer.GetBPMetadataFileNames(transportsNames); m_FileMetadataManager.OpenFiles(bpMetadataFileNames, m_OpenMode, m_IO.m_TransportsParameters, m_BP3Serializer.m_Profiler.IsActive); m_FileMetadataManager.WriteFiles( m_BP3Serializer.m_Metadata.m_Buffer.data(), m_BP3Serializer.m_Metadata.m_Position); m_FileMetadataManager.CloseFiles(); if (!isFinal) { m_BP3Serializer.ResetBuffer(m_BP3Serializer.m_Metadata, true); m_FileMetadataManager.m_Transports.clear(); } } } void BP3Writer::WriteData(const bool isFinal, const int transportIndex) { size_t dataSize = m_BP3Serializer.m_Data.m_Position; if (isFinal) { m_BP3Serializer.CloseData(m_IO); dataSize = m_BP3Serializer.m_Data.m_Position; } else { m_BP3Serializer.CloseStream(m_IO); } m_FileDataManager.WriteFiles(m_BP3Serializer.m_Data.m_Buffer.data(), dataSize, transportIndex); m_FileDataManager.FlushFiles(transportIndex); } void BP3Writer::AggregateWriteData(const bool isFinal, const int transportIndex) { m_BP3Serializer.CloseStream(m_IO, false); // async? for (int r = 0; r < m_BP3Serializer.m_Aggregator.m_Size; ++r) { std::vector<MPI_Request> dataRequests = m_BP3Serializer.m_Aggregator.IExchange(m_BP3Serializer.m_Data, r); std::vector<MPI_Request> absolutePositionRequests = m_BP3Serializer.m_Aggregator.IExchangeAbsolutePosition( m_BP3Serializer.m_Data, r); if (m_BP3Serializer.m_Aggregator.m_IsConsumer) { const BufferSTL &bufferSTL = m_BP3Serializer.m_Aggregator.GetConsumerBuffer( m_BP3Serializer.m_Data); m_FileDataManager.WriteFiles(bufferSTL.m_Buffer.data(), bufferSTL.m_Position, transportIndex); m_FileDataManager.FlushFiles(transportIndex); } m_BP3Serializer.m_Aggregator.WaitAbsolutePosition( absolutePositionRequests, r); m_BP3Serializer.m_Aggregator.Wait(dataRequests, r); m_BP3Serializer.m_Aggregator.SwapBuffers(r); } m_BP3Serializer.UpdateOffsetsInMetadata(); if (isFinal) // Write metadata footer { BufferSTL &bufferSTL = m_BP3Serializer.m_Data; m_BP3Serializer.ResetBuffer(bufferSTL, false, false); m_BP3Serializer.AggregateCollectiveMetadata( m_BP3Serializer.m_Aggregator.m_Comm, bufferSTL, false); if (m_BP3Serializer.m_Aggregator.m_IsConsumer) { m_FileDataManager.WriteFiles(bufferSTL.m_Buffer.data(), bufferSTL.m_Position, transportIndex); m_FileDataManager.FlushFiles(transportIndex); } m_BP3Serializer.m_Aggregator.Close(); } m_BP3Serializer.m_Aggregator.ResetBuffers(); } #define declare_type(T, L) \ T *BP3Writer::DoBufferData_##L(const size_t payloadPosition, \ const size_t bufferID) noexcept \ { \ return BufferDataCommon<T>(payloadPosition, bufferID); \ } ADIOS2_FOREACH_PRIMITVE_STDTYPE_2ARGS(declare_type) #undef declare_type } // end namespace engine } // end namespace core } // end namespace adios2 <commit_msg>Fixing Bug when mixing deferred and sync mode<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * BP3Writer.cpp * * Created on: Dec 19, 2016 * Author: William F Godoy godoywf@ornl.gov */ #include "BP3Writer.h" #include "BP3Writer.tcc" #include "adios2/ADIOSMPI.h" #include "adios2/ADIOSMacros.h" #include "adios2/core/IO.h" #include "adios2/helper/adiosFunctions.h" //CheckIndexRange #include "adios2/toolkit/transport/file/FileFStream.h" namespace adios2 { namespace core { namespace engine { BP3Writer::BP3Writer(IO &io, const std::string &name, const Mode mode, MPI_Comm mpiComm) : Engine("BP3", io, name, mode, mpiComm), m_BP3Serializer(mpiComm, m_DebugMode), m_FileDataManager(mpiComm, m_DebugMode), m_FileMetadataManager(mpiComm, m_DebugMode) { m_IO.m_ReadStreaming = false; m_EndMessage = " in call to IO Open BPFileWriter " + m_Name + "\n"; Init(); } StepStatus BP3Writer::BeginStep(StepMode mode, const float timeoutSeconds) { m_BP3Serializer.m_DeferredVariables.clear(); m_BP3Serializer.m_DeferredVariablesDataSize = 0; m_IO.m_ReadStreaming = false; return StepStatus::OK; } size_t BP3Writer::CurrentStep() const { return m_BP3Serializer.m_MetadataSet.CurrentStep; } void BP3Writer::PerformPuts() { if (m_BP3Serializer.m_DeferredVariables.empty()) { return; } m_BP3Serializer.ResizeBuffer(m_BP3Serializer.m_DeferredVariablesDataSize, "in call to PerformPuts"); for (const std::string &variableName : m_BP3Serializer.m_DeferredVariables) { const std::string type = m_IO.InquireVariableType(variableName); if (type == "compound") { // not supported } #define declare_template_instantiation(T) \ else if (type == helper::GetType<T>()) \ { \ Variable<T> &variable = FindVariable<T>( \ variableName, "in call to PerformPuts, EndStep or Close"); \ PerformPutCommon(variable); \ } ADIOS2_FOREACH_PRIMITIVE_STDTYPE_1ARG(declare_template_instantiation) #undef declare_template_instantiation } m_BP3Serializer.m_DeferredVariables.clear(); } void BP3Writer::EndStep() { if (m_BP3Serializer.m_DeferredVariables.size() > 0) { PerformPuts(); } // true: advances step m_BP3Serializer.SerializeData(m_IO, true); const size_t currentStep = CurrentStep(); const size_t flushStepsCount = m_BP3Serializer.m_FlushStepsCount; if (currentStep % flushStepsCount == 0) { Flush(); } } void BP3Writer::Flush(const int transportIndex) { DoFlush(false, transportIndex); m_BP3Serializer.ResetBuffer(m_BP3Serializer.m_Data); if (m_BP3Serializer.m_CollectiveMetadata) { WriteCollectiveMetadataFile(); } } // PRIVATE void BP3Writer::Init() { InitParameters(); InitTransports(); InitBPBuffer(); } #define declare_type(T) \ void BP3Writer::DoPut(Variable<T> &variable, \ typename Variable<T>::Span &span, \ const size_t bufferID) \ { \ return PutCommon(variable, span, bufferID); \ } ADIOS2_FOREACH_PRIMITIVE_STDTYPE_1ARG(declare_type) #undef declare_type #define declare_type(T) \ void BP3Writer::DoPutSync(Variable<T> &variable, const T *data) \ { \ PutSyncCommon(variable, variable.SetBlockInfo(data, CurrentStep())); \ variable.m_BlocksInfo.pop_back(); \ } \ void BP3Writer::DoPutDeferred(Variable<T> &variable, const T *data) \ { \ PutDeferredCommon(variable, data); \ } ADIOS2_FOREACH_STDTYPE_1ARG(declare_type) #undef declare_type void BP3Writer::InitParameters() { m_BP3Serializer.InitParameters(m_IO.m_Parameters); } void BP3Writer::InitTransports() { // TODO need to add support for aggregators here later if (m_IO.m_TransportsParameters.empty()) { Params defaultTransportParameters; defaultTransportParameters["transport"] = "File"; m_IO.m_TransportsParameters.push_back(defaultTransportParameters); } // only consumers will interact with transport managers std::vector<std::string> bpSubStreamNames; if (m_BP3Serializer.m_Aggregator.m_IsConsumer) { // Names passed to IO AddTransport option with key "Name" const std::vector<std::string> transportsNames = m_FileDataManager.GetFilesBaseNames(m_Name, m_IO.m_TransportsParameters); // /path/name.bp.dir/name.bp.rank bpSubStreamNames = m_BP3Serializer.GetBPSubStreamNames(transportsNames); } m_BP3Serializer.ProfilerStart("mkdir"); m_FileDataManager.MkDirsBarrier(bpSubStreamNames, m_BP3Serializer.m_NodeLocal); m_BP3Serializer.ProfilerStop("mkdir"); if (m_BP3Serializer.m_Aggregator.m_IsConsumer) { m_FileDataManager.OpenFiles(bpSubStreamNames, m_OpenMode, m_IO.m_TransportsParameters, m_BP3Serializer.m_Profiler.IsActive); } } void BP3Writer::InitBPBuffer() { if (m_OpenMode == Mode::Append) { throw std::invalid_argument( "ADIOS2: OpenMode Append hasn't been implemented, yet"); // TODO: Get last pg timestep and update timestep counter in } else { m_BP3Serializer.PutProcessGroupIndex( m_IO.m_Name, m_IO.m_HostLanguage, m_FileDataManager.GetTransportsTypes()); } } void BP3Writer::DoFlush(const bool isFinal, const int transportIndex) { if (m_BP3Serializer.m_Aggregator.m_IsActive) { AggregateWriteData(isFinal, transportIndex); } else { WriteData(isFinal, transportIndex); } } void BP3Writer::DoClose(const int transportIndex) { if (m_BP3Serializer.m_DeferredVariables.size() > 0) { PerformPuts(); } DoFlush(true, transportIndex); if (m_BP3Serializer.m_Aggregator.m_IsConsumer) { m_FileDataManager.CloseFiles(transportIndex); } if (m_BP3Serializer.m_CollectiveMetadata && m_FileDataManager.AllTransportsClosed()) { WriteCollectiveMetadataFile(true); } if (m_BP3Serializer.m_Profiler.IsActive && m_FileDataManager.AllTransportsClosed()) { WriteProfilingJSONFile(); } } void BP3Writer::WriteProfilingJSONFile() { auto transportTypes = m_FileDataManager.GetTransportsTypes(); auto transportProfilers = m_FileDataManager.GetTransportsProfilers(); auto transportTypesMD = m_FileMetadataManager.GetTransportsTypes(); auto transportProfilersMD = m_FileMetadataManager.GetTransportsProfilers(); transportTypes.insert(transportTypes.end(), transportTypesMD.begin(), transportTypesMD.end()); transportProfilers.insert(transportProfilers.end(), transportProfilersMD.begin(), transportProfilersMD.end()); const std::string lineJSON(m_BP3Serializer.GetRankProfilingJSON( transportTypes, transportProfilers) + ",\n"); const std::vector<char> profilingJSON( m_BP3Serializer.AggregateProfilingJSON(lineJSON)); if (m_BP3Serializer.m_RankMPI == 0) { transport::FileFStream profilingJSONStream(m_MPIComm, m_DebugMode); auto bpBaseNames = m_BP3Serializer.GetBPBaseNames({m_Name}); profilingJSONStream.Open(bpBaseNames[0] + "/profiling.json", Mode::Write); profilingJSONStream.Write(profilingJSON.data(), profilingJSON.size()); profilingJSONStream.Close(); } } void BP3Writer::WriteCollectiveMetadataFile(const bool isFinal) { m_BP3Serializer.AggregateCollectiveMetadata( m_MPIComm, m_BP3Serializer.m_Metadata, true); if (m_BP3Serializer.m_RankMPI == 0) { // first init metadata files const std::vector<std::string> transportsNames = m_FileMetadataManager.GetFilesBaseNames( m_Name, m_IO.m_TransportsParameters); const std::vector<std::string> bpMetadataFileNames = m_BP3Serializer.GetBPMetadataFileNames(transportsNames); m_FileMetadataManager.OpenFiles(bpMetadataFileNames, m_OpenMode, m_IO.m_TransportsParameters, m_BP3Serializer.m_Profiler.IsActive); m_FileMetadataManager.WriteFiles( m_BP3Serializer.m_Metadata.m_Buffer.data(), m_BP3Serializer.m_Metadata.m_Position); m_FileMetadataManager.CloseFiles(); if (!isFinal) { m_BP3Serializer.ResetBuffer(m_BP3Serializer.m_Metadata, true); m_FileMetadataManager.m_Transports.clear(); } } } void BP3Writer::WriteData(const bool isFinal, const int transportIndex) { size_t dataSize = m_BP3Serializer.m_Data.m_Position; if (isFinal) { m_BP3Serializer.CloseData(m_IO); dataSize = m_BP3Serializer.m_Data.m_Position; } else { m_BP3Serializer.CloseStream(m_IO); } m_FileDataManager.WriteFiles(m_BP3Serializer.m_Data.m_Buffer.data(), dataSize, transportIndex); m_FileDataManager.FlushFiles(transportIndex); } void BP3Writer::AggregateWriteData(const bool isFinal, const int transportIndex) { m_BP3Serializer.CloseStream(m_IO, false); // async? for (int r = 0; r < m_BP3Serializer.m_Aggregator.m_Size; ++r) { std::vector<MPI_Request> dataRequests = m_BP3Serializer.m_Aggregator.IExchange(m_BP3Serializer.m_Data, r); std::vector<MPI_Request> absolutePositionRequests = m_BP3Serializer.m_Aggregator.IExchangeAbsolutePosition( m_BP3Serializer.m_Data, r); if (m_BP3Serializer.m_Aggregator.m_IsConsumer) { const BufferSTL &bufferSTL = m_BP3Serializer.m_Aggregator.GetConsumerBuffer( m_BP3Serializer.m_Data); m_FileDataManager.WriteFiles(bufferSTL.m_Buffer.data(), bufferSTL.m_Position, transportIndex); m_FileDataManager.FlushFiles(transportIndex); } m_BP3Serializer.m_Aggregator.WaitAbsolutePosition( absolutePositionRequests, r); m_BP3Serializer.m_Aggregator.Wait(dataRequests, r); m_BP3Serializer.m_Aggregator.SwapBuffers(r); } m_BP3Serializer.UpdateOffsetsInMetadata(); if (isFinal) // Write metadata footer { BufferSTL &bufferSTL = m_BP3Serializer.m_Data; m_BP3Serializer.ResetBuffer(bufferSTL, false, false); m_BP3Serializer.AggregateCollectiveMetadata( m_BP3Serializer.m_Aggregator.m_Comm, bufferSTL, false); if (m_BP3Serializer.m_Aggregator.m_IsConsumer) { m_FileDataManager.WriteFiles(bufferSTL.m_Buffer.data(), bufferSTL.m_Position, transportIndex); m_FileDataManager.FlushFiles(transportIndex); } m_BP3Serializer.m_Aggregator.Close(); } m_BP3Serializer.m_Aggregator.ResetBuffers(); } #define declare_type(T, L) \ T *BP3Writer::DoBufferData_##L(const size_t payloadPosition, \ const size_t bufferID) noexcept \ { \ return BufferDataCommon<T>(payloadPosition, bufferID); \ } ADIOS2_FOREACH_PRIMITVE_STDTYPE_2ARGS(declare_type) #undef declare_type } // end namespace engine } // end namespace core } // end namespace adios2 <|endoftext|>
<commit_before>#include "timeline.h" #include <iostream> #include <cassert> #include <sstream> #include <QPainter> #include <QMouseEvent> using std::cout; using std::endl; Timeline::Timeline(QWidget* parent) : QWidget(parent), m_range(0, 100), m_value(0), m_tickDistance(8), m_labelDistance(80) { setMinimumHeight(40); } Timeline::~Timeline() { } int Timeline::positionFromValue(float value) const { return round((value - m_range.first) / (m_range.second - m_range.first) * (float)width()); } float Timeline::valueFromPosition(int pos) const { return (float)pos / (float)width() * (m_range.second - m_range.first) + m_range.first; } void Timeline::paintEvent(QPaintEvent * event) { QPainter painter(this); // fill the background painter.setBrush(QColor(20,20,20)); painter.setPen(QColor(20,20,20)); painter.drawRect(rect()); // get the font properties const QFontMetrics metrics(font()); // draw the ticks { painter.setPen(QColor(64,64,64)); unsigned end = floor(m_range.second); unsigned step = tickSkip(m_tickDistance); for(unsigned a=ceil(m_range.first); a < end; a += step) { const int pos = positionFromValue(a); painter.drawLine(pos, metrics.height()+6, pos, height()); } } // draw the units { painter.setPen(QColor(128,128,128)); unsigned end = floor(m_range.second); unsigned step = tickSkip(m_labelDistance); for(unsigned a=ceil(m_range.first); a < end; a += step) { const int pos = positionFromValue(a); painter.drawLine(pos, metrics.height()+2, pos, height()); std::stringstream label; label << a; painter.drawText(pos, metrics.height(), label.str().c_str()); } } // draw the current value QPen pen(QColor(255, 128, 0), 3); painter.setPen(pen); const int pos = positionFromValue(m_value); painter.drawLine(pos, 0, pos, height()); // painter.setFont(font()); } void Timeline::setRange(std::pair<float, float> range) { m_range = range; m_value = std::min(std::max(m_value, m_range.first), m_range.second); repaint(); } const std::pair<float, float>& Timeline::range() const { return m_range; } void Timeline::setValue(float val) { m_value = std::min(std::max(val, m_range.first), m_range.second); repaint(); } float Timeline::value() const { return m_value; } void Timeline::mousePressEvent(QMouseEvent * event) { if(event->button() == Qt::LeftButton) { const float value = valueFromPosition(event->x()); setValue(value); emit valueChanged(value); } else QWidget::mousePressEvent(event); } void Timeline::mouseMoveEvent(QMouseEvent * event) { if(event->buttons() & Qt::LeftButton) { const float value = valueFromPosition(event->x()); setValue(value); emit valueChanged(value); } else QWidget::mouseMoveEvent(event); } void Timeline::setTickDistance(unsigned dist) { assert(dist > 0); m_tickDistance = dist; } unsigned Timeline::tickDistance() const { return m_tickDistance; } void Timeline::setLabelDistance(unsigned dist) { assert(dist > 0); m_labelDistance = dist; } unsigned Timeline::labelDistance() const { return m_labelDistance; } unsigned Timeline::tickSkip(unsigned dist) const { // crazy cases if(m_range.second - m_range.first < 1.0f) return 1; // compute the mantissa and exponent const float singleTickDist = (m_range.second - m_range.first) * (float)dist / (float)width(); const int exponent = floor(log10(singleTickDist)); const float mantissa = singleTickDist / pow(10.0f, exponent); // enough space = just draw all sticks if(exponent < 0) return 1; const float d1 = std::abs(1.0f - mantissa); const float d2 = std::abs(2.0f - mantissa); const float d5 = std::abs(5.0f - mantissa); const float d10 = std::abs(10.0f - mantissa); unsigned m; if((d1 <= d2) && (d1 <= d5) && (d1 <= d10)) m = 1; else if((d2 <= d1) && (d2 <= d5) && (d2 <= d10)) m = 2; else if((d5 <= d1) && (d5 <= d2) && (d5 <= d10)) m = 5; else m = 10; return m * pow(10, exponent); } <commit_msg>Fixed timeline's range when moving outside the widget's area<commit_after>#include "timeline.h" #include <iostream> #include <cassert> #include <sstream> #include <QPainter> #include <QMouseEvent> using std::cout; using std::endl; Timeline::Timeline(QWidget* parent) : QWidget(parent), m_range(0, 100), m_value(0), m_tickDistance(8), m_labelDistance(80) { setMinimumHeight(40); } Timeline::~Timeline() { } int Timeline::positionFromValue(float value) const { return round((value - m_range.first) / (m_range.second - m_range.first) * (float)width()); } float Timeline::valueFromPosition(int pos) const { const float val = (float)pos / (float)width() * (m_range.second - m_range.first) + m_range.first; return std::max(std::min(val, m_range.second), m_range.first); } void Timeline::paintEvent(QPaintEvent * event) { QPainter painter(this); // fill the background painter.setBrush(QColor(20,20,20)); painter.setPen(QColor(20,20,20)); painter.drawRect(rect()); // get the font properties const QFontMetrics metrics(font()); // draw the ticks { painter.setPen(QColor(64,64,64)); unsigned end = floor(m_range.second); unsigned step = tickSkip(m_tickDistance); for(unsigned a=ceil(m_range.first); a < end; a += step) { const int pos = positionFromValue(a); painter.drawLine(pos, metrics.height()+6, pos, height()); } } // draw the units { painter.setPen(QColor(128,128,128)); unsigned end = floor(m_range.second); unsigned step = tickSkip(m_labelDistance); for(unsigned a=ceil(m_range.first); a < end; a += step) { const int pos = positionFromValue(a); painter.drawLine(pos, metrics.height()+2, pos, height()); std::stringstream label; label << a; painter.drawText(pos, metrics.height(), label.str().c_str()); } } // draw the current value QPen pen(QColor(255, 128, 0), 3); painter.setPen(pen); const int pos = positionFromValue(m_value); painter.drawLine(pos, 0, pos, height()); // painter.setFont(font()); } void Timeline::setRange(std::pair<float, float> range) { m_range = range; m_value = std::min(std::max(m_value, m_range.first), m_range.second); repaint(); } const std::pair<float, float>& Timeline::range() const { return m_range; } void Timeline::setValue(float val) { m_value = std::min(std::max(val, m_range.first), m_range.second); repaint(); } float Timeline::value() const { return m_value; } void Timeline::mousePressEvent(QMouseEvent * event) { if(event->button() == Qt::LeftButton) { const float value = valueFromPosition(event->x()); setValue(value); emit valueChanged(value); } else QWidget::mousePressEvent(event); } void Timeline::mouseMoveEvent(QMouseEvent * event) { if(event->buttons() & Qt::LeftButton) { const float value = valueFromPosition(event->x()); setValue(value); emit valueChanged(value); } else QWidget::mouseMoveEvent(event); } void Timeline::setTickDistance(unsigned dist) { assert(dist > 0); m_tickDistance = dist; } unsigned Timeline::tickDistance() const { return m_tickDistance; } void Timeline::setLabelDistance(unsigned dist) { assert(dist > 0); m_labelDistance = dist; } unsigned Timeline::labelDistance() const { return m_labelDistance; } unsigned Timeline::tickSkip(unsigned dist) const { // crazy cases if(m_range.second - m_range.first < 1.0f) return 1; // compute the mantissa and exponent const float singleTickDist = (m_range.second - m_range.first) * (float)dist / (float)width(); const int exponent = floor(log10(singleTickDist)); const float mantissa = singleTickDist / pow(10.0f, exponent); // enough space = just draw all sticks if(exponent < 0) return 1; const float d1 = std::abs(1.0f - mantissa); const float d2 = std::abs(2.0f - mantissa); const float d5 = std::abs(5.0f - mantissa); const float d10 = std::abs(10.0f - mantissa); unsigned m; if((d1 <= d2) && (d1 <= d5) && (d1 <= d10)) m = 1; else if((d2 <= d1) && (d2 <= d5) && (d2 <= d10)) m = 2; else if((d5 <= d1) && (d5 <= d2) && (d5 <= d10)) m = 5; else m = 10; return m * pow(10, exponent); } <|endoftext|>
<commit_before>/* * Vulkan device class * * Encapsulates a physical Vulkan device and it's logical representation * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #pragma once #include <exception> #include "vulkan/vulkan.h" #include "vulkantools.h" #include "vulkanbuffer.hpp" namespace vk { struct VulkanDevice { /** @brief Physical device representation */ VkPhysicalDevice physicalDevice; /** @brief Logical device representation (application's view of the device) */ VkDevice logicalDevice; /** @brief Properties of the physical device including limits that the application can check against */ VkPhysicalDeviceProperties properties; /** @brief Features of the physical device that an application can use to check if a feature is supported */ VkPhysicalDeviceFeatures features; /** @brief Memory types and heaps of the physical device */ VkPhysicalDeviceMemoryProperties memoryProperties; /** @brief Set to true when the debug marker extension is detected */ bool enableDebugMarkers = false; /** * Default constructor * * @param physicalDevice Phyiscal device that is to be used */ VulkanDevice(VkPhysicalDevice physicalDevice) { assert(physicalDevice); this->physicalDevice = physicalDevice; // Store Properties features, limits and properties of the physical device for later use // Device properties also contain limits and sparse properties vkGetPhysicalDeviceProperties(physicalDevice, &properties); // Features should be checked by the examples before using them vkGetPhysicalDeviceFeatures(physicalDevice, &features); // Memory properties are used regularly for creating all kinds of buffer vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memoryProperties); } /** * Default destructor * * @note Frees the logical device */ ~VulkanDevice() { if (logicalDevice) { vkDestroyDevice(logicalDevice, nullptr); } } /** * Get the index of a memory type that has all the requested property bits set * * @param typeBits Bitmask with bits set for each memory type supported by the resource to request for (from VkMemoryRequirements) * @param properties Bitmask of properties for the memory type to request * * @return Index of the requested memory type * * @throw Throws an exception if no memory type could be found that supports the requested properties */ uint32_t getMemoryType(uint32_t typeBits, VkMemoryPropertyFlags properties) { for (uint32_t i = 0; i < memoryProperties.memoryTypeCount; i++) { if ((typeBits & 1) == 1) { if ((memoryProperties.memoryTypes[i].propertyFlags & properties) == properties) { return i; } } typeBits >>= 1; } #if defined(__ANDROID__) //todo : Exceptions are disabled by default on Android (need to add LOCAL_CPP_FEATURES += exceptions to Android.mk), so for now just return zero return 0; #else throw std::runtime_error("Could not find a matching memory type"); #endif } /** * Create the logical device based on the assigned physical device * * @param queueCreateInfos A vector containing queue create infos for all queues to be requested on the device * @param enabledFeatures Can be used to enable certain features upon device creation * @param useSwapChain Set to false for headless rendering to omit the swapchain device extensions * * @return VkResult of the device creation call */ VkResult createLogicalDevice(std::vector<VkDeviceQueueCreateInfo> &queueCreateInfos, VkPhysicalDeviceFeatures enabledFeatures, bool useSwapChain = true) { // Create the logical device representation std::vector<const char*> deviceExtensions; if (useSwapChain) { // If the device will be used for presenting to a display via a swapchain // we need to request the swapchain extension deviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); } VkDeviceCreateInfo deviceCreateInfo = {}; deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; deviceCreateInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());; deviceCreateInfo.pQueueCreateInfos = queueCreateInfos.data(); deviceCreateInfo.pEnabledFeatures = &enabledFeatures; // Cnable the debug marker extension if it is present (likely meaning a debugging tool is present) if (vkTools::checkDeviceExtensionPresent(physicalDevice, VK_EXT_DEBUG_MARKER_EXTENSION_NAME)) { deviceExtensions.push_back(VK_EXT_DEBUG_MARKER_EXTENSION_NAME); enableDebugMarkers = true; } if (deviceExtensions.size() > 0) { deviceCreateInfo.enabledExtensionCount = (uint32_t)deviceExtensions.size(); deviceCreateInfo.ppEnabledExtensionNames = deviceExtensions.data(); } return vkCreateDevice(physicalDevice, &deviceCreateInfo, nullptr, &logicalDevice); } /** * Create a buffer on the device * * @param usageFlags Usage flag bitmask for the buffer (i.e. index, vertex, uniform buffer) * @param memoryPropertyFlags Memory properties for this buffer (i.e. device local, host visible, coherent) * @param size Size of the buffer in byes * @param buffer Pointer to the buffer handle acquired by the function * @param memory Pointer to the memory handle acquired by the function * @param data Pointer to the data that should be copied to the buffer after creation (optional, if not set, no data is copied over) * * @return VK_SUCCESS if buffer handle and memory have been created and (optionally passed) data has been copied */ VkResult createBuffer(VkBufferUsageFlags usageFlags, VkMemoryPropertyFlags memoryPropertyFlags, VkDeviceSize size, VkBuffer *buffer, VkDeviceMemory *memory, void *data = nullptr) { // Create the buffer handle VkBufferCreateInfo bufferCreateInfo = vkTools::initializers::bufferCreateInfo(usageFlags, size); VK_CHECK_RESULT(vkCreateBuffer(logicalDevice, &bufferCreateInfo, nullptr, buffer)); // Create the memory backing up the buffer handle VkMemoryRequirements memReqs; VkMemoryAllocateInfo memAlloc = vkTools::initializers::memoryAllocateInfo(); vkGetBufferMemoryRequirements(logicalDevice, *buffer, &memReqs); memAlloc.allocationSize = memReqs.size; // Find a memory type index that fits the properties of the buffer memAlloc.memoryTypeIndex = getMemoryType(memReqs.memoryTypeBits, memoryPropertyFlags); VK_CHECK_RESULT(vkAllocateMemory(logicalDevice, &memAlloc, nullptr, memory)); // If a pointer to the buffer data has been passed, map the buffer and copy over the data if (data != nullptr) { void *mapped; VK_CHECK_RESULT(vkMapMemory(logicalDevice, *memory, 0, size, 0, &mapped)); memcpy(mapped, data, size); vkUnmapMemory(logicalDevice, *memory); } // Attach the memory to the buffer object VK_CHECK_RESULT(vkBindBufferMemory(logicalDevice, *buffer, *memory, 0)); return VK_SUCCESS; } /** * Create a buffer on the device * * @param usageFlags Usage flag bitmask for the buffer (i.e. index, vertex, uniform buffer) * @param memoryPropertyFlags Memory properties for this buffer (i.e. device local, host visible, coherent) * @param buffer Pointer to a vk::Vulkan buffer object * @param size Size of the buffer in byes * @param data Pointer to the data that should be copied to the buffer after creation (optional, if not set, no data is copied over) * * @return VK_SUCCESS if buffer handle and memory have been created and (optionally passed) data has been copied */ VkResult createBuffer(VkBufferUsageFlags usageFlags, VkMemoryPropertyFlags memoryPropertyFlags, vk::Buffer *buffer, VkDeviceSize size, void *data = nullptr) { buffer->device = logicalDevice; // Create the buffer handle VkBufferCreateInfo bufferCreateInfo = vkTools::initializers::bufferCreateInfo(usageFlags, size); VK_CHECK_RESULT(vkCreateBuffer(logicalDevice, &bufferCreateInfo, nullptr, &buffer->buffer)); // Create the memory backing up the buffer handle VkMemoryRequirements memReqs; VkMemoryAllocateInfo memAlloc = vkTools::initializers::memoryAllocateInfo(); vkGetBufferMemoryRequirements(logicalDevice, buffer->buffer, &memReqs); memAlloc.allocationSize = memReqs.size; // Find a memory type index that fits the properties of the buffer memAlloc.memoryTypeIndex = getMemoryType(memReqs.memoryTypeBits, memoryPropertyFlags); VK_CHECK_RESULT(vkAllocateMemory(logicalDevice, &memAlloc, nullptr, &buffer->memory)); buffer->alignment = memReqs.alignment; buffer->size = memAlloc.allocationSize; buffer->usageFlags = usageFlags; buffer->memoryPropertyFlags = memoryPropertyFlags; // If a pointer to the buffer data has been passed, map the buffer and copy over the data if (data != nullptr) { VK_CHECK_RESULT(buffer->map()); memcpy(buffer->mapped, data, size); buffer->unmap(); } // Initialize a default descriptor that covers the whole buffer size buffer->setupDescriptor(); // Attach the memory to the buffer object return buffer->bind(); } }; } <commit_msg>Queue family index stuff moved to VulkanDevice class<commit_after>/* * Vulkan device class * * Encapsulates a physical Vulkan device and it's logical representation * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #pragma once #include <exception> #include "vulkan/vulkan.h" #include "vulkantools.h" #include "vulkanbuffer.hpp" namespace vk { struct VulkanDevice { /** @brief Physical device representation */ VkPhysicalDevice physicalDevice; /** @brief Logical device representation (application's view of the device) */ VkDevice logicalDevice; /** @brief Properties of the physical device including limits that the application can check against */ VkPhysicalDeviceProperties properties; /** @brief Features of the physical device that an application can use to check if a feature is supported */ VkPhysicalDeviceFeatures features; /** @brief Memory types and heaps of the physical device */ VkPhysicalDeviceMemoryProperties memoryProperties; /** @brief Set to true when the debug marker extension is detected */ bool enableDebugMarkers = false; /** @brief Contains queue family indices */ struct { uint32_t graphics = 0; uint32_t compute = 0; } queueFamilyIndices; /** * Default constructor * * @param physicalDevice Phyiscal device that is to be used */ VulkanDevice(VkPhysicalDevice physicalDevice) { assert(physicalDevice); this->physicalDevice = physicalDevice; // Store Properties features, limits and properties of the physical device for later use // Device properties also contain limits and sparse properties vkGetPhysicalDeviceProperties(physicalDevice, &properties); // Features should be checked by the examples before using them vkGetPhysicalDeviceFeatures(physicalDevice, &features); // Memory properties are used regularly for creating all kinds of buffer vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memoryProperties); } /** * Default destructor * * @note Frees the logical device */ ~VulkanDevice() { if (logicalDevice) { vkDestroyDevice(logicalDevice, nullptr); } } /** * Get the index of a memory type that has all the requested property bits set * * @param typeBits Bitmask with bits set for each memory type supported by the resource to request for (from VkMemoryRequirements) * @param properties Bitmask of properties for the memory type to request * * @return Index of the requested memory type * * @throw Throws an exception if no memory type could be found that supports the requested properties */ uint32_t getMemoryType(uint32_t typeBits, VkMemoryPropertyFlags properties) { for (uint32_t i = 0; i < memoryProperties.memoryTypeCount; i++) { if ((typeBits & 1) == 1) { if ((memoryProperties.memoryTypes[i].propertyFlags & properties) == properties) { return i; } } typeBits >>= 1; } #if defined(__ANDROID__) //todo : Exceptions are disabled by default on Android (need to add LOCAL_CPP_FEATURES += exceptions to Android.mk), so for now just return zero return 0; #else throw std::runtime_error("Could not find a matching memory type"); #endif } /** * Get the index of a queue family that supports the requested queue flags * * @param queueFlags Queue flags to find a queue family index for * * @return INdex * * @throw Throws an exception if no queue family index could be found that supports the requested flags */ uint32_t getQueueFamiliyIndex(VkQueueFlagBits queueFlags) { uint32_t queueIndex; uint32_t queueCount; // Get number of available queue families on this device vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueCount, NULL); assert(queueCount >= 1); // Get available queue families std::vector<VkQueueFamilyProperties> queueProps; queueProps.resize(queueCount); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueCount, queueProps.data()); for (uint32_t i = 0; i < queueCount; i++) { if (queueProps[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { return i; break; } } // todo: Advanced search for devices that have dedicated queues for compute and transfer // Try to find queues with only the requested flags or (if not present) with as few // other flags set as possible (example: http://vulkan.gpuinfo.org/displayreport.php?id=509#queuefamilies) #if defined(__ANDROID__) //todo : Exceptions are disabled by default on Android (need to add LOCAL_CPP_FEATURES += exceptions to Android.mk), so for now just return zero return 0; #else throw std::runtime_error("Could not find a matching queue family index"); #endif } /** * Create the logical device based on the assigned physical device * * @param queueCreateInfos A vector containing queue create infos for all queues to be requested on the device * @param enabledFeatures Can be used to enable certain features upon device creation * @param useSwapChain Set to false for headless rendering to omit the swapchain device extensions * * @return VkResult of the device creation call */ VkResult createLogicalDevice(std::vector<VkDeviceQueueCreateInfo> &queueCreateInfos, VkPhysicalDeviceFeatures enabledFeatures, bool useSwapChain = true) { // Create the logical device representation std::vector<const char*> deviceExtensions; if (useSwapChain) { // If the device will be used for presenting to a display via a swapchain // we need to request the swapchain extension deviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); } VkDeviceCreateInfo deviceCreateInfo = {}; deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; deviceCreateInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());; deviceCreateInfo.pQueueCreateInfos = queueCreateInfos.data(); deviceCreateInfo.pEnabledFeatures = &enabledFeatures; // Cnable the debug marker extension if it is present (likely meaning a debugging tool is present) if (vkTools::checkDeviceExtensionPresent(physicalDevice, VK_EXT_DEBUG_MARKER_EXTENSION_NAME)) { deviceExtensions.push_back(VK_EXT_DEBUG_MARKER_EXTENSION_NAME); enableDebugMarkers = true; } if (deviceExtensions.size() > 0) { deviceCreateInfo.enabledExtensionCount = (uint32_t)deviceExtensions.size(); deviceCreateInfo.ppEnabledExtensionNames = deviceExtensions.data(); } return vkCreateDevice(physicalDevice, &deviceCreateInfo, nullptr, &logicalDevice); } /** * Create the logical device based on the assigned physical device * * @note Using this overload will implicitly get default queue family indices for graphics and compute * * @param enabledFeatures Can be used to enable certain features upon device creation * @param useSwapChain Set to false for headless rendering to omit the swapchain device extensions * * @return VkResult of the device creation call */ VkResult createLogicalDevice(VkPhysicalDeviceFeatures enabledFeatures, bool useSwapChain = true) { // Get queue family indices for graphics and compute // Note that the indices may overlap depending on the implementation queueFamilyIndices.graphics = getQueueFamiliyIndex(VK_QUEUE_GRAPHICS_BIT); queueFamilyIndices.compute = getQueueFamiliyIndex(VK_QUEUE_COMPUTE_BIT); //todo: Transfer? // Pass queue information for graphics and compute, so examples can later on request queues from both std::vector<float> queuePriorities; std::vector<VkDeviceQueueCreateInfo> queueCreateInfos{}; // We need one queue create info per queue family index // If graphics and compute share the same queue family index we only need one queue create info but // with two queues to request queueCreateInfos.resize(1); queuePriorities.resize(1, 0.0f); // Graphics queueCreateInfos[0] = {}; queueCreateInfos[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfos[0].queueFamilyIndex = queueFamilyIndices.graphics; queueCreateInfos[0].queueCount = 1; queueCreateInfos[0].pQueuePriorities = queuePriorities.data(); // Compute // If compute has a different queue family index, add another create info, else just add if (queueFamilyIndices.graphics != queueFamilyIndices.compute) { queueCreateInfos.resize(2); queueCreateInfos[1] = {}; queueCreateInfos[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfos[1].queueFamilyIndex = queueFamilyIndices.compute; queueCreateInfos[1].queueCount = 1; queueCreateInfos[1].pQueuePriorities = queuePriorities.data(); } else { queueCreateInfos[0].queueCount++; queuePriorities.push_back(0.0f); } return createLogicalDevice(queueCreateInfos, enabledFeatures, useSwapChain); } /** * Create a buffer on the device * * @param usageFlags Usage flag bitmask for the buffer (i.e. index, vertex, uniform buffer) * @param memoryPropertyFlags Memory properties for this buffer (i.e. device local, host visible, coherent) * @param size Size of the buffer in byes * @param buffer Pointer to the buffer handle acquired by the function * @param memory Pointer to the memory handle acquired by the function * @param data Pointer to the data that should be copied to the buffer after creation (optional, if not set, no data is copied over) * * @return VK_SUCCESS if buffer handle and memory have been created and (optionally passed) data has been copied */ VkResult createBuffer(VkBufferUsageFlags usageFlags, VkMemoryPropertyFlags memoryPropertyFlags, VkDeviceSize size, VkBuffer *buffer, VkDeviceMemory *memory, void *data = nullptr) { // Create the buffer handle VkBufferCreateInfo bufferCreateInfo = vkTools::initializers::bufferCreateInfo(usageFlags, size); VK_CHECK_RESULT(vkCreateBuffer(logicalDevice, &bufferCreateInfo, nullptr, buffer)); // Create the memory backing up the buffer handle VkMemoryRequirements memReqs; VkMemoryAllocateInfo memAlloc = vkTools::initializers::memoryAllocateInfo(); vkGetBufferMemoryRequirements(logicalDevice, *buffer, &memReqs); memAlloc.allocationSize = memReqs.size; // Find a memory type index that fits the properties of the buffer memAlloc.memoryTypeIndex = getMemoryType(memReqs.memoryTypeBits, memoryPropertyFlags); VK_CHECK_RESULT(vkAllocateMemory(logicalDevice, &memAlloc, nullptr, memory)); // If a pointer to the buffer data has been passed, map the buffer and copy over the data if (data != nullptr) { void *mapped; VK_CHECK_RESULT(vkMapMemory(logicalDevice, *memory, 0, size, 0, &mapped)); memcpy(mapped, data, size); vkUnmapMemory(logicalDevice, *memory); } // Attach the memory to the buffer object VK_CHECK_RESULT(vkBindBufferMemory(logicalDevice, *buffer, *memory, 0)); return VK_SUCCESS; } /** * Create a buffer on the device * * @param usageFlags Usage flag bitmask for the buffer (i.e. index, vertex, uniform buffer) * @param memoryPropertyFlags Memory properties for this buffer (i.e. device local, host visible, coherent) * @param buffer Pointer to a vk::Vulkan buffer object * @param size Size of the buffer in byes * @param data Pointer to the data that should be copied to the buffer after creation (optional, if not set, no data is copied over) * * @return VK_SUCCESS if buffer handle and memory have been created and (optionally passed) data has been copied */ VkResult createBuffer(VkBufferUsageFlags usageFlags, VkMemoryPropertyFlags memoryPropertyFlags, vk::Buffer *buffer, VkDeviceSize size, void *data = nullptr) { buffer->device = logicalDevice; // Create the buffer handle VkBufferCreateInfo bufferCreateInfo = vkTools::initializers::bufferCreateInfo(usageFlags, size); VK_CHECK_RESULT(vkCreateBuffer(logicalDevice, &bufferCreateInfo, nullptr, &buffer->buffer)); // Create the memory backing up the buffer handle VkMemoryRequirements memReqs; VkMemoryAllocateInfo memAlloc = vkTools::initializers::memoryAllocateInfo(); vkGetBufferMemoryRequirements(logicalDevice, buffer->buffer, &memReqs); memAlloc.allocationSize = memReqs.size; // Find a memory type index that fits the properties of the buffer memAlloc.memoryTypeIndex = getMemoryType(memReqs.memoryTypeBits, memoryPropertyFlags); VK_CHECK_RESULT(vkAllocateMemory(logicalDevice, &memAlloc, nullptr, &buffer->memory)); buffer->alignment = memReqs.alignment; buffer->size = memAlloc.allocationSize; buffer->usageFlags = usageFlags; buffer->memoryPropertyFlags = memoryPropertyFlags; // If a pointer to the buffer data has been passed, map the buffer and copy over the data if (data != nullptr) { VK_CHECK_RESULT(buffer->map()); memcpy(buffer->mapped, data, size); buffer->unmap(); } // Initialize a default descriptor that covers the whole buffer size buffer->setupDescriptor(); // Attach the memory to the buffer object return buffer->bind(); } }; } <|endoftext|>