text
stringlengths
54
60.6k
<commit_before>/* Copyright (c) 2017, CNRS-LAAS All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <pybind11/pybind11.h> #include <pybind11/stl.h> // for conversions between c++ and python collections #include <pybind11/numpy.h> // support for numpy arrays #include "core/structures/trajectory.h" #include "raster.h" #include "vns/factory.h" namespace py = pybind11; /** Converts a numpy array to a vector */ template<class T> std::vector<T> as_vector(py::array_t<T, py::array::c_style | py::array::forcecast> array) { std::vector<T> data(array.size()); for(ssize_t x=0; x<array.shape(0); x++) { for(ssize_t y=0; y<array.shape(1); y++) { data[x + y*array.shape(0)] = *(array.data(x, y)); } } return data; } /** Converts a vector to a 2D numpy array. */ template<class T> py::array_t<T> as_nparray(std::vector<T> vec, size_t x_width, size_t y_height) { ASSERT(vec.size() == x_width * y_height) py::array_t<T, py::array::c_style | py::array::forcecast> array(std::vector<size_t> {x_width, y_height}); auto s_x_width = static_cast<ssize_t>(x_width); auto s_y_height = static_cast<ssize_t>(y_height); for(ssize_t x=0; x<s_x_width; x++) { for (ssize_t y = 0; y < s_y_height; y++) { *(array.mutable_data(x, y)) = vec[x + y*x_width]; } } return array; } PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>); PYBIND11_MODULE(uav_planning, m) { m.doc() = "Python module for UAV trajectory planning"; srand(0); py::class_<DRaster>(m, "DRaster") .def(py::init([](py::array_t<double, py::array::c_style | py::array::forcecast> arr, double x_offset, double y_offset, double cell_width) { return new DRaster(as_vector<double>(arr), arr.shape(0), arr.shape(1), x_offset, y_offset, cell_width); })) .def("as_numpy", [](DRaster& self) { return as_nparray<double>(self.data, self.x_width, self.y_height); }) .def_readonly("x_offset", &DRaster::x_offset) .def_readonly("y_offset", &DRaster::y_offset) .def_readonly("cell_width", &DRaster::cell_width); py::class_<LRaster>(m, "LRaster") .def(py::init([](py::array_t<long, py::array::c_style | py::array::forcecast> arr, double x_offset, double y_offset, double cell_width) { return new LRaster(as_vector<long>(arr), arr.shape(0), arr.shape(1), x_offset, y_offset, cell_width); })) .def("as_numpy", [](LRaster& self) { return as_nparray<long>(self.data, self.x_width, self.y_height); }) .def_readonly("x_offset", &LRaster::x_offset) .def_readonly("y_offset", &LRaster::y_offset) .def_readonly("cell_width", &LRaster::cell_width); py::class_<TimeWindow>(m, "TimeWindow") .def(py::init<const double, const double>(), py::arg("start"), py::arg("end")) .def_readonly("start", &TimeWindow::start) .def_readonly("end", &TimeWindow::end) .def("__repr__", [](const TimeWindow &tw) { std::stringstream repr; repr << "TimeWindow(" << tw.start << ", " << tw.end << ")"; return repr.str(); } ) .def("as_tuple", [](TimeWindow &self) { return py::make_tuple(self.start, self.end); } ); py::class_<Cell>(m, "Cell") .def(py::init<const size_t, const size_t>(), py::arg("x"), py::arg("y")) .def_readonly("x", &Cell::x) .def_readonly("y", &Cell::y) .def("__repr__", [](const Cell &c) { std::stringstream repr; repr << "Cell(" << c.x << ", " << c.y << ")"; return repr.str(); } ) .def("as_tuple", [](Cell &self) { return py::make_tuple(self.x, self.y); } ); py::class_<Position>(m, "Position2d") .def(py::init<double, double>(), py::arg("x"), py::arg("y")) .def_readonly("x", &Position::x) .def_readonly("y", &Position::y) .def("__repr__", [](const Position &p) { std::stringstream repr; repr << "Position2d(" << p.x << ", " << p.y << ")"; return repr.str(); } ) .def("as_tuple", [](Position &self) { return py::make_tuple(self.x, self.y); } ); py::class_<Position3d>(m, "Position") .def(py::init<double, double, double>(), py::arg("x"), py::arg("y"), py::arg("z")) .def_readonly("x", &Position3d::x) .def_readonly("y", &Position3d::y) .def_readonly("z", &Position3d::z) .def("__repr__", [](const Position3d &p) { std::stringstream repr; repr << "Position(" << p.x << ", " << p.y << ", " << p.z << ")"; return repr.str(); } ) .def("as_tuple", [](Position3d &self) { return py::make_tuple(self.x, self.y, self.z); } ); py::class_<PositionTime>(m, "Position2dTime") .def(py::init<Position, double>(), py::arg("point"), py::arg("time")) .def_readonly("pt", &PositionTime::pt) .def_readonly("y", &PositionTime::time) .def("__repr__", [](const PositionTime &p) { std::stringstream repr; repr << "Position2dTime(" << p.pt.x << ", " << p.pt.y << ", " << p.time << ")"; return repr.str(); } ) .def("as_tuple", [](PositionTime &self) { return py::make_tuple(py::make_tuple(self.pt.x, self.pt.y), self.time); } ); py::class_<Position3dTime>(m, "PositionTime") .def(py::init<Position3d, double>(), py::arg("point"), py::arg("time")) .def_readonly("pt", &Position3dTime::pt) .def_readonly("y", &Position3dTime::time) .def("__repr__", [](const Position3dTime &p) { std::stringstream repr; repr << "PositionTime(" << p.pt.x << ", " << p.pt.y << ", " << p.pt.z << ", " << p.time << ")"; return repr.str(); } ) .def("as_tuple", [](Position3dTime &self) { return py::make_tuple(py::make_tuple(self.pt.x, self.pt.y, self.pt.z), self.time); } ); py::class_<FireData>(m, "FireData") .def(py::init<DRaster&, DiscreteDRaster&>(), py::arg("ignitions"), py::arg("elevation")) .def_readonly("ignitions", &FireData::ignitions) .def_readonly("traversal_end", &FireData::traversal_end) .def_readonly("propagation_directions", &FireData::propagation_directions) .def_readonly("elevation", &FireData::elevation); // .def_readonly_static("isochrone_timespan", &FireData::isochrone_timespan) // .def_readonly("isochrones", &FireData::isochrones); py::class_<Waypoint3d>(m, "Waypoint") .def(py::init<const double, const double, const double, const double>(), py::arg("x"), py::arg("y"), py::arg("z"), py::arg("direction")) .def_readonly("x", &Waypoint3d::x) .def_readonly("y", &Waypoint3d::y) .def_readonly("z", &Waypoint3d::z) .def_readonly("dir", &Waypoint3d::dir) .def("__repr__", &Waypoint3d::to_string); py::class_<Segment3d>(m, "Segment") .def(py::init<const Waypoint3d, const double>()) .def(py::init<const Waypoint3d, const Waypoint3d>()) .def_readonly("start", &Segment3d::start) .def_readonly("end", &Segment3d::end) .def_readonly("length", &Segment3d::length) .def("__repr__", &Segment3d::to_string); py::class_<UAV>(m, "UAV") .def(py::init<const double, const double, const double>()) .def_readonly("min_turn_radius", &UAV::min_turn_radius) .def_readonly("max_air_speed", &UAV::max_air_speed) .def_readonly("max_pitch_angle", &UAV::max_pitch_angle) .def("travel_distance", (double (UAV::*)(const Waypoint3d &, const Waypoint3d &) const)&UAV::travel_distance, py::arg("origin"), py::arg("destination")) .def("travel_distance", (double (UAV::*)(const Waypoint &, const Waypoint &) const)&UAV::travel_distance, py::arg("origin"), py::arg("destination")) .def("travel_time", (double (UAV::*)(const Waypoint3d &, const Waypoint3d &) const)&UAV::travel_time, py::arg("origin"), py::arg("destination")) .def("travel_time", (double (UAV::*)(const Waypoint &, const Waypoint &) const)&UAV::travel_time, py::arg("origin"), py::arg("destination")); py::class_<Trajectory>(m, "Trajectory") .def(py::init<const TrajectoryConfig&>()) .def_readonly("conf", &Trajectory::conf) .def("start_time", (double (Trajectory::*)() const)&Trajectory::start_time) .def("end_time", (double (Trajectory::*)() const)&Trajectory::end_time) .def_readonly("segments", &Trajectory::traj) .def("length", &Trajectory::length) .def("duration", &Trajectory::duration) .def("as_waypoints", &Trajectory::as_waypoints) .def("sampled", &Trajectory::sampled, py::arg("step_size") = 1) .def("with_waypoint_at_end", &Trajectory::with_waypoint_at_end) .def("__repr__", &Trajectory::to_string); py::class_<TrajectoryConfig>(m, "TrajectoryConfig") .def(py::init<UAV, Waypoint3d, Waypoint3d, double, double>()) .def_readonly("uav", &TrajectoryConfig::uav) .def_readonly("max_flight_time", &TrajectoryConfig::max_flight_time) .def_static("build", [](UAV uav, double start_time, double max_flight_time) -> TrajectoryConfig { return TrajectoryConfig(uav, start_time, max_flight_time); }, "Constructor", py::arg("uav"), py::arg("start_time") = 0, py::arg("max_flight_time") = std::numeric_limits<double>::max()); py::class_<Plan>(m, "Plan") .def("trajectories", [](Plan& self) { return self.core.trajectories; }) .def("utility", &Plan::utility) .def("duration", &Plan::duration) .def_readonly("firedata", &Plan::firedata) .def("observations", &Plan::observations); py::class_<SearchResult>(m, "SearchResult") .def("initial_plan", &SearchResult::initial) .def("final_plan", &SearchResult::final) .def_readonly("intermediate_plans", &SearchResult::intermediate_plans) .def("metadata", [](SearchResult &self) { return self.metadata.dump(); } ); m.def("plan_vns", [](vector<TrajectoryConfig> configs, DRaster ignitions, DRaster elevation, const std::string& json_conf) -> SearchResult { auto time = []() { struct timeval tp; gettimeofday(&tp, NULL); return (double) tp.tv_sec + ((double)(tp.tv_usec / 1000) /1000.); }; json conf = json::parse(json_conf); const double min_time = conf["min_time"]; const double max_time = conf["max_time"]; const size_t save_every = conf["save_every"]; const bool save_improvements = conf["save_improvements"]; const size_t discrete_elevation_interval = conf["discrete_elevation_interval"]; printf("Processing firedata data\n"); double preprocessing_start = time(); shared_ptr<FireData> fire_data; if (discrete_elevation_interval > 0) { fire_data = make_shared<FireData>(ignitions, DiscreteDRaster(elevation, discrete_elevation_interval)); } else { fire_data = make_shared<FireData>(ignitions, elevation); } double preprocessing_end = time(); printf("Building initial plan\n"); Plan p(configs, fire_data, TimeWindow{min_time, max_time}); printf("Planning\n"); auto vns = vns::build_from_config(conf["vns"].dump()); const double planning_start = time(); auto res = vns->search(p, 0, save_every, save_improvements); const double planning_end = time(); printf("Plan found\n"); res.metadata["planning_time"] = planning_end - planning_start; res.metadata["preprocessing_time"] = preprocessing_end - preprocessing_start; res.metadata["configuration"] = conf; return res; }, py::arg("trajectory_configs"), py::arg("ignitions"), py::arg("elevation"), py::arg("json_conf"), py::call_guard<py::gil_scoped_release>()); } <commit_msg>Expose UAV.path_sampling in python<commit_after>/* Copyright (c) 2017, CNRS-LAAS All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <pybind11/pybind11.h> #include <pybind11/stl.h> // for conversions between c++ and python collections #include <pybind11/numpy.h> // support for numpy arrays #include "core/structures/trajectory.h" #include "raster.h" #include "vns/factory.h" namespace py = pybind11; /** Converts a numpy array to a vector */ template<class T> std::vector<T> as_vector(py::array_t<T, py::array::c_style | py::array::forcecast> array) { std::vector<T> data(array.size()); for(ssize_t x=0; x<array.shape(0); x++) { for(ssize_t y=0; y<array.shape(1); y++) { data[x + y*array.shape(0)] = *(array.data(x, y)); } } return data; } /** Converts a vector to a 2D numpy array. */ template<class T> py::array_t<T> as_nparray(std::vector<T> vec, size_t x_width, size_t y_height) { ASSERT(vec.size() == x_width * y_height) py::array_t<T, py::array::c_style | py::array::forcecast> array(std::vector<size_t> {x_width, y_height}); auto s_x_width = static_cast<ssize_t>(x_width); auto s_y_height = static_cast<ssize_t>(y_height); for(ssize_t x=0; x<s_x_width; x++) { for (ssize_t y = 0; y < s_y_height; y++) { *(array.mutable_data(x, y)) = vec[x + y*x_width]; } } return array; } PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>); PYBIND11_MODULE(uav_planning, m) { m.doc() = "Python module for UAV trajectory planning"; srand(0); py::class_<DRaster>(m, "DRaster") .def(py::init([](py::array_t<double, py::array::c_style | py::array::forcecast> arr, double x_offset, double y_offset, double cell_width) { return new DRaster(as_vector<double>(arr), arr.shape(0), arr.shape(1), x_offset, y_offset, cell_width); })) .def("as_numpy", [](DRaster& self) { return as_nparray<double>(self.data, self.x_width, self.y_height); }) .def_readonly("x_offset", &DRaster::x_offset) .def_readonly("y_offset", &DRaster::y_offset) .def_readonly("cell_width", &DRaster::cell_width); py::class_<LRaster>(m, "LRaster") .def(py::init([](py::array_t<long, py::array::c_style | py::array::forcecast> arr, double x_offset, double y_offset, double cell_width) { return new LRaster(as_vector<long>(arr), arr.shape(0), arr.shape(1), x_offset, y_offset, cell_width); })) .def("as_numpy", [](LRaster& self) { return as_nparray<long>(self.data, self.x_width, self.y_height); }) .def_readonly("x_offset", &LRaster::x_offset) .def_readonly("y_offset", &LRaster::y_offset) .def_readonly("cell_width", &LRaster::cell_width); py::class_<TimeWindow>(m, "TimeWindow") .def(py::init<const double, const double>(), py::arg("start"), py::arg("end")) .def_readonly("start", &TimeWindow::start) .def_readonly("end", &TimeWindow::end) .def("__repr__", [](const TimeWindow &tw) { std::stringstream repr; repr << "TimeWindow(" << tw.start << ", " << tw.end << ")"; return repr.str(); } ) .def("as_tuple", [](TimeWindow &self) { return py::make_tuple(self.start, self.end); } ); py::class_<Cell>(m, "Cell") .def(py::init<const size_t, const size_t>(), py::arg("x"), py::arg("y")) .def_readonly("x", &Cell::x) .def_readonly("y", &Cell::y) .def("__repr__", [](const Cell &c) { std::stringstream repr; repr << "Cell(" << c.x << ", " << c.y << ")"; return repr.str(); } ) .def("as_tuple", [](Cell &self) { return py::make_tuple(self.x, self.y); } ); py::class_<Position>(m, "Position2d") .def(py::init<double, double>(), py::arg("x"), py::arg("y")) .def_readonly("x", &Position::x) .def_readonly("y", &Position::y) .def("__repr__", [](const Position &p) { std::stringstream repr; repr << "Position2d(" << p.x << ", " << p.y << ")"; return repr.str(); } ) .def("as_tuple", [](Position &self) { return py::make_tuple(self.x, self.y); } ); py::class_<Position3d>(m, "Position") .def(py::init<double, double, double>(), py::arg("x"), py::arg("y"), py::arg("z")) .def_readonly("x", &Position3d::x) .def_readonly("y", &Position3d::y) .def_readonly("z", &Position3d::z) .def("__repr__", [](const Position3d &p) { std::stringstream repr; repr << "Position(" << p.x << ", " << p.y << ", " << p.z << ")"; return repr.str(); } ) .def("as_tuple", [](Position3d &self) { return py::make_tuple(self.x, self.y, self.z); } ); py::class_<PositionTime>(m, "Position2dTime") .def(py::init<Position, double>(), py::arg("point"), py::arg("time")) .def_readonly("pt", &PositionTime::pt) .def_readonly("y", &PositionTime::time) .def("__repr__", [](const PositionTime &p) { std::stringstream repr; repr << "Position2dTime(" << p.pt.x << ", " << p.pt.y << ", " << p.time << ")"; return repr.str(); } ) .def("as_tuple", [](PositionTime &self) { return py::make_tuple(py::make_tuple(self.pt.x, self.pt.y), self.time); } ); py::class_<Position3dTime>(m, "PositionTime") .def(py::init<Position3d, double>(), py::arg("point"), py::arg("time")) .def_readonly("pt", &Position3dTime::pt) .def_readonly("y", &Position3dTime::time) .def("__repr__", [](const Position3dTime &p) { std::stringstream repr; repr << "PositionTime(" << p.pt.x << ", " << p.pt.y << ", " << p.pt.z << ", " << p.time << ")"; return repr.str(); } ) .def("as_tuple", [](Position3dTime &self) { return py::make_tuple(py::make_tuple(self.pt.x, self.pt.y, self.pt.z), self.time); } ); py::class_<FireData>(m, "FireData") .def(py::init<DRaster&, DiscreteDRaster&>(), py::arg("ignitions"), py::arg("elevation")) .def_readonly("ignitions", &FireData::ignitions) .def_readonly("traversal_end", &FireData::traversal_end) .def_readonly("propagation_directions", &FireData::propagation_directions) .def_readonly("elevation", &FireData::elevation); // .def_readonly_static("isochrone_timespan", &FireData::isochrone_timespan) // .def_readonly("isochrones", &FireData::isochrones); py::class_<Waypoint3d>(m, "Waypoint") .def(py::init<const double, const double, const double, const double>(), py::arg("x"), py::arg("y"), py::arg("z"), py::arg("direction")) .def_readonly("x", &Waypoint3d::x) .def_readonly("y", &Waypoint3d::y) .def_readonly("z", &Waypoint3d::z) .def_readonly("dir", &Waypoint3d::dir) .def("__repr__", &Waypoint3d::to_string); py::class_<Segment3d>(m, "Segment") .def(py::init<const Waypoint3d, const double>()) .def(py::init<const Waypoint3d, const Waypoint3d>()) .def_readonly("start", &Segment3d::start) .def_readonly("end", &Segment3d::end) .def_readonly("length", &Segment3d::length) .def("__repr__", &Segment3d::to_string); py::class_<UAV>(m, "UAV") .def(py::init<const double, const double, const double>()) .def_readonly("min_turn_radius", &UAV::min_turn_radius) .def_readonly("max_air_speed", &UAV::max_air_speed) .def_readonly("max_pitch_angle", &UAV::max_pitch_angle) .def("travel_distance", (double (UAV::*)(const Waypoint3d &, const Waypoint3d &) const) &UAV::travel_distance, py::arg("origin"), py::arg("destination")) .def("travel_distance", (double (UAV::*)(const Waypoint &, const Waypoint &) const) &UAV::travel_distance, py::arg("origin"), py::arg("destination")) .def("travel_time", (double (UAV::*)(const Waypoint3d &, const Waypoint3d &) const) &UAV::travel_time, py::arg("origin"), py::arg("destination")) .def("travel_time", (double (UAV::*)(const Waypoint &, const Waypoint &) const) &UAV::travel_time, py::arg("origin"), py::arg("destination")) .def("path_sampling", (std::vector<Waypoint3d> (UAV::*)(const Waypoint3d &, const Waypoint3d &, const double) const) &UAV::path_sampling, py::arg("origin"), py::arg("destination"), py::arg("step_size")); py::class_<Trajectory>(m, "Trajectory") .def(py::init<const TrajectoryConfig&>()) .def_readonly("conf", &Trajectory::conf) .def("start_time", (double (Trajectory::*)() const)&Trajectory::start_time) .def("end_time", (double (Trajectory::*)() const)&Trajectory::end_time) .def_readonly("segments", &Trajectory::traj) .def("length", &Trajectory::length) .def("duration", &Trajectory::duration) .def("as_waypoints", &Trajectory::as_waypoints) .def("sampled", &Trajectory::sampled, py::arg("step_size") = 1) .def("with_waypoint_at_end", &Trajectory::with_waypoint_at_end) .def("__repr__", &Trajectory::to_string); py::class_<TrajectoryConfig>(m, "TrajectoryConfig") .def(py::init<UAV, Waypoint3d, Waypoint3d, double, double>()) .def_readonly("uav", &TrajectoryConfig::uav) .def_readonly("max_flight_time", &TrajectoryConfig::max_flight_time) .def_static("build", [](UAV uav, double start_time, double max_flight_time) -> TrajectoryConfig { return TrajectoryConfig(uav, start_time, max_flight_time); }, "Constructor", py::arg("uav"), py::arg("start_time") = 0, py::arg("max_flight_time") = std::numeric_limits<double>::max()); py::class_<Plan>(m, "Plan") .def("trajectories", [](Plan& self) { return self.core.trajectories; }) .def("utility", &Plan::utility) .def("duration", &Plan::duration) .def_readonly("firedata", &Plan::firedata) .def("observations", &Plan::observations); py::class_<SearchResult>(m, "SearchResult") .def("initial_plan", &SearchResult::initial) .def("final_plan", &SearchResult::final) .def_readonly("intermediate_plans", &SearchResult::intermediate_plans) .def("metadata", [](SearchResult &self) { return self.metadata.dump(); } ); m.def("plan_vns", [](vector<TrajectoryConfig> configs, DRaster ignitions, DRaster elevation, const std::string& json_conf) -> SearchResult { auto time = []() { struct timeval tp; gettimeofday(&tp, NULL); return (double) tp.tv_sec + ((double)(tp.tv_usec / 1000) /1000.); }; json conf = json::parse(json_conf); const double min_time = conf["min_time"]; const double max_time = conf["max_time"]; const size_t save_every = conf["save_every"]; const bool save_improvements = conf["save_improvements"]; const size_t discrete_elevation_interval = conf["discrete_elevation_interval"]; printf("Processing firedata data\n"); double preprocessing_start = time(); shared_ptr<FireData> fire_data; if (discrete_elevation_interval > 0) { fire_data = make_shared<FireData>(ignitions, DiscreteDRaster(elevation, discrete_elevation_interval)); } else { fire_data = make_shared<FireData>(ignitions, elevation); } double preprocessing_end = time(); printf("Building initial plan\n"); Plan p(configs, fire_data, TimeWindow{min_time, max_time}); printf("Planning\n"); auto vns = vns::build_from_config(conf["vns"].dump()); const double planning_start = time(); auto res = vns->search(p, 0, save_every, save_improvements); const double planning_end = time(); printf("Plan found\n"); res.metadata["planning_time"] = planning_end - planning_start; res.metadata["preprocessing_time"] = preprocessing_end - preprocessing_start; res.metadata["configuration"] = conf; return res; }, py::arg("trajectory_configs"), py::arg("ignitions"), py::arg("elevation"), py::arg("json_conf"), py::call_guard<py::gil_scoped_release>()); } <|endoftext|>
<commit_before>//===--- XPCService.cpp ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "sourcekitd/Internal-XPC.h" #include "sourcekitd/Logging.h" #include "SourceKit/Core/LLVM.h" #include "SourceKit/Support/Concurrency.h" #include "SourceKit/Support/UIdent.h" #include "SourceKit/Support/Logging.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Errno.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/Threading.h" #include <xpc/xpc.h> using namespace SourceKit; using namespace sourcekitd; static xpc_connection_t MainConnection = nullptr; void sourcekitd::postNotification(sourcekitd_response_t Notification) { xpc_connection_t peer = MainConnection; if (!peer) goto done; { xpc_object_t contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, (uint64_t)xpc::Message::Notification); xpc_array_set_value(contents, XPC_ARRAY_APPEND, Notification); xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents); xpc_release(contents); xpc_connection_send_message(peer, msg); xpc_release(msg); } done: // The function accepted ownership. xpc_release(Notification); } namespace { /// \brief Associates sourcekitd_uid_t to a UIdent. class SKUIDToUIDMap { typedef llvm::DenseMap<void *, UIdent> MapTy; MapTy Map; WorkQueue Queue{ WorkQueue::Dequeuing::Concurrent, "UIDMap" }; public: UIdent get(sourcekitd_uid_t SKDUID); void set(sourcekitd_uid_t SKDUID, UIdent UID); }; } static SKUIDToUIDMap UIDMap; sourcekitd_uid_t sourcekitd::SKDUIDFromUIdent(UIdent UID) { if (void *Tag = UID.getTag()) return reinterpret_cast<sourcekitd_uid_t>(Tag); // FIXME: The following should run in the synchronous dispatch queue of the // connection. But does it matter, since if MainConnection is null or gets // destroyed it means the client crashed ? xpc_connection_t peer = MainConnection; if (!peer) return nullptr; xpc_object_t contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, (uint64_t)xpc::Message::UIDSynchronization); xpc_array_set_string(contents, XPC_ARRAY_APPEND, UID.c_str()); xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents); xpc_release(contents); xpc_object_t reply = xpc_connection_send_message_with_reply_sync(peer, msg); xpc_release(msg); if (xpc_get_type(reply) == XPC_TYPE_ERROR) { xpc_release(reply); return nullptr; } assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY); uint64_t val = xpc_dictionary_get_uint64(reply, xpc::KeyMsgResponse); xpc_release(reply); sourcekitd_uid_t skduid = sourcekitd_uid_t(val); UID.setTag(skduid); UIDMap.set(skduid, UID); return skduid; } UIdent sourcekitd::UIdentFromSKDUID(sourcekitd_uid_t SKDUID) { // This should be used only for debugging/logging purposes. UIdent UID = UIDMap.get(SKDUID); if (UID.isValid()) return UID; xpc_connection_t Peer = MainConnection; if (!Peer) return UIdent(); xpc_object_t contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, (uint64_t)xpc::Message::UIDSynchronization); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, uintptr_t(SKDUID)); xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents); xpc_release(contents); xpc_object_t reply = xpc_connection_send_message_with_reply_sync(Peer, msg); xpc_release(msg); if (xpc_get_type(reply) == XPC_TYPE_ERROR) { xpc_release(reply); return UIdent(); } assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY); const char *Str = xpc_dictionary_get_string(reply, xpc::KeyMsgResponse); UID = UIdent(Str); UID.setTag(SKDUID); UIDMap.set(SKDUID, UID); xpc_release(reply); return UID; } void anchorForGetMainExecutableInXPCService() {} namespace { /// Responsible for replying to an XPC request. class XPCResponder { xpc_connection_t Peer; xpc_object_t Event; bool Responded = false; public: XPCResponder(xpc_object_t event, xpc_connection_t peer) : Peer(xpc_connection_t(xpc_retain(peer))), Event(xpc_retain(event)) {} ~XPCResponder() { if (!Responded) { LOG_WARN_FUNC("failed to respond to request"); sendReply(createErrorRequestFailed("Internal error: no response was " "provided for the request")); } xpc_release(Event); xpc_release(Peer); } /// Accepts ownership of the response object. void sendReply(sourcekitd_response_t response) { if (Responded) { LOG_WARN_FUNC("tried to respond to an already handled request"); return; } xpc_object_t reply = xpc_dictionary_create_reply(Event); xpc_dictionary_set_value(reply, xpc::KeyMsgResponse, response); xpc_release(response); xpc_connection_send_message(Peer, reply); xpc_release(reply); Responded = true; } }; } std::string sourcekitd::getRuntimeLibPath() { std::string MainExePath = llvm::sys::fs::getMainExecutable("sourcekit", reinterpret_cast<void *>(&anchorForGetMainExecutableInXPCService)); #ifdef SOURCEKIT_UNVERSIONED_FRAMEWORK_BUNDLE // MainExePath points to "lib/sourcekitd.framework/XPCServices/ // SourceKitService.xpc/SourceKitService" const unsigned MainExeLibNestingLevel = 4; #else // MainExePath points to "lib/sourcekitd.framework/Versions/Current/XPCServices/ // SourceKitService.xpc/Contents/MacOS/SourceKitService" const unsigned MainExeLibNestingLevel = 8; #endif // Get it to lib. StringRef Path = MainExePath; for (unsigned i = 0; i < MainExeLibNestingLevel; ++i) Path = llvm::sys::path::parent_path(Path); return Path; } static void sourcekitdServer_peer_event_handler(xpc_connection_t peer, xpc_object_t event) { xpc_type_t type = xpc_get_type(event); if (type == XPC_TYPE_ERROR) { if (event == XPC_ERROR_CONNECTION_INVALID) { // The client process on the other end of the connection has either // crashed or cancelled the connection. After receiving this error, // the connection is in an invalid state, and we do not need to // call xpc_connection_cancel(). // No need to call sourcekitd::shutdown() since the process is going down // anyway, plus if we get a new connection before the process closes then // we will fail to re-initialize properly since the initialize call is at // main. xpc_transaction_end(); } else if (event == XPC_ERROR_TERMINATION_IMMINENT) { // Handle per-connection termination cleanup. xpc_connection_cancel(peer); } } else { assert(type == XPC_TYPE_DICTIONARY); // Handle the message xpc_retain(event); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{ xpc_object_t contents = xpc_dictionary_get_value(event, "msg"); if (!contents) { // Ping back. contents = xpc_dictionary_get_value(event, "ping"); assert(contents && "unexpected message"); xpc_object_t reply = xpc_dictionary_create_reply(event); assert(reply); xpc_connection_send_message(peer, reply); xpc_release(reply); return; } auto Responder = std::make_shared<XPCResponder>(event, peer); xpc_release(event); assert(xpc_get_type(contents) == XPC_TYPE_ARRAY); sourcekitd_object_t req = xpc_array_get_value(contents, 0); sourcekitd::handleRequest(req, [Responder](sourcekitd_response_t response) { Responder->sendReply(response); }); }); } } static void getInitializationInfo(xpc_connection_t peer) { xpc_object_t contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, (uint64_t)xpc::Message::Initialization); xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents); xpc_release(contents); xpc_object_t reply = xpc_connection_send_message_with_reply_sync(peer, msg); xpc_release(msg); if (xpc_get_type(reply) == XPC_TYPE_ERROR) { xpc_release(reply); return; } assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY); uint64_t Delay = xpc_dictionary_get_uint64(reply, xpc::KeySemaEditorDelay); xpc_release(reply); if (Delay != 0) { llvm::SmallString<4> Buf; { llvm::raw_svector_ostream OS(Buf); OS << Delay; } setenv("SOURCEKIT_DELAY_SEMA_EDITOR", Buf.c_str(), /*overwrite=*/1); } } static void sourcekitdServer_event_handler(xpc_connection_t peer) { // Keep the service alive even when idle. xpc_transaction_begin(); // By defaults, new connections will target the default dispatch // concurrent queue. xpc_connection_set_event_handler(peer, ^(xpc_object_t event) { sourcekitdServer_peer_event_handler(peer, event); }); // Update the main connection xpc_retain(peer); if (MainConnection) xpc_release(MainConnection); MainConnection = peer; // This will tell the connection to begin listening for events. If you // have some other initialization that must be done asynchronously, then // you can defer this call until after that initialization is done. xpc_connection_resume(peer); dispatch_async(dispatch_get_main_queue(), ^{ getInitializationInfo(MainConnection); }); } static void fatal_error_handler(void *user_data, const std::string& reason, bool gen_crash_diag) { // Write the result out to stderr avoiding errs() because raw_ostreams can // call report_fatal_error. fprintf(stderr, "SOURCEKITD SERVER FATAL ERROR: %s\n", reason.c_str()); ::abort(); } int main(int argc, const char *argv[]) { llvm::install_fatal_error_handler(fatal_error_handler, 0); sourcekitd::enableLogging("sourcekit-serv"); sourcekitd::initialize(); // Increase the file descriptor limit. // FIXME: Portability ? static const size_t FDLimit = 4096; struct rlimit l; if (getrlimit(RLIMIT_NOFILE, &l) == 0) { if (l.rlim_cur < FDLimit) { l.rlim_cur = FDLimit; if (setrlimit(RLIMIT_NOFILE, &l) == 0) { LOG_INFO_FUNC(Low, "bumped file descriptor limit to " << FDLimit); } else { LOG_WARN_FUNC("setrlimit failed: " << llvm::sys::StrError()); } } } else { LOG_WARN_FUNC("getrlimit failed: " << llvm::sys::StrError()); } xpc_main(sourcekitdServer_event_handler); return 0; } UIdent SKUIDToUIDMap::get(sourcekitd_uid_t SKDUID) { UIdent UID; Queue.dispatchSync([&]{ MapTy::iterator It = Map.find(SKDUID); if (It != Map.end()) UID = It->second; }); return UID; } void SKUIDToUIDMap::set(sourcekitd_uid_t SKDUID, UIdent UID) { Queue.dispatchBarrier([=]{ this->Map[SKDUID] = UID; }); } <commit_msg>[sourcekitd] In the fatal error handler, don't call abort() if gen_crash_diag is false<commit_after>//===--- XPCService.cpp ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "sourcekitd/Internal-XPC.h" #include "sourcekitd/Logging.h" #include "SourceKit/Core/LLVM.h" #include "SourceKit/Support/Concurrency.h" #include "SourceKit/Support/UIdent.h" #include "SourceKit/Support/Logging.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Errno.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/Threading.h" #include <xpc/xpc.h> using namespace SourceKit; using namespace sourcekitd; static xpc_connection_t MainConnection = nullptr; void sourcekitd::postNotification(sourcekitd_response_t Notification) { xpc_connection_t peer = MainConnection; if (!peer) goto done; { xpc_object_t contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, (uint64_t)xpc::Message::Notification); xpc_array_set_value(contents, XPC_ARRAY_APPEND, Notification); xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents); xpc_release(contents); xpc_connection_send_message(peer, msg); xpc_release(msg); } done: // The function accepted ownership. xpc_release(Notification); } namespace { /// \brief Associates sourcekitd_uid_t to a UIdent. class SKUIDToUIDMap { typedef llvm::DenseMap<void *, UIdent> MapTy; MapTy Map; WorkQueue Queue{ WorkQueue::Dequeuing::Concurrent, "UIDMap" }; public: UIdent get(sourcekitd_uid_t SKDUID); void set(sourcekitd_uid_t SKDUID, UIdent UID); }; } static SKUIDToUIDMap UIDMap; sourcekitd_uid_t sourcekitd::SKDUIDFromUIdent(UIdent UID) { if (void *Tag = UID.getTag()) return reinterpret_cast<sourcekitd_uid_t>(Tag); // FIXME: The following should run in the synchronous dispatch queue of the // connection. But does it matter, since if MainConnection is null or gets // destroyed it means the client crashed ? xpc_connection_t peer = MainConnection; if (!peer) return nullptr; xpc_object_t contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, (uint64_t)xpc::Message::UIDSynchronization); xpc_array_set_string(contents, XPC_ARRAY_APPEND, UID.c_str()); xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents); xpc_release(contents); xpc_object_t reply = xpc_connection_send_message_with_reply_sync(peer, msg); xpc_release(msg); if (xpc_get_type(reply) == XPC_TYPE_ERROR) { xpc_release(reply); return nullptr; } assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY); uint64_t val = xpc_dictionary_get_uint64(reply, xpc::KeyMsgResponse); xpc_release(reply); sourcekitd_uid_t skduid = sourcekitd_uid_t(val); UID.setTag(skduid); UIDMap.set(skduid, UID); return skduid; } UIdent sourcekitd::UIdentFromSKDUID(sourcekitd_uid_t SKDUID) { // This should be used only for debugging/logging purposes. UIdent UID = UIDMap.get(SKDUID); if (UID.isValid()) return UID; xpc_connection_t Peer = MainConnection; if (!Peer) return UIdent(); xpc_object_t contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, (uint64_t)xpc::Message::UIDSynchronization); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, uintptr_t(SKDUID)); xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents); xpc_release(contents); xpc_object_t reply = xpc_connection_send_message_with_reply_sync(Peer, msg); xpc_release(msg); if (xpc_get_type(reply) == XPC_TYPE_ERROR) { xpc_release(reply); return UIdent(); } assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY); const char *Str = xpc_dictionary_get_string(reply, xpc::KeyMsgResponse); UID = UIdent(Str); UID.setTag(SKDUID); UIDMap.set(SKDUID, UID); xpc_release(reply); return UID; } void anchorForGetMainExecutableInXPCService() {} namespace { /// Responsible for replying to an XPC request. class XPCResponder { xpc_connection_t Peer; xpc_object_t Event; bool Responded = false; public: XPCResponder(xpc_object_t event, xpc_connection_t peer) : Peer(xpc_connection_t(xpc_retain(peer))), Event(xpc_retain(event)) {} ~XPCResponder() { if (!Responded) { LOG_WARN_FUNC("failed to respond to request"); sendReply(createErrorRequestFailed("Internal error: no response was " "provided for the request")); } xpc_release(Event); xpc_release(Peer); } /// Accepts ownership of the response object. void sendReply(sourcekitd_response_t response) { if (Responded) { LOG_WARN_FUNC("tried to respond to an already handled request"); return; } xpc_object_t reply = xpc_dictionary_create_reply(Event); xpc_dictionary_set_value(reply, xpc::KeyMsgResponse, response); xpc_release(response); xpc_connection_send_message(Peer, reply); xpc_release(reply); Responded = true; } }; } std::string sourcekitd::getRuntimeLibPath() { std::string MainExePath = llvm::sys::fs::getMainExecutable("sourcekit", reinterpret_cast<void *>(&anchorForGetMainExecutableInXPCService)); #ifdef SOURCEKIT_UNVERSIONED_FRAMEWORK_BUNDLE // MainExePath points to "lib/sourcekitd.framework/XPCServices/ // SourceKitService.xpc/SourceKitService" const unsigned MainExeLibNestingLevel = 4; #else // MainExePath points to "lib/sourcekitd.framework/Versions/Current/XPCServices/ // SourceKitService.xpc/Contents/MacOS/SourceKitService" const unsigned MainExeLibNestingLevel = 8; #endif // Get it to lib. StringRef Path = MainExePath; for (unsigned i = 0; i < MainExeLibNestingLevel; ++i) Path = llvm::sys::path::parent_path(Path); return Path; } static void sourcekitdServer_peer_event_handler(xpc_connection_t peer, xpc_object_t event) { xpc_type_t type = xpc_get_type(event); if (type == XPC_TYPE_ERROR) { if (event == XPC_ERROR_CONNECTION_INVALID) { // The client process on the other end of the connection has either // crashed or cancelled the connection. After receiving this error, // the connection is in an invalid state, and we do not need to // call xpc_connection_cancel(). // No need to call sourcekitd::shutdown() since the process is going down // anyway, plus if we get a new connection before the process closes then // we will fail to re-initialize properly since the initialize call is at // main. xpc_transaction_end(); } else if (event == XPC_ERROR_TERMINATION_IMMINENT) { // Handle per-connection termination cleanup. xpc_connection_cancel(peer); } } else { assert(type == XPC_TYPE_DICTIONARY); // Handle the message xpc_retain(event); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{ xpc_object_t contents = xpc_dictionary_get_value(event, "msg"); if (!contents) { // Ping back. contents = xpc_dictionary_get_value(event, "ping"); assert(contents && "unexpected message"); xpc_object_t reply = xpc_dictionary_create_reply(event); assert(reply); xpc_connection_send_message(peer, reply); xpc_release(reply); return; } auto Responder = std::make_shared<XPCResponder>(event, peer); xpc_release(event); assert(xpc_get_type(contents) == XPC_TYPE_ARRAY); sourcekitd_object_t req = xpc_array_get_value(contents, 0); sourcekitd::handleRequest(req, [Responder](sourcekitd_response_t response) { Responder->sendReply(response); }); }); } } static void getInitializationInfo(xpc_connection_t peer) { xpc_object_t contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, (uint64_t)xpc::Message::Initialization); xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents); xpc_release(contents); xpc_object_t reply = xpc_connection_send_message_with_reply_sync(peer, msg); xpc_release(msg); if (xpc_get_type(reply) == XPC_TYPE_ERROR) { xpc_release(reply); return; } assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY); uint64_t Delay = xpc_dictionary_get_uint64(reply, xpc::KeySemaEditorDelay); xpc_release(reply); if (Delay != 0) { llvm::SmallString<4> Buf; { llvm::raw_svector_ostream OS(Buf); OS << Delay; } setenv("SOURCEKIT_DELAY_SEMA_EDITOR", Buf.c_str(), /*overwrite=*/1); } } static void sourcekitdServer_event_handler(xpc_connection_t peer) { // Keep the service alive even when idle. xpc_transaction_begin(); // By defaults, new connections will target the default dispatch // concurrent queue. xpc_connection_set_event_handler(peer, ^(xpc_object_t event) { sourcekitdServer_peer_event_handler(peer, event); }); // Update the main connection xpc_retain(peer); if (MainConnection) xpc_release(MainConnection); MainConnection = peer; // This will tell the connection to begin listening for events. If you // have some other initialization that must be done asynchronously, then // you can defer this call until after that initialization is done. xpc_connection_resume(peer); dispatch_async(dispatch_get_main_queue(), ^{ getInitializationInfo(MainConnection); }); } static void fatal_error_handler(void *user_data, const std::string& reason, bool gen_crash_diag) { // Write the result out to stderr avoiding errs() because raw_ostreams can // call report_fatal_error. fprintf(stderr, "SOURCEKITD SERVER FATAL ERROR: %s\n", reason.c_str()); if (gen_crash_diag) ::abort(); } int main(int argc, const char *argv[]) { llvm::install_fatal_error_handler(fatal_error_handler, 0); sourcekitd::enableLogging("sourcekit-serv"); sourcekitd::initialize(); // Increase the file descriptor limit. // FIXME: Portability ? static const size_t FDLimit = 4096; struct rlimit l; if (getrlimit(RLIMIT_NOFILE, &l) == 0) { if (l.rlim_cur < FDLimit) { l.rlim_cur = FDLimit; if (setrlimit(RLIMIT_NOFILE, &l) == 0) { LOG_INFO_FUNC(Low, "bumped file descriptor limit to " << FDLimit); } else { LOG_WARN_FUNC("setrlimit failed: " << llvm::sys::StrError()); } } } else { LOG_WARN_FUNC("getrlimit failed: " << llvm::sys::StrError()); } xpc_main(sourcekitdServer_event_handler); return 0; } UIdent SKUIDToUIDMap::get(sourcekitd_uid_t SKDUID) { UIdent UID; Queue.dispatchSync([&]{ MapTy::iterator It = Map.find(SKDUID); if (It != Map.end()) UID = It->second; }); return UID; } void SKUIDToUIDMap::set(sourcekitd_uid_t SKDUID, UIdent UID) { Queue.dispatchBarrier([=]{ this->Map[SKDUID] = UID; }); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "courgette/base_test_unittest.h" #include "courgette/courgette.h" #include "courgette/streams.h" class EnsembleTest : public BaseTest { public: void TestEnsemble(std::string src_bytes, std::string tgt_bytes) const; void PeEnsemble() const; }; void EnsembleTest::TestEnsemble(std::string src_bytes, std::string tgt_bytes) const { courgette::SourceStream source; courgette::SourceStream target; source.Init(src_bytes); target.Init(tgt_bytes); courgette::SinkStream patch_sink; courgette::Status status; status = courgette::GenerateEnsemblePatch(&source, &target, &patch_sink); EXPECT_EQ(courgette::C_OK, status); courgette::SourceStream patch_source; patch_source.Init(patch_sink.Buffer(), patch_sink.Length()); courgette::SinkStream patch_result; status = courgette::ApplyEnsemblePatch(&source, &patch_source, &patch_result); EXPECT_EQ(courgette::C_OK, status); EXPECT_EQ(target.OriginalLength(), patch_result.Length()); EXPECT_FALSE(memcmp(target.Buffer(), patch_result.Buffer(), target.OriginalLength())); } void EnsembleTest::PeEnsemble() const { std::list<std::string> src_ensemble; std::list<std::string> tgt_ensemble; src_ensemble.push_back("en-US.dll"); src_ensemble.push_back("setup1.exe"); src_ensemble.push_back("elf-32-1"); src_ensemble.push_back("pe-64.exe"); tgt_ensemble.push_back("en-US.dll"); tgt_ensemble.push_back("setup2.exe"); tgt_ensemble.push_back("elf-32-2"); tgt_ensemble.push_back("pe-64.exe"); std::string src_bytes = FilesContents(src_ensemble); std::string tgt_bytes = FilesContents(tgt_ensemble); src_bytes = "aaabbbccc" + src_bytes + "dddeeefff"; tgt_bytes = "aaagggccc" + tgt_bytes + "dddeeefff"; TestEnsemble(src_bytes, tgt_bytes); } TEST_F(EnsembleTest, All) { PeEnsemble(); } <commit_msg>Disable the Courgette ensemble unittest.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "courgette/base_test_unittest.h" #include "courgette/courgette.h" #include "courgette/streams.h" class EnsembleTest : public BaseTest { public: void TestEnsemble(std::string src_bytes, std::string tgt_bytes) const; void PeEnsemble() const; }; void EnsembleTest::TestEnsemble(std::string src_bytes, std::string tgt_bytes) const { courgette::SourceStream source; courgette::SourceStream target; source.Init(src_bytes); target.Init(tgt_bytes); courgette::SinkStream patch_sink; courgette::Status status; status = courgette::GenerateEnsemblePatch(&source, &target, &patch_sink); EXPECT_EQ(courgette::C_OK, status); courgette::SourceStream patch_source; patch_source.Init(patch_sink.Buffer(), patch_sink.Length()); courgette::SinkStream patch_result; status = courgette::ApplyEnsemblePatch(&source, &patch_source, &patch_result); EXPECT_EQ(courgette::C_OK, status); EXPECT_EQ(target.OriginalLength(), patch_result.Length()); EXPECT_FALSE(memcmp(target.Buffer(), patch_result.Buffer(), target.OriginalLength())); } void EnsembleTest::PeEnsemble() const { std::list<std::string> src_ensemble; std::list<std::string> tgt_ensemble; src_ensemble.push_back("en-US.dll"); src_ensemble.push_back("setup1.exe"); src_ensemble.push_back("elf-32-1"); src_ensemble.push_back("pe-64.exe"); tgt_ensemble.push_back("en-US.dll"); tgt_ensemble.push_back("setup2.exe"); tgt_ensemble.push_back("elf-32-2"); tgt_ensemble.push_back("pe-64.exe"); std::string src_bytes = FilesContents(src_ensemble); std::string tgt_bytes = FilesContents(tgt_ensemble); src_bytes = "aaabbbccc" + src_bytes + "dddeeefff"; tgt_bytes = "aaagggccc" + tgt_bytes + "dddeeefff"; TestEnsemble(src_bytes, tgt_bytes); } TEST_F(EnsembleTest, DISABLED_All) { // TODO(dgarrett) http://code.google.com/p/chromium/issues/detail?id=101614 PeEnsemble(); } <|endoftext|>
<commit_before>//https://code.google.com/p/nya-engine/ #include "fbo.h" #include "platform_specific_gl.h" namespace nya_render { #ifdef NO_EXTENSIONS_INIT #define fbo_glGenFramebuffers glGenFramebuffers #define fbo_glBindFramebuffer glBindFramebuffer #define fbo_glDeleteFramebuffers glDeleteFramebuffers; #define fbo_glFramebufferTexture2D glFramebufferTexture2D; #else PFNGLGENFRAMEBUFFERSPROC fbo_glGenFramebuffers; PFNGLBINDFRAMEBUFFERPROC fbo_glBindFramebuffer; PFNGLDELETEFRAMEBUFFERSPROC fbo_glDeleteFramebuffers; PFNGLFRAMEBUFFERTEXTURE2DPROC fbo_glFramebufferTexture2D; #endif bool check_init_fbo() { static bool initialised=false; static bool failed=true; if(initialised) return !failed; //if(!has_extension("GL_EXT_framebuffer_object")) // return false; #ifndef NO_EXTENSIONS_INIT fbo_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)get_extension("glGenFramebuffers"); if(!fbo_glGenFramebuffers) return false; fbo_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)get_extension("glBindFramebuffer"); if(!fbo_glBindFramebuffer) return false; fbo_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)get_extension("glDeleteFramebuffers"); if(!fbo_glDeleteFramebuffers) return false; fbo_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)get_extension("glFramebufferTexture2D"); if(!fbo_glFramebufferTexture2D) return false; #endif initialised=true; failed=false; return true; } void fbo::set_color_target(const texture &tex) { if(!check_init_fbo()) return; if(tex.m_gl_type!=GL_TEXTURE_2D) return; if(m_color_target_idx==tex.m_tex_id) return; if(!m_fbo_idx) fbo_glGenFramebuffers(1,&m_fbo_idx); fbo_glBindFramebuffer(GL_FRAMEBUFFER,m_fbo_idx); if(!m_color_target_idx && m_depth_target_idx) { glDrawBuffer(GL_COLOR_ATTACHMENT0); glReadBuffer(GL_COLOR_ATTACHMENT0); } fbo_glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,tex.m_tex_id,0); fbo_glBindFramebuffer(GL_FRAMEBUFFER,0); m_color_target_idx=tex.m_tex_id; } void fbo::set_depth_target(const texture &tex) { if(!check_init_fbo()) return; if(tex.m_gl_type!=GL_TEXTURE_2D) return; if(m_depth_target_idx==tex.m_tex_id) return; if(!m_fbo_idx) fbo_glGenFramebuffers(1,&m_fbo_idx); fbo_glBindFramebuffer(GL_FRAMEBUFFER,m_fbo_idx); if(!m_color_target_idx) { glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); } fbo_glFramebufferTexture2D(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D,tex.m_tex_id,0); fbo_glBindFramebuffer(GL_FRAMEBUFFER,0); m_depth_target_idx=tex.m_tex_id; } void fbo::release() { if(!m_fbo_idx) return; fbo_glBindFramebuffer(GL_FRAMEBUFFER,0); fbo_glDeleteFramebuffers(1,&m_fbo_idx); m_fbo_idx=0; m_color_target_idx=0; m_depth_target_idx=0; } void fbo::bind() { if(!m_fbo_idx) return; fbo_glBindFramebuffer(GL_FRAMEBUFFER,m_fbo_idx); } void fbo::unbind() { if(!m_fbo_idx) return; fbo_glBindFramebuffer(GL_FRAMEBUFFER,0); } } <commit_msg>fbo fix<commit_after>//https://code.google.com/p/nya-engine/ #include "fbo.h" #include "platform_specific_gl.h" namespace nya_render { #ifdef NO_EXTENSIONS_INIT #define fbo_glGenFramebuffers glGenFramebuffers #define fbo_glBindFramebuffer glBindFramebuffer #define fbo_glDeleteFramebuffers glDeleteFramebuffers #define fbo_glFramebufferTexture2D glFramebufferTexture2D #else PFNGLGENFRAMEBUFFERSPROC fbo_glGenFramebuffers; PFNGLBINDFRAMEBUFFERPROC fbo_glBindFramebuffer; PFNGLDELETEFRAMEBUFFERSPROC fbo_glDeleteFramebuffers; PFNGLFRAMEBUFFERTEXTURE2DPROC fbo_glFramebufferTexture2D; #endif bool check_init_fbo() { static bool initialised=false; static bool failed=true; if(initialised) return !failed; //if(!has_extension("GL_EXT_framebuffer_object")) // return false; #ifndef NO_EXTENSIONS_INIT fbo_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)get_extension("glGenFramebuffers"); if(!fbo_glGenFramebuffers) return false; fbo_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)get_extension("glBindFramebuffer"); if(!fbo_glBindFramebuffer) return false; fbo_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)get_extension("glDeleteFramebuffers"); if(!fbo_glDeleteFramebuffers) return false; fbo_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)get_extension("glFramebufferTexture2D"); if(!fbo_glFramebufferTexture2D) return false; #endif initialised=true; failed=false; return true; } void fbo::set_color_target(const texture &tex) { if(!check_init_fbo()) return; if(tex.m_gl_type!=GL_TEXTURE_2D) return; if(m_color_target_idx==tex.m_tex_id) return; if(!m_fbo_idx) fbo_glGenFramebuffers(1,&m_fbo_idx); fbo_glBindFramebuffer(GL_FRAMEBUFFER,m_fbo_idx); if(!m_color_target_idx && m_depth_target_idx) { glDrawBuffer(GL_COLOR_ATTACHMENT0); glReadBuffer(GL_COLOR_ATTACHMENT0); } fbo_glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,tex.m_tex_id,0); fbo_glBindFramebuffer(GL_FRAMEBUFFER,0); m_color_target_idx=tex.m_tex_id; } void fbo::set_depth_target(const texture &tex) { if(!check_init_fbo()) return; if(tex.m_gl_type!=GL_TEXTURE_2D) return; if(m_depth_target_idx==tex.m_tex_id) return; if(!m_fbo_idx) fbo_glGenFramebuffers(1,&m_fbo_idx); fbo_glBindFramebuffer(GL_FRAMEBUFFER,m_fbo_idx); if(!m_color_target_idx) { glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); } fbo_glFramebufferTexture2D(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D,tex.m_tex_id,0); fbo_glBindFramebuffer(GL_FRAMEBUFFER,0); m_depth_target_idx=tex.m_tex_id; } void fbo::release() { if(!m_fbo_idx) return; fbo_glBindFramebuffer(GL_FRAMEBUFFER,0); fbo_glDeleteFramebuffers(1,&m_fbo_idx); m_fbo_idx=0; m_color_target_idx=0; m_depth_target_idx=0; } void fbo::bind() { if(!m_fbo_idx) return; fbo_glBindFramebuffer(GL_FRAMEBUFFER,m_fbo_idx); } void fbo::unbind() { if(!m_fbo_idx) return; fbo_glBindFramebuffer(GL_FRAMEBUFFER,0); } } <|endoftext|>
<commit_before>/* This file is part of Ingen. * Copyright (C) 2008-2009 Dave Robillard <http://drobilla.net> * * Ingen is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * Ingen 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 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., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <dlfcn.h> #include <limits.h> #include <stdlib.h> #include <glibmm/module.h> #include <glibmm/miscutils.h> #include "ingen-config.h" #include "runtime_paths.hpp" using namespace std; namespace Ingen { namespace Shared { static std::string bundle_path; /** Must be called once at startup, and passed a pointer to a function * that lives in the 'top level' of the bundle (e.g. the executable). * Passing a function defined in a module etc. will not work! */ void set_bundle_path_from_code(void* function) { Dl_info dli; dladdr(function, &dli); #ifdef BUNDLE char bin_loc[PATH_MAX]; realpath(dli.dli_fname, bin_loc); #else const char* bin_loc = dli.dli_fname; #endif string bundle = bin_loc; bundle = bundle.substr(0, bundle.find_last_of(G_DIR_SEPARATOR)); bundle_path = bundle; } void set_bundle_path(const char* path) { bundle_path = path; } /** Return the absolute path of a file in an Ingen LV2 bundle */ std::string bundle_file_path(const std::string& name) { return Glib::build_filename(bundle_path, name); } /** Return the absolute path of a 'resource' file. */ std::string data_file_path(const std::string& name) { #ifdef BUNDLE return Glib::build_filename(bundle_path, Glib::build_path(INGEN_DATA_DIR, name)); #else return Glib::build_filename(INGEN_DATA_DIR, name); #endif } /** Return the absolute path of a module (dynamically loaded shared library). */ std::string module_path(const std::string& name) { std::string ret; #ifdef BUNDLE ret = Glib::Module::build_path(Glib::build_path(bundle_path, INGEN_MODULE_DIR), name); #else ret = Glib::Module::build_path(INGEN_MODULE_DIR, name); #endif #ifdef __APPLE__ // MacPorts glib doesnt seem to do portable path building correctly... if (ret.substr(ret.length() - 3) == ".so") ret = ret.substr(0, ret.length() - 2).append("dylib"); return ret; #endif } } // namespace Ingen } // namespace Shared <commit_msg>Fix module loading on non-Apple (oops).<commit_after>/* This file is part of Ingen. * Copyright (C) 2008-2009 Dave Robillard <http://drobilla.net> * * Ingen is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * Ingen 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 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., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <dlfcn.h> #include <limits.h> #include <stdlib.h> #include <glibmm/module.h> #include <glibmm/miscutils.h> #include "ingen-config.h" #include "runtime_paths.hpp" using namespace std; namespace Ingen { namespace Shared { static std::string bundle_path; /** Must be called once at startup, and passed a pointer to a function * that lives in the 'top level' of the bundle (e.g. the executable). * Passing a function defined in a module etc. will not work! */ void set_bundle_path_from_code(void* function) { Dl_info dli; dladdr(function, &dli); #ifdef BUNDLE char bin_loc[PATH_MAX]; realpath(dli.dli_fname, bin_loc); #else const char* bin_loc = dli.dli_fname; #endif string bundle = bin_loc; bundle = bundle.substr(0, bundle.find_last_of(G_DIR_SEPARATOR)); bundle_path = bundle; } void set_bundle_path(const char* path) { bundle_path = path; } /** Return the absolute path of a file in an Ingen LV2 bundle */ std::string bundle_file_path(const std::string& name) { return Glib::build_filename(bundle_path, name); } /** Return the absolute path of a 'resource' file. */ std::string data_file_path(const std::string& name) { #ifdef BUNDLE return Glib::build_filename(bundle_path, Glib::build_path(INGEN_DATA_DIR, name)); #else return Glib::build_filename(INGEN_DATA_DIR, name); #endif } /** Return the absolute path of a module (dynamically loaded shared library). */ std::string module_path(const std::string& name) { std::string ret; #ifdef BUNDLE ret = Glib::Module::build_path(Glib::build_path(bundle_path, INGEN_MODULE_DIR), name); #else ret = Glib::Module::build_path(INGEN_MODULE_DIR, name); #endif #ifdef __APPLE__ // MacPorts glib doesnt seem to do portable path building correctly... if (ret.substr(ret.length() - 3) == ".so") ret = ret.substr(0, ret.length() - 2).append("dylib"); #endif return ret; } } // namespace Ingen } // namespace Shared <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <cassert> #include <vector> #include <unordered_map> #include <string> #include <stdexcept> #include <functional> #include "utils/uncopyable.hpp" #include "utils/tout.hpp" namespace fr { struct Config; struct Camera; class Image; class LightList; struct Shader; struct Texture; struct Material; struct Mesh; class NetNode; struct FatRay; class Library : private Uncopyable { public: explicit Library(); ~Library(); // Configs... void StoreConfig(Config* config); inline Config* LookupConfig() const { return _config; } // Cameras... void StoreCamera(Camera* camera); inline Camera* LookupCamera() const { return _camera; } // Images... void StoreImage(Image* image); inline Image* LookupImage() const { return _image; } // Light lists... void StoreLightList(LightList* lights); inline LightList* LookupLightList() const { return _lights; } // Shaders... inline uint32_t NextShaderID() const { return _shaders.size(); } void StoreShader(uint32_t id, Shader* shader); inline Shader* LookupShader(uint32_t id) const { assert(id > 0); assert(id < _shaders.size()); return _shaders[id]; }; // Textures... inline uint32_t NextTextureID() const { return _textures.size(); } void StoreTexture(uint32_t id, Texture* texture); inline Texture* LookupTexture(uint32_t id) const { assert(id > 0); assert(id < _textures.size()); return _textures[id]; } // Materials... inline uint32_t NextMaterialID() const { return _materials.size(); } void StoreMaterial(uint32_t id, Material* material, const std::string& name); inline Material* LookupMaterial(uint32_t id) const { assert(id > 0); assert(id < _materials.size()); return _materials[id]; } inline uint32_t LookupMaterial(const std::string& name) const { uint32_t id = 0; try { id = _material_name_index.at(name); } catch (std::out_of_range& e) { id = 0; } return id; } // Meshes... inline uint32_t NextMeshID() const { return _meshes.size(); } void StoreMesh(uint32_t id, Mesh* mesh); inline Mesh* LookupMesh(uint32_t id) const { assert(id > 0); assert(id < _meshes.size()); return _meshes[id]; } void ForEachMesh(std::function<void (uint32_t id, Mesh* mesh)> func); void ForEachEmissiveMesh(std::function<void (uint32_t id, Mesh* mesh)> func); void NaiveIntersect(FatRay* ray, uint32_t me); void Intersect(FatRay* ray, uint32_t me); // Net nodes... void StoreNetNode(uint32_t id, NetNode* node); inline NetNode* LookupNetNode(uint32_t id) const { assert(id > 0); assert(id < _nodes.size()); return _nodes[id]; } void ForEachNetNode(std::function<void (uint32_t id, NetNode* node)> func); template <typename RetType> std::vector<RetType> ForEachNetNode(std::function<RetType (uint32_t id, NetNode* node)> func) { std::vector<RetType> results(_nodes.size()); for (uint32_t id = 1; id < _nodes.size(); id++) { NetNode* node = _nodes[id]; if (node == nullptr) continue; RetType result = func(id, node); results.insert(results.begin() + id, result); } return results; } // Spatial index access for net nodes... void BuildSpatialIndex(); inline uint32_t LookupNetNodeBySpaceCode(uint64_t spacecode) const { #ifndef NDEBUG if (_chunk_size == 0) { TERRLN("Attempted to lookup net node by space code without first building the spatial index!"); exit(EXIT_FAILURE); } #endif return _spatial_index.at(spacecode / _chunk_size); } private: Config *_config; Camera* _camera; Image* _image; LightList* _lights; std::vector<Shader*> _shaders; std::vector<Texture*> _textures; std::vector<Material*> _materials; std::vector<Mesh*> _meshes; std::vector<NetNode*> _nodes; std::unordered_map<std::string, uint32_t> _material_name_index; std::vector<uint32_t> _spatial_index; std::vector<uint32_t> _emissive_index; uint64_t _chunk_size; }; } // namespace fr <commit_msg>Don't need NaiveIntersect anymore.<commit_after>#pragma once #include <cstdint> #include <cassert> #include <vector> #include <unordered_map> #include <string> #include <stdexcept> #include <functional> #include "utils/uncopyable.hpp" #include "utils/tout.hpp" namespace fr { struct Config; struct Camera; class Image; class LightList; struct Shader; struct Texture; struct Material; struct Mesh; class NetNode; struct FatRay; class Library : private Uncopyable { public: explicit Library(); ~Library(); // Configs... void StoreConfig(Config* config); inline Config* LookupConfig() const { return _config; } // Cameras... void StoreCamera(Camera* camera); inline Camera* LookupCamera() const { return _camera; } // Images... void StoreImage(Image* image); inline Image* LookupImage() const { return _image; } // Light lists... void StoreLightList(LightList* lights); inline LightList* LookupLightList() const { return _lights; } // Shaders... inline uint32_t NextShaderID() const { return _shaders.size(); } void StoreShader(uint32_t id, Shader* shader); inline Shader* LookupShader(uint32_t id) const { assert(id > 0); assert(id < _shaders.size()); return _shaders[id]; }; // Textures... inline uint32_t NextTextureID() const { return _textures.size(); } void StoreTexture(uint32_t id, Texture* texture); inline Texture* LookupTexture(uint32_t id) const { assert(id > 0); assert(id < _textures.size()); return _textures[id]; } // Materials... inline uint32_t NextMaterialID() const { return _materials.size(); } void StoreMaterial(uint32_t id, Material* material, const std::string& name); inline Material* LookupMaterial(uint32_t id) const { assert(id > 0); assert(id < _materials.size()); return _materials[id]; } inline uint32_t LookupMaterial(const std::string& name) const { uint32_t id = 0; try { id = _material_name_index.at(name); } catch (std::out_of_range& e) { id = 0; } return id; } // Meshes... inline uint32_t NextMeshID() const { return _meshes.size(); } void StoreMesh(uint32_t id, Mesh* mesh); inline Mesh* LookupMesh(uint32_t id) const { assert(id > 0); assert(id < _meshes.size()); return _meshes[id]; } void ForEachMesh(std::function<void (uint32_t id, Mesh* mesh)> func); void ForEachEmissiveMesh(std::function<void (uint32_t id, Mesh* mesh)> func); void Intersect(FatRay* ray, uint32_t me); // Net nodes... void StoreNetNode(uint32_t id, NetNode* node); inline NetNode* LookupNetNode(uint32_t id) const { assert(id > 0); assert(id < _nodes.size()); return _nodes[id]; } void ForEachNetNode(std::function<void (uint32_t id, NetNode* node)> func); template <typename RetType> std::vector<RetType> ForEachNetNode(std::function<RetType (uint32_t id, NetNode* node)> func) { std::vector<RetType> results(_nodes.size()); for (uint32_t id = 1; id < _nodes.size(); id++) { NetNode* node = _nodes[id]; if (node == nullptr) continue; RetType result = func(id, node); results.insert(results.begin() + id, result); } return results; } // Spatial index access for net nodes... void BuildSpatialIndex(); inline uint32_t LookupNetNodeBySpaceCode(uint64_t spacecode) const { #ifndef NDEBUG if (_chunk_size == 0) { TERRLN("Attempted to lookup net node by space code without first building the spatial index!"); exit(EXIT_FAILURE); } #endif return _spatial_index.at(spacecode / _chunk_size); } private: Config *_config; Camera* _camera; Image* _image; LightList* _lights; std::vector<Shader*> _shaders; std::vector<Texture*> _textures; std::vector<Material*> _materials; std::vector<Mesh*> _meshes; std::vector<NetNode*> _nodes; std::unordered_map<std::string, uint32_t> _material_name_index; std::vector<uint32_t> _spatial_index; std::vector<uint32_t> _emissive_index; uint64_t _chunk_size; }; } // namespace fr <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLChangeInfoContext.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: dvo $ $Date: 2001-01-24 16:49:51 $ * * 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 _XMLOFF_XMLCHANGEINFOCONTEXT_HXX #define _XMLOFF_XMLCHANGEINFOCONTEXT_HXX #ifndef _XMLOFF_XMLICTXT_HXX #include "xmlictxt.hxx" #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif namespace com { namespace sun { namespace star { namespace xml { namespace sax { class XAttributeList; } } } } } class XMLChangedRegionImportContext; /** * Import <office:change-info> elements as children of <text:changed-region> * elements. The attribute values will be passed to the enclosing * XMLChangedRegionImportContext (which has to be passed down in the * constructor). */ class XMLChangeInfoContext : public SvXMLImportContext { const ::rtl::OUString& rType; ::rtl::OUString sAuthor; ::rtl::OUString sDateTime; ::rtl::OUStringBuffer sCommentBuffer; XMLChangedRegionImportContext& rChangedRegion; public: TYPEINFO(); XMLChangeInfoContext( SvXMLImport& rImport, sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, XMLChangedRegionImportContext& rChangedRegion, const ::rtl::OUString& rChangeType); ~XMLChangeInfoContext(); virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList> & xAttrList); virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual void EndElement(); }; #endif <commit_msg>INTEGRATION: CWS oasis (1.2.288); FILE MERGED 2004/05/12 11:00:37 mib 1.2.288.1: - #i20153#: changed <office:annotation> and <office:change-info><commit_after>/************************************************************************* * * $RCSfile: XMLChangeInfoContext.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-07-13 08:31:07 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_XMLCHANGEINFOCONTEXT_HXX #define _XMLOFF_XMLCHANGEINFOCONTEXT_HXX #ifndef _XMLOFF_XMLICTXT_HXX #include "xmlictxt.hxx" #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif namespace com { namespace sun { namespace star { namespace xml { namespace sax { class XAttributeList; } } } } } class XMLChangedRegionImportContext; /** * Import <office:change-info> elements as children of <text:changed-region> * elements. The attribute values will be passed to the enclosing * XMLChangedRegionImportContext (which has to be passed down in the * constructor). */ class XMLChangeInfoContext : public SvXMLImportContext { const ::rtl::OUString& rType; ::rtl::OUStringBuffer sAuthorBuffer; ::rtl::OUStringBuffer sDateTimeBuffer; ::rtl::OUStringBuffer sCommentBuffer; XMLChangedRegionImportContext& rChangedRegion; public: TYPEINFO(); XMLChangeInfoContext( SvXMLImport& rImport, sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, XMLChangedRegionImportContext& rChangedRegion, const ::rtl::OUString& rChangeType); ~XMLChangeInfoContext(); virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList> & xAttrList); virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual void EndElement(); }; #endif <|endoftext|>
<commit_before><commit_msg>Protect X11 with ifdef USE_X11 in global commands test<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2016 Shanghai Jiao Tong University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * * For more about this software visit: * * http://ipads.se.sjtu.edu.cn/projects/wukong * */ #include <map> #include <boost/mpi.hpp> #include <iostream> #include "global.hpp" #include "conflict.hpp" #include "config.hpp" #include "bind.hpp" #include "mem.hpp" #ifdef USE_GPU #include "gpu_mem.hpp" #endif #include "string_server.hpp" #include "dgraph.hpp" #include "proxy.hpp" #include "console.hpp" #include "rdma.hpp" #include "data_statistic.hpp" #include "logger2.hpp" #include "engine/engine.hpp" #include "comm/adaptor.hpp" #include "unit.hpp" void *engine_thread(void *arg) { Engine *engine = (Engine *)arg; if (enable_binding && core_bindings.count(engine->tid) != 0) bind_to_core(core_bindings[engine->tid]); else bind_to_core(default_bindings[engine->tid % num_cores]); engine->run(); } void *proxy_thread(void *arg) { Proxy *proxy = (Proxy *)arg; if (enable_binding && core_bindings.count(proxy->tid) != 0) bind_to_core(core_bindings[proxy->tid]); else bind_to_core(default_bindings[proxy->tid % num_cores]); // run the builtin console run_console(proxy); } static void usage(char *fn) { cout << "usage: " << fn << " <config_fname> <host_fname> [options]" << endl; cout << "options:" << endl; cout << " -b binding : the file of core binding" << endl; cout << " -c command : the one-shot command" << endl; } int main(int argc, char *argv[]) { conflict_detector(); boost::mpi::environment env(argc, argv); boost::mpi::communicator world; int sid = world.rank(); // server ID if (argc < 3) { usage(argv[0]); exit(EXIT_FAILURE); } // load global configs load_config(string(argv[1]), world.size()); // set the address file of host/cluster string host_fname = std::string(argv[2]); // load CPU topology by hwloc load_node_topo(); logstream(LOG_INFO) << "#" << sid << ": has " << num_cores << " cores." << LOG_endl; int c; while ((c = getopt(argc - 2, argv + 2, "b:c:")) != -1) { switch (c) { case 'b': enable_binding = load_core_binding(optarg); break; case 'c': enable_oneshot = true; oneshot_cmd = optarg; break; default: usage(argv[0]); exit(EXIT_FAILURE); } } // allocate memory regions vector<RDMA::MemoryRegion> mrs; // rdma broadcast memory vector<Broadcast_Mem *> bc_mems; Broadcast_Mem *mb_mem = new Broadcast_Mem(global_num_servers, global_num_threads); bc_mems.push_back(mb_mem); // CPU (host) memory Mem *mem = new Mem(global_num_servers, global_num_threads, bc_mems); logstream(LOG_INFO) << "#" << sid << ": allocate " << B2GiB(mem->size()) << "GB memory" << LOG_endl; RDMA::MemoryRegion mr_cpu = { RDMA::MemType::CPU, mem->address(), mem->size(), mem }; mrs.push_back(mr_cpu); #ifdef USE_GPU // GPU (device) memory int devid = 0; // FIXME: it means one GPU device? GPUMem *gpu_mem = new GPUMem(devid, global_num_servers, global_num_gpus); logstream(LOG_INFO) << "#" << sid << ": allocate " << B2GiB(gpu_mem->size()) << "GB GPU memory" << LOG_endl; RDMA::MemoryRegion mr_gpu = { RDMA::MemType::GPU, gpu_mem->address(), gpu_mem->size(), gpu_mem }; mrs.push_back(mr_gpu); #endif // two additional threads, // one for broadcast master, another for broadcast slave int rdma_init_nthreads = global_num_threads + 2; // init RDMA devices and connections RDMA_init(global_num_servers, rdma_init_nthreads, sid, mrs, host_fname); // init communication RDMA_Adaptor *rdma_adaptor = new RDMA_Adaptor(sid, mrs, global_num_servers, global_num_threads); TCP_Adaptor *tcp_adaptor = new TCP_Adaptor(sid, host_fname, global_data_port_base, global_num_servers, global_num_threads); // init control communicaiton con_adaptor = new TCP_Adaptor(sid, host_fname, global_ctrl_port_base, global_num_servers, global_num_proxies); // load string server (read-only, shared by all proxies and all engines) String_Server str_server(global_input_folder); // load RDF graph (shared by all engines and proxies) DGraph dgraph(sid, mem, &str_server, global_input_folder); // prepare statistics for SPARQL optimizer data_statistic stat(sid); if (global_generate_statistics) { uint64_t t0 = timer::get_usec(); dgraph.generate_statistic(stat); uint64_t t1 = timer::get_usec(); logstream(LOG_EMPH) << "generate_statistic using time: " << t1 - t0 << "usec" << LOG_endl; stat.gather_stat(con_adaptor); } else { // use the dataset name by default string fname = global_input_folder + "/statfile"; stat.load_stat_from_file(fname, con_adaptor); } // create proxies and engines ASSERT(global_num_threads == global_num_proxies + global_num_engines); for (int tid = 0; tid < global_num_threads; tid++) { Adaptor *adaptor = new Adaptor(tid, tcp_adaptor, rdma_adaptor); // TID: proxy = [0, #proxies), engine = [#proxies, #proxies + #engines) if (tid < global_num_proxies) { Proxy *proxy = new Proxy(sid, tid, &str_server, &dgraph, adaptor, &stat); proxies.push_back(proxy); } else { Engine *engine = new Engine(sid, tid, &str_server, &dgraph, adaptor); engines.push_back(engine); } } // launch all proxies and engines pthread_t *threads = new pthread_t[global_num_threads]; for (int tid = 0; tid < global_num_threads; tid++) { // TID: proxy = [0, #proxies), engine = [#proxies, #proxies + #engines) if (tid < global_num_proxies) pthread_create(&(threads[tid]), NULL, proxy_thread, (void *)proxies[tid]); else pthread_create(&(threads[tid]), NULL, engine_thread, (void *)engines[tid - global_num_proxies]); } // wait to all threads termination for (size_t t = 0; t < global_num_threads; t++) { if (int rc = pthread_join(threads[t], NULL)) { logger(LOG_ERROR, "return code from pthread_join() is %d\n", rc); exit(-1); } } /// TODO: exit gracefully (properly call MPI_Init() and MPI_Finalize(), delete all objects) return 0; } <commit_msg>name refine<commit_after>/* * Copyright (c) 2016 Shanghai Jiao Tong University. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * * For more about this software visit: * * http://ipads.se.sjtu.edu.cn/projects/wukong * */ #include <map> #include <boost/mpi.hpp> #include <iostream> #include "global.hpp" #include "conflict.hpp" #include "config.hpp" #include "bind.hpp" #include "mem.hpp" #ifdef USE_GPU #include "gpu_mem.hpp" #endif #include "string_server.hpp" #include "dgraph.hpp" #include "proxy.hpp" #include "console.hpp" #include "rdma.hpp" #include "data_statistic.hpp" #include "logger2.hpp" #include "engine/engine.hpp" #include "comm/adaptor.hpp" #include "unit.hpp" void *engine_thread(void *arg) { Engine *engine = (Engine *)arg; if (enable_binding && core_bindings.count(engine->tid) != 0) bind_to_core(core_bindings[engine->tid]); else bind_to_core(default_bindings[engine->tid % num_cores]); engine->run(); } void *proxy_thread(void *arg) { Proxy *proxy = (Proxy *)arg; if (enable_binding && core_bindings.count(proxy->tid) != 0) bind_to_core(core_bindings[proxy->tid]); else bind_to_core(default_bindings[proxy->tid % num_cores]); // run the builtin console run_console(proxy); } static void usage(char *fn) { cout << "usage: " << fn << " <config_fname> <host_fname> [options]" << endl; cout << "options:" << endl; cout << " -b binding : the file of core binding" << endl; cout << " -c command : the one-shot command" << endl; } int main(int argc, char *argv[]) { conflict_detector(); boost::mpi::environment env(argc, argv); boost::mpi::communicator world; int sid = world.rank(); // server ID if (argc < 3) { usage(argv[0]); exit(EXIT_FAILURE); } // load global configs load_config(string(argv[1]), world.size()); // set the address file of host/cluster string host_fname = std::string(argv[2]); // load CPU topology by hwloc load_node_topo(); logstream(LOG_INFO) << "#" << sid << ": has " << num_cores << " cores." << LOG_endl; int c; while ((c = getopt(argc - 2, argv + 2, "b:c:")) != -1) { switch (c) { case 'b': enable_binding = load_core_binding(optarg); break; case 'c': enable_oneshot = true; oneshot_cmd = optarg; break; default: usage(argv[0]); exit(EXIT_FAILURE); } } // allocate memory regions vector<RDMA::MemoryRegion> mrs; // rdma broadcast memory vector<Broadcast_Mem *> bcast_mems; Broadcast_Mem *ss_bcast_mem = new Broadcast_Mem(global_num_servers, global_num_threads); bcast_mems.push_back(ss_bcast_mem); // CPU (host) memory Mem *mem = new Mem(global_num_servers, global_num_threads, bcast_mems); logstream(LOG_INFO) << "#" << sid << ": allocate " << B2GiB(mem->size()) << "GB memory" << LOG_endl; RDMA::MemoryRegion mr_cpu = { RDMA::MemType::CPU, mem->address(), mem->size(), mem }; mrs.push_back(mr_cpu); #ifdef USE_GPU // GPU (device) memory int devid = 0; // FIXME: it means one GPU device? GPUMem *gpu_mem = new GPUMem(devid, global_num_servers, global_num_gpus); logstream(LOG_INFO) << "#" << sid << ": allocate " << B2GiB(gpu_mem->size()) << "GB GPU memory" << LOG_endl; RDMA::MemoryRegion mr_gpu = { RDMA::MemType::GPU, gpu_mem->address(), gpu_mem->size(), gpu_mem }; mrs.push_back(mr_gpu); #endif // RDMA full-link communication int flink_nthreads = global_num_proxies + global_num_engines; // RDMA broadcast communication int bcast_nthreads = 2; int rdma_init_nthreads = flink_nthreads + bcast_nthreads; // init RDMA devices and connections RDMA_init(global_num_servers, rdma_init_nthreads, sid, mrs, host_fname); // init communication RDMA_Adaptor *rdma_adaptor = new RDMA_Adaptor(sid, mrs, global_num_servers, global_num_threads); TCP_Adaptor *tcp_adaptor = new TCP_Adaptor(sid, host_fname, global_data_port_base, global_num_servers, global_num_threads); // init control communicaiton con_adaptor = new TCP_Adaptor(sid, host_fname, global_ctrl_port_base, global_num_servers, global_num_proxies); // load string server (read-only, shared by all proxies and all engines) String_Server str_server(global_input_folder); // load RDF graph (shared by all engines and proxies) DGraph dgraph(sid, mem, &str_server, global_input_folder); // prepare statistics for SPARQL optimizer data_statistic stat(sid); if (global_generate_statistics) { uint64_t t0 = timer::get_usec(); dgraph.generate_statistic(stat); uint64_t t1 = timer::get_usec(); logstream(LOG_EMPH) << "generate_statistic using time: " << t1 - t0 << "usec" << LOG_endl; stat.gather_stat(con_adaptor); } else { // use the dataset name by default string fname = global_input_folder + "/statfile"; stat.load_stat_from_file(fname, con_adaptor); } // create proxies and engines ASSERT(global_num_threads == global_num_proxies + global_num_engines); for (int tid = 0; tid < global_num_threads; tid++) { Adaptor *adaptor = new Adaptor(tid, tcp_adaptor, rdma_adaptor); // TID: proxy = [0, #proxies), engine = [#proxies, #proxies + #engines) if (tid < global_num_proxies) { Proxy *proxy = new Proxy(sid, tid, &str_server, &dgraph, adaptor, &stat); proxies.push_back(proxy); } else { Engine *engine = new Engine(sid, tid, &str_server, &dgraph, adaptor); engines.push_back(engine); } } // launch all proxies and engines pthread_t *threads = new pthread_t[global_num_threads]; for (int tid = 0; tid < global_num_threads; tid++) { // TID: proxy = [0, #proxies), engine = [#proxies, #proxies + #engines) if (tid < global_num_proxies) pthread_create(&(threads[tid]), NULL, proxy_thread, (void *)proxies[tid]); else pthread_create(&(threads[tid]), NULL, engine_thread, (void *)engines[tid - global_num_proxies]); } // wait to all threads termination for (size_t t = 0; t < global_num_threads; t++) { if (int rc = pthread_join(threads[t], NULL)) { logger(LOG_ERROR, "return code from pthread_join() is %d\n", rc); exit(-1); } } /// TODO: exit gracefully (properly call MPI_Init() and MPI_Finalize(), delete all objects) return 0; } <|endoftext|>
<commit_before>//===-- UnixSignals.cpp -----------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Target/UnixSignals.h" #include "Plugins/Process/Utility/FreeBSDSignals.h" #include "Plugins/Process/Utility/LinuxSignals.h" #include "Plugins/Process/Utility/MipsLinuxSignals.h" #include "Plugins/Process/Utility/NetBSDSignals.h" #include "lldb/Host/StringConvert.h" #include "lldb/Utility/ArchSpec.h" using namespace lldb_private; UnixSignals::Signal::Signal(const char *name, bool default_suppress, bool default_stop, bool default_notify, const char *description, const char *alias) : m_name(name), m_alias(alias), m_description(), m_suppress(default_suppress), m_stop(default_stop), m_notify(default_notify) { if (description) m_description.assign(description); } lldb::UnixSignalsSP UnixSignals::Create(const ArchSpec &arch) { const auto &triple = arch.GetTriple(); switch (triple.getOS()) { case llvm::Triple::Linux: { switch (triple.getArch()) { case llvm::Triple::mips: case llvm::Triple::mipsel: case llvm::Triple::mips64: case llvm::Triple::mips64el: return std::make_shared<MipsLinuxSignals>(); default: return std::make_shared<LinuxSignals>(); } } case llvm::Triple::FreeBSD: case llvm::Triple::OpenBSD: return std::make_shared<FreeBSDSignals>(); case llvm::Triple::NetBSD: return std::make_shared<NetBSDSignals>(); default: return std::make_shared<UnixSignals>(); } } //---------------------------------------------------------------------- // UnixSignals constructor //---------------------------------------------------------------------- UnixSignals::UnixSignals() { Reset(); } UnixSignals::UnixSignals(const UnixSignals &rhs) : m_signals(rhs.m_signals) {} UnixSignals::~UnixSignals() = default; void UnixSignals::Reset() { // This builds one standard set of Unix Signals. If yours aren't quite in // this order, you can either subclass this class, and use Add & Remove to // change them // or you can subclass and build them afresh in your constructor; // // Note: the signals below are the Darwin signals. Do not change these! m_signals.clear(); // SIGNO NAME SUPPRESS STOP NOTIFY DESCRIPTION // ====== ============ ======== ====== ====== // =================================================== AddSignal(1, "SIGHUP", false, true, true, "hangup"); AddSignal(2, "SIGINT", true, true, true, "interrupt"); AddSignal(3, "SIGQUIT", false, true, true, "quit"); AddSignal(4, "SIGILL", false, true, true, "illegal instruction"); AddSignal(5, "SIGTRAP", true, true, true, "trace trap (not reset when caught)"); AddSignal(6, "SIGABRT", false, true, true, "abort()"); AddSignal(7, "SIGEMT", false, true, true, "pollable event"); AddSignal(8, "SIGFPE", false, true, true, "floating point exception"); AddSignal(9, "SIGKILL", false, true, true, "kill"); AddSignal(10, "SIGBUS", false, true, true, "bus error"); AddSignal(11, "SIGSEGV", false, true, true, "segmentation violation"); AddSignal(12, "SIGSYS", false, true, true, "bad argument to system call"); AddSignal(13, "SIGPIPE", false, true, true, "write on a pipe with no one to read it"); AddSignal(14, "SIGALRM", false, false, false, "alarm clock"); AddSignal(15, "SIGTERM", false, true, true, "software termination signal from kill"); AddSignal(16, "SIGURG", false, false, false, "urgent condition on IO channel"); AddSignal(17, "SIGSTOP", true, true, true, "sendable stop signal not from tty"); AddSignal(18, "SIGTSTP", false, true, true, "stop signal from tty"); AddSignal(19, "SIGCONT", false, true, true, "continue a stopped process"); AddSignal(20, "SIGCHLD", false, false, false, "to parent on child stop or exit"); AddSignal(21, "SIGTTIN", false, true, true, "to readers process group upon background tty read"); AddSignal(22, "SIGTTOU", false, true, true, "to readers process group upon background tty write"); AddSignal(23, "SIGIO", false, false, false, "input/output possible signal"); AddSignal(24, "SIGXCPU", false, true, true, "exceeded CPU time limit"); AddSignal(25, "SIGXFSZ", false, true, true, "exceeded file size limit"); AddSignal(26, "SIGVTALRM", false, false, false, "virtual time alarm"); AddSignal(27, "SIGPROF", false, false, false, "profiling time alarm"); AddSignal(28, "SIGWINCH", false, false, false, "window size changes"); AddSignal(29, "SIGINFO", false, true, true, "information request"); AddSignal(30, "SIGUSR1", false, true, true, "user defined signal 1"); AddSignal(31, "SIGUSR2", false, true, true, "user defined signal 2"); } void UnixSignals::AddSignal(int signo, const char *name, bool default_suppress, bool default_stop, bool default_notify, const char *description, const char *alias) { Signal new_signal(name, default_suppress, default_stop, default_notify, description, alias); m_signals.insert(std::make_pair(signo, new_signal)); ++m_version; } void UnixSignals::RemoveSignal(int signo) { collection::iterator pos = m_signals.find(signo); if (pos != m_signals.end()) m_signals.erase(pos); ++m_version; } const char *UnixSignals::GetSignalAsCString(int signo) const { collection::const_iterator pos = m_signals.find(signo); if (pos == m_signals.end()) return nullptr; else return pos->second.m_name.GetCString(); } bool UnixSignals::SignalIsValid(int32_t signo) const { return m_signals.find(signo) != m_signals.end(); } ConstString UnixSignals::GetShortName(ConstString name) const { if (name) { const char *signame = name.AsCString(); return ConstString(signame + 3); // Remove "SIG" from name } return name; } int32_t UnixSignals::GetSignalNumberFromName(const char *name) const { ConstString const_name(name); collection::const_iterator pos, end = m_signals.end(); for (pos = m_signals.begin(); pos != end; pos++) { if ((const_name == pos->second.m_name) || (const_name == pos->second.m_alias) || (const_name == GetShortName(pos->second.m_name)) || (const_name == GetShortName(pos->second.m_alias))) return pos->first; } const int32_t signo = StringConvert::ToSInt32(name, LLDB_INVALID_SIGNAL_NUMBER, 0); if (signo != LLDB_INVALID_SIGNAL_NUMBER) return signo; return LLDB_INVALID_SIGNAL_NUMBER; } int32_t UnixSignals::GetFirstSignalNumber() const { if (m_signals.empty()) return LLDB_INVALID_SIGNAL_NUMBER; return (*m_signals.begin()).first; } int32_t UnixSignals::GetNextSignalNumber(int32_t current_signal) const { collection::const_iterator pos = m_signals.find(current_signal); collection::const_iterator end = m_signals.end(); if (pos == end) return LLDB_INVALID_SIGNAL_NUMBER; else { pos++; if (pos == end) return LLDB_INVALID_SIGNAL_NUMBER; else return pos->first; } } const char *UnixSignals::GetSignalInfo(int32_t signo, bool &should_suppress, bool &should_stop, bool &should_notify) const { collection::const_iterator pos = m_signals.find(signo); if (pos == m_signals.end()) return nullptr; else { const Signal &signal = pos->second; should_suppress = signal.m_suppress; should_stop = signal.m_stop; should_notify = signal.m_notify; return signal.m_name.AsCString(""); } } bool UnixSignals::GetShouldSuppress(int signo) const { collection::const_iterator pos = m_signals.find(signo); if (pos != m_signals.end()) return pos->second.m_suppress; return false; } bool UnixSignals::SetShouldSuppress(int signo, bool value) { collection::iterator pos = m_signals.find(signo); if (pos != m_signals.end()) { pos->second.m_suppress = value; ++m_version; return true; } return false; } bool UnixSignals::SetShouldSuppress(const char *signal_name, bool value) { const int32_t signo = GetSignalNumberFromName(signal_name); if (signo != LLDB_INVALID_SIGNAL_NUMBER) return SetShouldSuppress(signo, value); return false; } bool UnixSignals::GetShouldStop(int signo) const { collection::const_iterator pos = m_signals.find(signo); if (pos != m_signals.end()) return pos->second.m_stop; return false; } bool UnixSignals::SetShouldStop(int signo, bool value) { collection::iterator pos = m_signals.find(signo); if (pos != m_signals.end()) { pos->second.m_stop = value; ++m_version; return true; } return false; } bool UnixSignals::SetShouldStop(const char *signal_name, bool value) { const int32_t signo = GetSignalNumberFromName(signal_name); if (signo != LLDB_INVALID_SIGNAL_NUMBER) return SetShouldStop(signo, value); return false; } bool UnixSignals::GetShouldNotify(int signo) const { collection::const_iterator pos = m_signals.find(signo); if (pos != m_signals.end()) return pos->second.m_notify; return false; } bool UnixSignals::SetShouldNotify(int signo, bool value) { collection::iterator pos = m_signals.find(signo); if (pos != m_signals.end()) { pos->second.m_notify = value; ++m_version; return true; } return false; } bool UnixSignals::SetShouldNotify(const char *signal_name, bool value) { const int32_t signo = GetSignalNumberFromName(signal_name); if (signo != LLDB_INVALID_SIGNAL_NUMBER) return SetShouldNotify(signo, value); return false; } int32_t UnixSignals::GetNumSignals() const { return m_signals.size(); } int32_t UnixSignals::GetSignalAtIndex(int32_t index) const { if (index < 0 || m_signals.size() <= static_cast<size_t>(index)) return LLDB_INVALID_SIGNAL_NUMBER; auto it = m_signals.begin(); std::advance(it, index); return it->first; } uint64_t UnixSignals::GetVersion() const { return m_version; } std::vector<int32_t> UnixSignals::GetFilteredSignals(llvm::Optional<bool> should_suppress, llvm::Optional<bool> should_stop, llvm::Optional<bool> should_notify) { std::vector<int32_t> result; for (int32_t signo = GetFirstSignalNumber(); signo != LLDB_INVALID_SIGNAL_NUMBER; signo = GetNextSignalNumber(signo)) { bool signal_suppress = false; bool signal_stop = false; bool signal_notify = false; GetSignalInfo(signo, signal_suppress, signal_stop, signal_notify); // If any of filtering conditions are not met, we move on to the next // signal. if (should_suppress.hasValue() && signal_suppress != should_suppress.getValue()) continue; if (should_stop.hasValue() && signal_stop != should_stop.getValue()) continue; if (should_notify.hasValue() && signal_notify != should_notify.getValue()) continue; result.push_back(signo); } return result; } <commit_msg>Change the default handling for SIGPIPE to pass/,no-stop/no-notify.<commit_after>//===-- UnixSignals.cpp -----------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Target/UnixSignals.h" #include "Plugins/Process/Utility/FreeBSDSignals.h" #include "Plugins/Process/Utility/LinuxSignals.h" #include "Plugins/Process/Utility/MipsLinuxSignals.h" #include "Plugins/Process/Utility/NetBSDSignals.h" #include "lldb/Host/StringConvert.h" #include "lldb/Utility/ArchSpec.h" using namespace lldb_private; UnixSignals::Signal::Signal(const char *name, bool default_suppress, bool default_stop, bool default_notify, const char *description, const char *alias) : m_name(name), m_alias(alias), m_description(), m_suppress(default_suppress), m_stop(default_stop), m_notify(default_notify) { if (description) m_description.assign(description); } lldb::UnixSignalsSP UnixSignals::Create(const ArchSpec &arch) { const auto &triple = arch.GetTriple(); switch (triple.getOS()) { case llvm::Triple::Linux: { switch (triple.getArch()) { case llvm::Triple::mips: case llvm::Triple::mipsel: case llvm::Triple::mips64: case llvm::Triple::mips64el: return std::make_shared<MipsLinuxSignals>(); default: return std::make_shared<LinuxSignals>(); } } case llvm::Triple::FreeBSD: case llvm::Triple::OpenBSD: return std::make_shared<FreeBSDSignals>(); case llvm::Triple::NetBSD: return std::make_shared<NetBSDSignals>(); default: return std::make_shared<UnixSignals>(); } } //---------------------------------------------------------------------- // UnixSignals constructor //---------------------------------------------------------------------- UnixSignals::UnixSignals() { Reset(); } UnixSignals::UnixSignals(const UnixSignals &rhs) : m_signals(rhs.m_signals) {} UnixSignals::~UnixSignals() = default; void UnixSignals::Reset() { // This builds one standard set of Unix Signals. If yours aren't quite in // this order, you can either subclass this class, and use Add & Remove to // change them // or you can subclass and build them afresh in your constructor; // // Note: the signals below are the Darwin signals. Do not change these! m_signals.clear(); // SIGNO NAME SUPPRESS STOP NOTIFY DESCRIPTION // ====== ============ ======== ====== ====== // =================================================== AddSignal(1, "SIGHUP", false, true, true, "hangup"); AddSignal(2, "SIGINT", true, true, true, "interrupt"); AddSignal(3, "SIGQUIT", false, true, true, "quit"); AddSignal(4, "SIGILL", false, true, true, "illegal instruction"); AddSignal(5, "SIGTRAP", true, true, true, "trace trap (not reset when caught)"); AddSignal(6, "SIGABRT", false, true, true, "abort()"); AddSignal(7, "SIGEMT", false, true, true, "pollable event"); AddSignal(8, "SIGFPE", false, true, true, "floating point exception"); AddSignal(9, "SIGKILL", false, true, true, "kill"); AddSignal(10, "SIGBUS", false, true, true, "bus error"); AddSignal(11, "SIGSEGV", false, true, true, "segmentation violation"); AddSignal(12, "SIGSYS", false, true, true, "bad argument to system call"); AddSignal(13, "SIGPIPE", false, false, false, "write on a pipe with no one to read it"); AddSignal(14, "SIGALRM", false, false, false, "alarm clock"); AddSignal(15, "SIGTERM", false, true, true, "software termination signal from kill"); AddSignal(16, "SIGURG", false, false, false, "urgent condition on IO channel"); AddSignal(17, "SIGSTOP", true, true, true, "sendable stop signal not from tty"); AddSignal(18, "SIGTSTP", false, true, true, "stop signal from tty"); AddSignal(19, "SIGCONT", false, true, true, "continue a stopped process"); AddSignal(20, "SIGCHLD", false, false, false, "to parent on child stop or exit"); AddSignal(21, "SIGTTIN", false, true, true, "to readers process group upon background tty read"); AddSignal(22, "SIGTTOU", false, true, true, "to readers process group upon background tty write"); AddSignal(23, "SIGIO", false, false, false, "input/output possible signal"); AddSignal(24, "SIGXCPU", false, true, true, "exceeded CPU time limit"); AddSignal(25, "SIGXFSZ", false, true, true, "exceeded file size limit"); AddSignal(26, "SIGVTALRM", false, false, false, "virtual time alarm"); AddSignal(27, "SIGPROF", false, false, false, "profiling time alarm"); AddSignal(28, "SIGWINCH", false, false, false, "window size changes"); AddSignal(29, "SIGINFO", false, true, true, "information request"); AddSignal(30, "SIGUSR1", false, true, true, "user defined signal 1"); AddSignal(31, "SIGUSR2", false, true, true, "user defined signal 2"); } void UnixSignals::AddSignal(int signo, const char *name, bool default_suppress, bool default_stop, bool default_notify, const char *description, const char *alias) { Signal new_signal(name, default_suppress, default_stop, default_notify, description, alias); m_signals.insert(std::make_pair(signo, new_signal)); ++m_version; } void UnixSignals::RemoveSignal(int signo) { collection::iterator pos = m_signals.find(signo); if (pos != m_signals.end()) m_signals.erase(pos); ++m_version; } const char *UnixSignals::GetSignalAsCString(int signo) const { collection::const_iterator pos = m_signals.find(signo); if (pos == m_signals.end()) return nullptr; else return pos->second.m_name.GetCString(); } bool UnixSignals::SignalIsValid(int32_t signo) const { return m_signals.find(signo) != m_signals.end(); } ConstString UnixSignals::GetShortName(ConstString name) const { if (name) { const char *signame = name.AsCString(); return ConstString(signame + 3); // Remove "SIG" from name } return name; } int32_t UnixSignals::GetSignalNumberFromName(const char *name) const { ConstString const_name(name); collection::const_iterator pos, end = m_signals.end(); for (pos = m_signals.begin(); pos != end; pos++) { if ((const_name == pos->second.m_name) || (const_name == pos->second.m_alias) || (const_name == GetShortName(pos->second.m_name)) || (const_name == GetShortName(pos->second.m_alias))) return pos->first; } const int32_t signo = StringConvert::ToSInt32(name, LLDB_INVALID_SIGNAL_NUMBER, 0); if (signo != LLDB_INVALID_SIGNAL_NUMBER) return signo; return LLDB_INVALID_SIGNAL_NUMBER; } int32_t UnixSignals::GetFirstSignalNumber() const { if (m_signals.empty()) return LLDB_INVALID_SIGNAL_NUMBER; return (*m_signals.begin()).first; } int32_t UnixSignals::GetNextSignalNumber(int32_t current_signal) const { collection::const_iterator pos = m_signals.find(current_signal); collection::const_iterator end = m_signals.end(); if (pos == end) return LLDB_INVALID_SIGNAL_NUMBER; else { pos++; if (pos == end) return LLDB_INVALID_SIGNAL_NUMBER; else return pos->first; } } const char *UnixSignals::GetSignalInfo(int32_t signo, bool &should_suppress, bool &should_stop, bool &should_notify) const { collection::const_iterator pos = m_signals.find(signo); if (pos == m_signals.end()) return nullptr; else { const Signal &signal = pos->second; should_suppress = signal.m_suppress; should_stop = signal.m_stop; should_notify = signal.m_notify; return signal.m_name.AsCString(""); } } bool UnixSignals::GetShouldSuppress(int signo) const { collection::const_iterator pos = m_signals.find(signo); if (pos != m_signals.end()) return pos->second.m_suppress; return false; } bool UnixSignals::SetShouldSuppress(int signo, bool value) { collection::iterator pos = m_signals.find(signo); if (pos != m_signals.end()) { pos->second.m_suppress = value; ++m_version; return true; } return false; } bool UnixSignals::SetShouldSuppress(const char *signal_name, bool value) { const int32_t signo = GetSignalNumberFromName(signal_name); if (signo != LLDB_INVALID_SIGNAL_NUMBER) return SetShouldSuppress(signo, value); return false; } bool UnixSignals::GetShouldStop(int signo) const { collection::const_iterator pos = m_signals.find(signo); if (pos != m_signals.end()) return pos->second.m_stop; return false; } bool UnixSignals::SetShouldStop(int signo, bool value) { collection::iterator pos = m_signals.find(signo); if (pos != m_signals.end()) { pos->second.m_stop = value; ++m_version; return true; } return false; } bool UnixSignals::SetShouldStop(const char *signal_name, bool value) { const int32_t signo = GetSignalNumberFromName(signal_name); if (signo != LLDB_INVALID_SIGNAL_NUMBER) return SetShouldStop(signo, value); return false; } bool UnixSignals::GetShouldNotify(int signo) const { collection::const_iterator pos = m_signals.find(signo); if (pos != m_signals.end()) return pos->second.m_notify; return false; } bool UnixSignals::SetShouldNotify(int signo, bool value) { collection::iterator pos = m_signals.find(signo); if (pos != m_signals.end()) { pos->second.m_notify = value; ++m_version; return true; } return false; } bool UnixSignals::SetShouldNotify(const char *signal_name, bool value) { const int32_t signo = GetSignalNumberFromName(signal_name); if (signo != LLDB_INVALID_SIGNAL_NUMBER) return SetShouldNotify(signo, value); return false; } int32_t UnixSignals::GetNumSignals() const { return m_signals.size(); } int32_t UnixSignals::GetSignalAtIndex(int32_t index) const { if (index < 0 || m_signals.size() <= static_cast<size_t>(index)) return LLDB_INVALID_SIGNAL_NUMBER; auto it = m_signals.begin(); std::advance(it, index); return it->first; } uint64_t UnixSignals::GetVersion() const { return m_version; } std::vector<int32_t> UnixSignals::GetFilteredSignals(llvm::Optional<bool> should_suppress, llvm::Optional<bool> should_stop, llvm::Optional<bool> should_notify) { std::vector<int32_t> result; for (int32_t signo = GetFirstSignalNumber(); signo != LLDB_INVALID_SIGNAL_NUMBER; signo = GetNextSignalNumber(signo)) { bool signal_suppress = false; bool signal_stop = false; bool signal_notify = false; GetSignalInfo(signo, signal_suppress, signal_stop, signal_notify); // If any of filtering conditions are not met, we move on to the next // signal. if (should_suppress.hasValue() && signal_suppress != should_suppress.getValue()) continue; if (should_stop.hasValue() && signal_stop != should_stop.getValue()) continue; if (should_notify.hasValue() && signal_notify != should_notify.getValue()) continue; result.push_back(signo); } return result; } <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright 2015 Cloudius Systems */ #include <cmath> #include <seastar/core/reactor.hh> #include <seastar/core/app-template.hh> #include <seastar/core/sleep.hh> #include <seastar/net/dns.hh> #include "tls_echo_server.hh" using namespace seastar; namespace bpo = boost::program_options; int main(int ac, char** av) { app_template app; app.add_options() ("port", bpo::value<uint16_t>()->default_value(10000), "Server port") ("address", bpo::value<std::string>()->default_value("127.0.0.1"), "Server address") ("cert,c", bpo::value<std::string>()->required(), "Server certificate file") ("key,k", bpo::value<std::string>()->required(), "Certificate key") ("verbose,v", bpo::value<bool>()->default_value(false)->implicit_value(true), "Verbose") ; return app.run_deprecated(ac, av, [&] { auto&& config = app.configuration(); uint16_t port = config["port"].as<uint16_t>(); auto crt = config["cert"].as<std::string>(); auto key = config["key"].as<std::string>(); auto addr = config["address"].as<std::string>(); auto verbose = config["verbose"].as<bool>(); std::cout << "Starting..." << std::endl; return net::dns::resolve_name(addr).then([=](net::inet_address a) { ipv4_addr ia(a, port); auto server = ::make_shared<seastar::sharded<echoserver>>(); return server->start(verbose).then([=]() { return server->invoke_on_all(&echoserver::listen, socket_address(ia), sstring(crt), sstring(key), tls::client_auth::NONE); }).handle_exception([=](auto e) { std::cerr << "Error: " << e << std::endl; engine().exit(1); }).then([=] { std::cout << "TLS echo server running at " << addr << ":" << port << std::endl; engine().at_exit([server] { return server->stop(); }); }); }); }); } <commit_msg>tls_echo_server_demo: main: capture server post stop()<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright 2015 Cloudius Systems */ #include <cmath> #include <seastar/core/reactor.hh> #include <seastar/core/app-template.hh> #include <seastar/core/sleep.hh> #include <seastar/net/dns.hh> #include "tls_echo_server.hh" using namespace seastar; namespace bpo = boost::program_options; int main(int ac, char** av) { app_template app; app.add_options() ("port", bpo::value<uint16_t>()->default_value(10000), "Server port") ("address", bpo::value<std::string>()->default_value("127.0.0.1"), "Server address") ("cert,c", bpo::value<std::string>()->required(), "Server certificate file") ("key,k", bpo::value<std::string>()->required(), "Certificate key") ("verbose,v", bpo::value<bool>()->default_value(false)->implicit_value(true), "Verbose") ; return app.run_deprecated(ac, av, [&] { auto&& config = app.configuration(); uint16_t port = config["port"].as<uint16_t>(); auto crt = config["cert"].as<std::string>(); auto key = config["key"].as<std::string>(); auto addr = config["address"].as<std::string>(); auto verbose = config["verbose"].as<bool>(); std::cout << "Starting..." << std::endl; return net::dns::resolve_name(addr).then([=](net::inet_address a) { ipv4_addr ia(a, port); auto server = ::make_shared<seastar::sharded<echoserver>>(); return server->start(verbose).then([=]() { return server->invoke_on_all(&echoserver::listen, socket_address(ia), sstring(crt), sstring(key), tls::client_auth::NONE); }).handle_exception([=](auto e) { std::cerr << "Error: " << e << std::endl; engine().exit(1); }).then([=] { std::cout << "TLS echo server running at " << addr << ":" << port << std::endl; engine().at_exit([server] { return server->stop().finally([server] {}); }); }); }); }); } <|endoftext|>
<commit_before>#ifndef slic3r_MeshUtils_hpp_ #define slic3r_MeshUtils_hpp_ #include "libslic3r/Point.hpp" #include "libslic3r/Geometry.hpp" #include <cfloat> namespace Slic3r { class TriangleMesh; class TriangleMeshSlicer; namespace GUI { class Camera; class ClippingPlane { double m_data[4]; public: ClippingPlane() { m_data[0] = 0.0; m_data[1] = 0.0; m_data[2] = 1.0; m_data[3] = 0.0; } ClippingPlane(const Vec3d& direction, double offset) { Vec3d norm_dir = direction.normalized(); m_data[0] = norm_dir(0); m_data[1] = norm_dir(1); m_data[2] = norm_dir(2); m_data[3] = offset; } bool operator==(const ClippingPlane& cp) const { return m_data[0]==cp.m_data[0] && m_data[1]==cp.m_data[1] && m_data[2]==cp.m_data[2] && m_data[3]==cp.m_data[3]; } bool operator!=(const ClippingPlane& cp) const { return ! (*this==cp); } double distance(const Vec3d& pt) const { assert(is_approx(get_normal().norm(), 1.)); return (-get_normal().dot(pt) + m_data[3]); } void set_normal(const Vec3d& normal) { for (size_t i=0; i<3; ++i) m_data[i] = normal(i); } void set_offset(double offset) { m_data[3] = offset; } Vec3d get_normal() const { return Vec3d(m_data[0], m_data[1], m_data[2]); } bool is_active() const { return m_data[3] != DBL_MAX; } static ClippingPlane ClipsNothing() { return ClippingPlane(Vec3d(0., 0., 1.), DBL_MAX); } const double* get_data() const { return m_data; } // Serialization through cereal library template <class Archive> void serialize( Archive & ar ) { ar( m_data[0], m_data[1], m_data[2], m_data[3] ); } }; class MeshClipper { public: void set_plane(const ClippingPlane& plane); void set_mesh(const TriangleMesh& mesh); void set_transformation(const Geometry::Transformation& trafo); const std::vector<Vec3f>& get_triangles(); private: void recalculate_triangles(); Geometry::Transformation m_trafo; const TriangleMesh* m_mesh = nullptr; ClippingPlane m_plane; std::vector<Vec2f> m_triangles2d; std::vector<Vec3f> m_triangles3d; bool m_triangles_valid = false; std::unique_ptr<TriangleMeshSlicer> m_tms; }; class MeshRaycaster { public: MeshRaycaster(const TriangleMesh& mesh); ~MeshRaycaster(); void set_transformation(const Geometry::Transformation& trafo); void set_camera(const Camera& camera); bool unproject_on_mesh(const Vec2d& mouse_pos, const Transform3d& trafo, const Camera& camera, std::vector<Vec3f>* positions = nullptr, std::vector<Vec3f>* normals = nullptr) const; std::vector<unsigned> get_unobscured_idxs(const Geometry::Transformation& trafo, const Camera& camera, const std::vector<Vec3f>& points, std::function<bool(const Vec3f&)> fn_ignore_hit) const; Vec3f get_closest_point(const Vec3f& point, Vec3f* normal = nullptr) const; private: // PIMPL wrapper around igl::AABB so I don't have to include the header-only IGL here class AABBWrapper; AABBWrapper* m_AABB_wrapper; const TriangleMesh* m_mesh = nullptr; }; } // namespace GUI } // namespace Slic3r #endif // slic3r_MeshUtils_hpp_ <commit_msg>Fixed typo<commit_after>#ifndef slic3r_MeshUtils_hpp_ #define slic3r_MeshUtils_hpp_ #include "libslic3r/Point.hpp" #include "libslic3r/Geometry.hpp" #include <cfloat> namespace Slic3r { class TriangleMesh; class TriangleMeshSlicer; namespace GUI { struct Camera; class ClippingPlane { double m_data[4]; public: ClippingPlane() { m_data[0] = 0.0; m_data[1] = 0.0; m_data[2] = 1.0; m_data[3] = 0.0; } ClippingPlane(const Vec3d& direction, double offset) { Vec3d norm_dir = direction.normalized(); m_data[0] = norm_dir(0); m_data[1] = norm_dir(1); m_data[2] = norm_dir(2); m_data[3] = offset; } bool operator==(const ClippingPlane& cp) const { return m_data[0]==cp.m_data[0] && m_data[1]==cp.m_data[1] && m_data[2]==cp.m_data[2] && m_data[3]==cp.m_data[3]; } bool operator!=(const ClippingPlane& cp) const { return ! (*this==cp); } double distance(const Vec3d& pt) const { assert(is_approx(get_normal().norm(), 1.)); return (-get_normal().dot(pt) + m_data[3]); } void set_normal(const Vec3d& normal) { for (size_t i=0; i<3; ++i) m_data[i] = normal(i); } void set_offset(double offset) { m_data[3] = offset; } Vec3d get_normal() const { return Vec3d(m_data[0], m_data[1], m_data[2]); } bool is_active() const { return m_data[3] != DBL_MAX; } static ClippingPlane ClipsNothing() { return ClippingPlane(Vec3d(0., 0., 1.), DBL_MAX); } const double* get_data() const { return m_data; } // Serialization through cereal library template <class Archive> void serialize( Archive & ar ) { ar( m_data[0], m_data[1], m_data[2], m_data[3] ); } }; class MeshClipper { public: void set_plane(const ClippingPlane& plane); void set_mesh(const TriangleMesh& mesh); void set_transformation(const Geometry::Transformation& trafo); const std::vector<Vec3f>& get_triangles(); private: void recalculate_triangles(); Geometry::Transformation m_trafo; const TriangleMesh* m_mesh = nullptr; ClippingPlane m_plane; std::vector<Vec2f> m_triangles2d; std::vector<Vec3f> m_triangles3d; bool m_triangles_valid = false; std::unique_ptr<TriangleMeshSlicer> m_tms; }; class MeshRaycaster { public: MeshRaycaster(const TriangleMesh& mesh); ~MeshRaycaster(); void set_transformation(const Geometry::Transformation& trafo); void set_camera(const Camera& camera); bool unproject_on_mesh(const Vec2d& mouse_pos, const Transform3d& trafo, const Camera& camera, std::vector<Vec3f>* positions = nullptr, std::vector<Vec3f>* normals = nullptr) const; std::vector<unsigned> get_unobscured_idxs(const Geometry::Transformation& trafo, const Camera& camera, const std::vector<Vec3f>& points, std::function<bool(const Vec3f&)> fn_ignore_hit) const; Vec3f get_closest_point(const Vec3f& point, Vec3f* normal = nullptr) const; private: // PIMPL wrapper around igl::AABB so I don't have to include the header-only IGL here class AABBWrapper; AABBWrapper* m_AABB_wrapper; const TriangleMesh* m_mesh = nullptr; }; } // namespace GUI } // namespace Slic3r #endif // slic3r_MeshUtils_hpp_ <|endoftext|>
<commit_before>#include "BluPrivatePCH.h" UBluEye::UBluEye(const class FObjectInitializer& PCIP) : Super(PCIP) { Width = 800; Height = 600; bIsTransparent = false; } void UBluEye::init() { /** * We don't want this running in editor unless it's PIE * If we don't check this, CEF will spawn infinit processes with widget components **/ if (GEngine) { if (GEngine->IsEditor() && !GWorld->IsPlayInEditor()) { UE_LOG(LogBlu, Log, TEXT("Notice: not playing - Component Will Not Initialize")); return; } } browserSettings.universal_access_from_file_urls = STATE_ENABLED; browserSettings.file_access_from_file_urls = STATE_ENABLED; info.width = Width; info.height = Height; // Set the texture update region (for now the whole image) RenderParams.UpdateRegions = new FUpdateTextureRegion2D(0, 0, 0, 0, Width, Height); // Set transparant option info.SetAsWindowless(0, bIsTransparent); renderer = new RenderHandler(Width, Height, this); g_handler = new BrowserClient(renderer); browser = CefBrowserHost::CreateBrowserSync(info, g_handler.get(), "about:blank", browserSettings, NULL); // Setup JS event emitter g_handler->SetEventEmitter(&ScriptEventEmitter); UE_LOG(LogBlu, Log, TEXT("Component Initialized")); CefString str = *DefaultURL; UE_LOG(LogBlu, Log, TEXT("Loading URL: %s"), *DefaultURL); // Load the default URL LoadURL(DefaultURL); ResetTexture(); } void UBluEye::ResetTexture() { // Here we init the texture to its initial state DestroyTexture(); // init the new Texture2D Texture = UTexture2D::CreateTransient(Width, Height, PF_B8G8R8A8); Texture->AddToRoot(); Texture->UpdateResource(); RenderParams.Texture2DResource = (FTexture2DResource*)Texture->Resource; ResetMatInstance(); } void UBluEye::DestroyTexture() { // Here we destory the texture and its resource if (Texture) { Texture->RemoveFromRoot(); if (Texture->Resource) { BeginReleaseResource(Texture->Resource); FlushRenderingCommands(); } Texture->MarkPendingKill(); Texture = nullptr; } } void UBluEye::TextureUpdate(const void *buffer) { if (!browser || !bEnabled) { UE_LOG(LogBlu, Warning, TEXT("NO BROWSER ACCESS OR NOT ENABLED")) return; } if (Texture && Texture->Resource) { // Is our texture ready? auto ref = static_cast<FTexture2DResource*>(Texture->Resource)->GetTexture2DRHI(); if (!ref) { UE_LOG(LogBlu, Warning, TEXT("NO REF")) return; } if (buffer == nullptr) { UE_LOG(LogBlu, Warning, TEXT("NO TEXTDATA")) return; } ENQUEUE_UNIQUE_RENDER_COMMAND_FOURPARAMETER( void, const void*, ImageData, buffer, UTexture2D*, TargetTexture, Texture, int32, Stride, Width * 4, FBluTextureParams, Params, RenderParams, { RHIUpdateTexture2D(Params.Texture2DResource->GetTexture2DRHI(), 0, *Params.UpdateRegions, Stride, (uint8*)ImageData); }); } else { UE_LOG(LogBlu, Warning, TEXT("no Texture or Texture->resource")) } } void UBluEye::ExecuteJS(const FString& code) { CefString codeStr = *code; browser->GetMainFrame()->ExecuteJavaScript(codeStr, "", 0); } void UBluEye::LoadURL(const FString& newURL) { // Check if we want to load a local file if (newURL.Contains(TEXT("blui://"), ESearchCase::IgnoreCase, ESearchDir::FromStart)) { // Get the current working directory FString GameDir = FPaths::ConvertRelativePathToFull(FPaths::GameDir()); // We're loading a local file, so replace the proto with our game directory path FString LocalFile = newURL.Replace(TEXT("blui://"), *GameDir, ESearchCase::IgnoreCase); // Now we use the file proto LocalFile = FString(TEXT("file:///")) + LocalFile; UE_LOG(LogBlu, Log, TEXT("Load Local File: %s"), *LocalFile) // Load it up browser->GetMainFrame()->LoadURL(*LocalFile); return; } // Load as usual browser->GetMainFrame()->LoadURL(*newURL); } bool UBluEye::IsBrowserLoading() { return browser->IsLoading(); } void UBluEye::ReloadBrowser(bool IgnoreCache) { if (IgnoreCache) { return browser->ReloadIgnoreCache(); } browser->Reload(); } void UBluEye::NavBack() { if (browser->CanGoBack()) { browser->GoBack(); } } void UBluEye::NavForward() { if (browser->CanGoForward()) { browser->GoForward(); } } void UBluEye::ResizeBrowser(int32 NewWidth, int32 NewHeight) { // Disable the web view while we resize bEnabled = false; // Set our new Width and Height Width = NewWidth; Height = NewHeight; // Update our render handler renderer->width = NewWidth; renderer->height = NewHeight; // Also update the Region definition RenderParams.UpdateRegions->Height = NewHeight; RenderParams.UpdateRegions->Width = NewWidth; // Let the browser's host know we resized it browser->GetHost()->WasResized(); // Now we can keep going bEnabled = true; } void UBluEye::TriggerMouseMove(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendFocusEvent(true); browser->GetHost()->SendMouseMoveEvent(mouse_event, false); } void UBluEye::TriggerLeftClick(const FVector2D& pos, const float scale) { TriggerLeftMouseDown(pos, scale); TriggerLeftMouseUp(pos, scale); } void UBluEye::TriggerRightClick(const FVector2D& pos, const float scale) { TriggerRightMouseDown(pos, scale); TriggerRightMouseUp(pos, scale); } void UBluEye::TriggerLeftMouseDown(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_LEFT, false, 1); } void UBluEye::TriggerRightMouseDown(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_RIGHT, false, 1); } void UBluEye::TriggerLeftMouseUp(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_LEFT, true, 1); } void UBluEye::TriggerRightMouseUp(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_RIGHT, true, 1); } void UBluEye::TriggerMouseWheel(const float MouseWheelDelta, const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseWheelEvent(mouse_event, MouseWheelDelta * 10, MouseWheelDelta * 10); } void UBluEye::KeyDown(FKeyEvent InKey) { processKeyMods(InKey); processKeyCode(InKey); key_event.type = KEYEVENT_KEYDOWN; browser->GetHost()->SendKeyEvent(key_event); } void UBluEye::KeyUp(FKeyEvent InKey) { processKeyMods(InKey); processKeyCode(InKey); key_event.type = KEYEVENT_KEYUP; browser->GetHost()->SendKeyEvent(key_event); } void UBluEye::KeyPress(FKeyEvent InKey) { // Simply trigger down, then up key events KeyDown(InKey); KeyUp(InKey); } void UBluEye::processKeyCode(FKeyEvent InKey) { key_event.native_key_code = InKey.GetKeyCode(); key_event.windows_key_code = InKey.GetKeyCode(); } void UBluEye::CharKeyPress(FCharacterEvent CharEvent) { // Process keymods like usual processKeyMods(CharEvent); // Below char input needs some special treatment, se we can't use the normal key down/up methods key_event.windows_key_code = CharEvent.GetCharacter(); key_event.native_key_code = CharEvent.GetCharacter(); key_event.type = KEYEVENT_CHAR; browser->GetHost()->SendKeyEvent(key_event); key_event.windows_key_code = CharEvent.GetCharacter(); key_event.native_key_code = CharEvent.GetCharacter(); key_event.type = KEYEVENT_KEYUP; browser->GetHost()->SendKeyEvent(key_event); } void UBluEye::RawCharKeyPress(const FString charToPress, bool isRepeat, bool LeftShiftDown, bool RightShiftDown, bool LeftControlDown, bool RightControlDown, bool LeftAltDown, bool RightAltDown, bool LeftCommandDown, bool RightCommandDown, bool CapsLocksOn) { FModifierKeysState* KeyState = new FModifierKeysState(LeftShiftDown, RightShiftDown, LeftControlDown, RightControlDown, LeftAltDown, RightAltDown, LeftCommandDown, RightCommandDown, CapsLocksOn); FCharacterEvent* CharEvent = new FCharacterEvent(charToPress.GetCharArray()[0], *KeyState, 0, isRepeat); CharKeyPress(*CharEvent); } void UBluEye::SpecialKeyPress(EBluSpecialKeys key, bool LeftShiftDown, bool RightShiftDown, bool LeftControlDown, bool RightControlDown, bool LeftAltDown, bool RightAltDown, bool LeftCommandDown, bool RightCommandDown, bool CapsLocksOn) { int32 keyValue = key; key_event.windows_key_code = keyValue; key_event.native_key_code = keyValue; key_event.type = KEYEVENT_KEYDOWN; browser->GetHost()->SendKeyEvent(key_event); key_event.windows_key_code = keyValue; key_event.native_key_code = keyValue; // bits 30 and 31 should be always 1 for WM_KEYUP key_event.type = KEYEVENT_KEYUP; browser->GetHost()->SendKeyEvent(key_event); } void UBluEye::processKeyMods(FInputEvent InKey) { int mods = 0; // Test alt if (InKey.IsAltDown()) { mods |= cef_event_flags_t::EVENTFLAG_ALT_DOWN; } else // Test control if (InKey.IsControlDown()) { mods |= cef_event_flags_t::EVENTFLAG_CONTROL_DOWN; } else // Test shift if (InKey.IsShiftDown()) { mods |= cef_event_flags_t::EVENTFLAG_SHIFT_DOWN; } key_event.modifiers = mods; } UTexture2D* UBluEye::GetTexture() const { if (!Texture) { return UTexture2D::CreateTransient(Width, Height); } return Texture; } UMaterialInstanceDynamic* UBluEye::GetMaterialInstance() const { return MaterialInstance; } void UBluEye::ResetMatInstance() { if (!Texture || !BaseMaterial || TextureParameterName.IsNone()) { return; } // Create material instance if (!MaterialInstance) { MaterialInstance = UMaterialInstanceDynamic::Create(BaseMaterial, NULL); if (!MaterialInstance) { UE_LOG(LogBlu, Warning, TEXT("UI Material instance can't be created")); return; } } // Check again, we must have material instance if (!MaterialInstance) { UE_LOG(LogBlu, Error, TEXT("UI Material instance wasn't created")); return; } // Check we have desired parameter UTexture* Tex = nullptr; if (!MaterialInstance->GetTextureParameterValue(TextureParameterName, Tex)) { UE_LOG(LogBlu, Warning, TEXT("UI Material instance Texture parameter not found")); return; } MaterialInstance->SetTextureParameterValue(TextureParameterName, GetTexture()); } void UBluEye::CloseBrowser() { BeginDestroy(); } void UBluEye::BeginDestroy() { if (browser) { // Make sure things stop playing, like audio, video, etc. LoadURL("about:blank"); // Close up the browser browser->GetHost()->CloseDevTools(); browser->GetHost()->CloseBrowser(true); UE_LOG(LogBlu, Warning, TEXT("Browser Closing")); } DestroyTexture(); Super::BeginDestroy(); }<commit_msg>Clean up key char method<commit_after>#include "BluPrivatePCH.h" UBluEye::UBluEye(const class FObjectInitializer& PCIP) : Super(PCIP) { Width = 800; Height = 600; bIsTransparent = false; } void UBluEye::init() { /** * We don't want this running in editor unless it's PIE * If we don't check this, CEF will spawn infinit processes with widget components **/ if (GEngine) { if (GEngine->IsEditor() && !GWorld->IsPlayInEditor()) { UE_LOG(LogBlu, Log, TEXT("Notice: not playing - Component Will Not Initialize")); return; } } browserSettings.universal_access_from_file_urls = STATE_ENABLED; browserSettings.file_access_from_file_urls = STATE_ENABLED; info.width = Width; info.height = Height; // Set the texture update region (for now the whole image) RenderParams.UpdateRegions = new FUpdateTextureRegion2D(0, 0, 0, 0, Width, Height); // Set transparant option info.SetAsWindowless(0, bIsTransparent); renderer = new RenderHandler(Width, Height, this); g_handler = new BrowserClient(renderer); browser = CefBrowserHost::CreateBrowserSync(info, g_handler.get(), "about:blank", browserSettings, NULL); // Setup JS event emitter g_handler->SetEventEmitter(&ScriptEventEmitter); UE_LOG(LogBlu, Log, TEXT("Component Initialized")); CefString str = *DefaultURL; UE_LOG(LogBlu, Log, TEXT("Loading URL: %s"), *DefaultURL); // Load the default URL LoadURL(DefaultURL); ResetTexture(); } void UBluEye::ResetTexture() { // Here we init the texture to its initial state DestroyTexture(); // init the new Texture2D Texture = UTexture2D::CreateTransient(Width, Height, PF_B8G8R8A8); Texture->AddToRoot(); Texture->UpdateResource(); RenderParams.Texture2DResource = (FTexture2DResource*)Texture->Resource; ResetMatInstance(); } void UBluEye::DestroyTexture() { // Here we destory the texture and its resource if (Texture) { Texture->RemoveFromRoot(); if (Texture->Resource) { BeginReleaseResource(Texture->Resource); FlushRenderingCommands(); } Texture->MarkPendingKill(); Texture = nullptr; } } void UBluEye::TextureUpdate(const void *buffer) { if (!browser || !bEnabled) { UE_LOG(LogBlu, Warning, TEXT("NO BROWSER ACCESS OR NOT ENABLED")) return; } if (Texture && Texture->Resource) { // Is our texture ready? auto ref = static_cast<FTexture2DResource*>(Texture->Resource)->GetTexture2DRHI(); if (!ref) { UE_LOG(LogBlu, Warning, TEXT("NO REF")) return; } if (buffer == nullptr) { UE_LOG(LogBlu, Warning, TEXT("NO TEXTDATA")) return; } ENQUEUE_UNIQUE_RENDER_COMMAND_FOURPARAMETER( void, const void*, ImageData, buffer, UTexture2D*, TargetTexture, Texture, int32, Stride, Width * 4, FBluTextureParams, Params, RenderParams, { RHIUpdateTexture2D(Params.Texture2DResource->GetTexture2DRHI(), 0, *Params.UpdateRegions, Stride, (uint8*)ImageData); }); } else { UE_LOG(LogBlu, Warning, TEXT("no Texture or Texture->resource")) } } void UBluEye::ExecuteJS(const FString& code) { CefString codeStr = *code; browser->GetMainFrame()->ExecuteJavaScript(codeStr, "", 0); } void UBluEye::LoadURL(const FString& newURL) { // Check if we want to load a local file if (newURL.Contains(TEXT("blui://"), ESearchCase::IgnoreCase, ESearchDir::FromStart)) { // Get the current working directory FString GameDir = FPaths::ConvertRelativePathToFull(FPaths::GameDir()); // We're loading a local file, so replace the proto with our game directory path FString LocalFile = newURL.Replace(TEXT("blui://"), *GameDir, ESearchCase::IgnoreCase); // Now we use the file proto LocalFile = FString(TEXT("file:///")) + LocalFile; UE_LOG(LogBlu, Log, TEXT("Load Local File: %s"), *LocalFile) // Load it up browser->GetMainFrame()->LoadURL(*LocalFile); return; } // Load as usual browser->GetMainFrame()->LoadURL(*newURL); } bool UBluEye::IsBrowserLoading() { return browser->IsLoading(); } void UBluEye::ReloadBrowser(bool IgnoreCache) { if (IgnoreCache) { return browser->ReloadIgnoreCache(); } browser->Reload(); } void UBluEye::NavBack() { if (browser->CanGoBack()) { browser->GoBack(); } } void UBluEye::NavForward() { if (browser->CanGoForward()) { browser->GoForward(); } } void UBluEye::ResizeBrowser(int32 NewWidth, int32 NewHeight) { // Disable the web view while we resize bEnabled = false; // Set our new Width and Height Width = NewWidth; Height = NewHeight; // Update our render handler renderer->width = NewWidth; renderer->height = NewHeight; // Also update the Region definition RenderParams.UpdateRegions->Height = NewHeight; RenderParams.UpdateRegions->Width = NewWidth; // Let the browser's host know we resized it browser->GetHost()->WasResized(); // Now we can keep going bEnabled = true; } void UBluEye::TriggerMouseMove(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendFocusEvent(true); browser->GetHost()->SendMouseMoveEvent(mouse_event, false); } void UBluEye::TriggerLeftClick(const FVector2D& pos, const float scale) { TriggerLeftMouseDown(pos, scale); TriggerLeftMouseUp(pos, scale); } void UBluEye::TriggerRightClick(const FVector2D& pos, const float scale) { TriggerRightMouseDown(pos, scale); TriggerRightMouseUp(pos, scale); } void UBluEye::TriggerLeftMouseDown(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_LEFT, false, 1); } void UBluEye::TriggerRightMouseDown(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_RIGHT, false, 1); } void UBluEye::TriggerLeftMouseUp(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_LEFT, true, 1); } void UBluEye::TriggerRightMouseUp(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_RIGHT, true, 1); } void UBluEye::TriggerMouseWheel(const float MouseWheelDelta, const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseWheelEvent(mouse_event, MouseWheelDelta * 10, MouseWheelDelta * 10); } void UBluEye::KeyDown(FKeyEvent InKey) { processKeyMods(InKey); processKeyCode(InKey); key_event.type = KEYEVENT_KEYDOWN; browser->GetHost()->SendKeyEvent(key_event); } void UBluEye::KeyUp(FKeyEvent InKey) { processKeyMods(InKey); processKeyCode(InKey); key_event.type = KEYEVENT_KEYUP; browser->GetHost()->SendKeyEvent(key_event); } void UBluEye::KeyPress(FKeyEvent InKey) { // Simply trigger down, then up key events KeyDown(InKey); KeyUp(InKey); } void UBluEye::processKeyCode(FKeyEvent InKey) { key_event.native_key_code = InKey.GetKeyCode(); key_event.windows_key_code = InKey.GetKeyCode(); } void UBluEye::CharKeyPress(FCharacterEvent CharEvent) { // Process keymods like usual processKeyMods(CharEvent); // Below char input needs some special treatment, se we can't use the normal key down/up methods key_event.windows_key_code = CharEvent.GetCharacter(); key_event.native_key_code = CharEvent.GetCharacter(); key_event.type = KEYEVENT_CHAR; browser->GetHost()->SendKeyEvent(key_event); } void UBluEye::RawCharKeyPress(const FString charToPress, bool isRepeat, bool LeftShiftDown, bool RightShiftDown, bool LeftControlDown, bool RightControlDown, bool LeftAltDown, bool RightAltDown, bool LeftCommandDown, bool RightCommandDown, bool CapsLocksOn) { FModifierKeysState* KeyState = new FModifierKeysState(LeftShiftDown, RightShiftDown, LeftControlDown, RightControlDown, LeftAltDown, RightAltDown, LeftCommandDown, RightCommandDown, CapsLocksOn); FCharacterEvent* CharEvent = new FCharacterEvent(charToPress.GetCharArray()[0], *KeyState, 0, isRepeat); CharKeyPress(*CharEvent); } void UBluEye::SpecialKeyPress(EBluSpecialKeys key, bool LeftShiftDown, bool RightShiftDown, bool LeftControlDown, bool RightControlDown, bool LeftAltDown, bool RightAltDown, bool LeftCommandDown, bool RightCommandDown, bool CapsLocksOn) { int32 keyValue = key; key_event.windows_key_code = keyValue; key_event.native_key_code = keyValue; key_event.type = KEYEVENT_KEYDOWN; browser->GetHost()->SendKeyEvent(key_event); key_event.windows_key_code = keyValue; key_event.native_key_code = keyValue; // bits 30 and 31 should be always 1 for WM_KEYUP key_event.type = KEYEVENT_KEYUP; browser->GetHost()->SendKeyEvent(key_event); } void UBluEye::processKeyMods(FInputEvent InKey) { int mods = 0; // Test alt if (InKey.IsAltDown()) { mods |= cef_event_flags_t::EVENTFLAG_ALT_DOWN; } else // Test control if (InKey.IsControlDown()) { mods |= cef_event_flags_t::EVENTFLAG_CONTROL_DOWN; } else // Test shift if (InKey.IsShiftDown()) { mods |= cef_event_flags_t::EVENTFLAG_SHIFT_DOWN; } key_event.modifiers = mods; } UTexture2D* UBluEye::GetTexture() const { if (!Texture) { return UTexture2D::CreateTransient(Width, Height); } return Texture; } UMaterialInstanceDynamic* UBluEye::GetMaterialInstance() const { return MaterialInstance; } void UBluEye::ResetMatInstance() { if (!Texture || !BaseMaterial || TextureParameterName.IsNone()) { return; } // Create material instance if (!MaterialInstance) { MaterialInstance = UMaterialInstanceDynamic::Create(BaseMaterial, NULL); if (!MaterialInstance) { UE_LOG(LogBlu, Warning, TEXT("UI Material instance can't be created")); return; } } // Check again, we must have material instance if (!MaterialInstance) { UE_LOG(LogBlu, Error, TEXT("UI Material instance wasn't created")); return; } // Check we have desired parameter UTexture* Tex = nullptr; if (!MaterialInstance->GetTextureParameterValue(TextureParameterName, Tex)) { UE_LOG(LogBlu, Warning, TEXT("UI Material instance Texture parameter not found")); return; } MaterialInstance->SetTextureParameterValue(TextureParameterName, GetTexture()); } void UBluEye::CloseBrowser() { BeginDestroy(); } void UBluEye::BeginDestroy() { if (browser) { // Make sure things stop playing, like audio, video, etc. LoadURL("about:blank"); // Close up the browser browser->GetHost()->CloseDevTools(); browser->GetHost()->CloseBrowser(true); UE_LOG(LogBlu, Warning, TEXT("Browser Closing")); } DestroyTexture(); Super::BeginDestroy(); }<|endoftext|>
<commit_before>#include "fontContext.h" #include "platform.h" #define SDF_IMPLEMENTATION #include "sdf.h" #include <memory> #define DEFAULT "fonts/NotoSans-Regular.ttf" #define FONT_AR "fonts/NotoNaskh-Regular.ttf" #define FONT_HE "fonts/NotoSansHebrew-Regular.ttf" #define FONT_JA "fonts/DroidSansJapanese.ttf" #define FALLBACK "fonts/DroidSansFallback.ttf" #if defined(PLATFORM_ANDROID) #define ANDROID_FONT_PATH "/system/fonts/" #endif #define BASE_SIZE 16 #define STEP_SIZE 12 #define SDF_WIDTH 6 #define MIN_LINE_WIDTH 4 namespace Tangram { FontContext::FontContext() : m_sdfRadius(SDF_WIDTH), m_atlas(*this, GlyphTexture::size, m_sdfRadius), m_batch(m_atlas, m_scratch), m_sceneResourceRoot("") { // TODO: make this platform independent #if defined(PLATFORM_ANDROID) auto fontPath = systemFontPath("sans-serif", "400", "normal"); LOG("FONT %s", fontPath.c_str()); int size = BASE_SIZE; for (int i = 0; i < 3; i++, size += STEP_SIZE) { m_font[i] = m_alfons.addFont("default", alfons::InputSource(fontPath), size); } std::string fallback = ""; int importance = 0; while (importance < 100) { fallback = systemFontFallbackPath(importance++, 400); if (fallback.empty()) { break; } if (fallback.find("UI-") != std::string::npos) { continue; } fontPath = ANDROID_FONT_PATH; fontPath += fallback; LOG("FALLBACK %s", fontPath.c_str()); int size = BASE_SIZE; for (int i = 0; i < 3; i++, size += STEP_SIZE) { m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(fontPath), size)); } } #elif defined(PLATFORM_IOS) int size = BASE_SIZE; auto loadFonts = [&](const char* path) { unsigned int dataSize; char* data = reinterpret_cast<char*>(bytesFromFile(path, PathType::resource, &dataSize, m_sceneResourceRoot.c_str())); if (data) { for (int i = 0; i < 3; i++, size += STEP_SIZE) { m_font[i] = m_alfons.addFont("default", alfons::InputSource(data, dataSize), size); } free(data); } }; auto addFaces = [&](const char* path) { unsigned int dataSize; char* data = reinterpret_cast<char*>(bytesFromFile(path, PathType::resource, &dataSize, m_sceneResourceRoot.c_str())); if (data) { for (int i = 0; i < 3; i++, size += STEP_SIZE) { m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(data, dataSize), size)); } free(data); } }; loadFonts(DEFAULT); addFaces(FONT_AR); addFaces(FONT_HE); addFaces(FONT_JA); addFaces(FALLBACK); #else int size = BASE_SIZE; for (int i = 0; i < 3; i++, size += STEP_SIZE) { m_font[i] = m_alfons.addFont("default", alfons::InputSource(DEFAULT), size); m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_AR), size)); m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_HE), size)); m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_JA), size)); m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FALLBACK), size)); } #endif } // Synchronized on m_mutex in layoutText(), called on tile-worker threads void FontContext::addTexture(alfons::AtlasID id, uint16_t width, uint16_t height) { if (m_textures.size() == max_textures) { LOGE("Way too many glyph textures!"); return; } m_textures.emplace_back(); } // Synchronized on m_mutex in layoutText(), called on tile-worker threads void FontContext::addGlyph(alfons::AtlasID id, uint16_t gx, uint16_t gy, uint16_t gw, uint16_t gh, const unsigned char* src, uint16_t pad) { if (id >= max_textures) { return; } auto& texData = m_textures[id].texData; auto& texture = m_textures[id].texture; m_textures[id].dirty = true; uint16_t stride = GlyphTexture::size; uint16_t width = GlyphTexture::size; unsigned char* dst = &texData[(gx + pad) + (gy + pad) * stride]; for (size_t y = 0, pos = 0; y < gh; y++, pos += gw) { std::memcpy(dst + y * stride, src + pos, gw); } dst = &texData[gx + gy * width]; gw += pad * 2; gh += pad * 2; size_t bytes = gw * gh * sizeof(float) * 3; if (m_sdfBuffer.size() < bytes) { m_sdfBuffer.resize(bytes); } sdfBuildDistanceFieldNoAlloc(dst, width, m_sdfRadius, dst, gw, gh, width, &m_sdfBuffer[0]); texture.setDirty(gy, gh); } void FontContext::releaseAtlas(std::bitset<max_textures> _refs) { if (!_refs.any()) { return; } std::lock_guard<std::mutex> lock(m_mutex); for (size_t i = 0; i < m_textures.size(); i++) { if (!_refs[i]) { continue; } if (--m_atlasRefCount[i] == 0) { LOGD("CLEAR ATLAS %d", i); m_atlas.clear(i); m_textures[i].texData.assign(GlyphTexture::size * GlyphTexture::size, 0); } } } void FontContext::updateTextures() { std::lock_guard<std::mutex> lock(m_mutex); for (auto& gt : m_textures) { if (gt.dirty || !gt.texture.isValid()) { gt.dirty = false; auto td = reinterpret_cast<const GLuint*>(gt.texData.data()); gt.texture.update(0, td); } } } void FontContext::bindTexture(alfons::AtlasID _id, GLuint _unit) { std::lock_guard<std::mutex> lock(m_mutex); m_textures[_id].texture.bind(_unit); } bool FontContext::layoutText(TextStyle::Parameters& _params, const std::string& _text, std::vector<GlyphQuad>& _quads, std::bitset<max_textures>& _refs, glm::vec2& _size) { std::lock_guard<std::mutex> lock(m_mutex); alfons::LineLayout line = m_shaper.shape(_params.font, _text); if (line.shapes().size() == 0) { LOGD("Empty text line"); return false; } line.setScale(_params.fontScale); // m_batch.drawShapeRange() calls FontContext's TextureCallback for new glyphs // and MeshCallback (drawGlyph) for vertex quads of each glyph in LineLayout. m_scratch.quads = &_quads; size_t quadsStart = _quads.size(); alfons::LineMetrics metrics; if (_params.wordWrap) { m_textWrapper.draw(m_batch, line, MIN_LINE_WIDTH, _params.maxLineWidth, _params.align, _params.lineSpacing, metrics); } else { glm::vec2 position(0); m_batch.drawShapeRange(line, 0, line.shapes().size(), position, metrics); } // TextLabel parameter: Dimension float width = metrics.aabb.z - metrics.aabb.x; float height = metrics.aabb.w - metrics.aabb.y; // Offset to center all glyphs around 0/0 glm::vec2 offset((metrics.aabb.x + width * 0.5) * TextVertex::position_scale, (metrics.aabb.y + height * 0.5) * TextVertex::position_scale); auto it = _quads.begin() + quadsStart; if (it == _quads.end()) { // No glyphs added return false; } while (it != _quads.end()) { if (!_refs[it->atlas]) { _refs[it->atlas] = true; m_atlasRefCount[it->atlas]++; } it->quad[0].pos -= offset; it->quad[1].pos -= offset; it->quad[2].pos -= offset; it->quad[3].pos -= offset; ++it; } _size = glm::vec2(width, height); return true; } void FontContext::ScratchBuffer::drawGlyph(const alfons::Rect& q, const alfons::AtlasGlyph& atlasGlyph) { if (atlasGlyph.atlas >= max_textures) { return; } auto& g = *atlasGlyph.glyph; quads->push_back({ atlasGlyph.atlas, {{glm::vec2{q.x1, q.y1} * TextVertex::position_scale, {g.u1, g.v1}}, {glm::vec2{q.x1, q.y2} * TextVertex::position_scale, {g.u1, g.v2}}, {glm::vec2{q.x2, q.y1} * TextVertex::position_scale, {g.u2, g.v1}}, {glm::vec2{q.x2, q.y2} * TextVertex::position_scale, {g.u2, g.v2}}}}); } auto FontContext::getFont(const std::string& _family, const std::string& _style, const std::string& _weight, float _size) -> std::shared_ptr<alfons::Font> { int sizeIndex = 0; // Pick the smallest font that does not scale down too much float fontSize = BASE_SIZE; for (int i = 0; i < 3; i++) { sizeIndex = i; if (_size <= fontSize) { break; } fontSize += STEP_SIZE; } //LOG(">> %f - %d ==> %f", _size, sizeIndex, _size / ((sizeIndex+1) * BASE_SIZE)); std::lock_guard<std::mutex> lock(m_mutex); static std::string fontName; fontName.clear(); fontName += _family; fontName += '_'; fontName += _weight; fontName += '_'; fontName += _style; auto font = m_alfons.getFont(fontName, fontSize); if (font->hasFaces()) { return font; } unsigned int dataSize = 0; unsigned char* data = nullptr; // Assuming bundled ttf file follows this convention auto bundledFontPath = "fonts/" + _family + "-" + _weight + _style + ".ttf"; if (!(data = bytesFromFile(bundledFontPath.c_str(), PathType::resource, &dataSize, m_sceneResourceRoot.c_str())) && !(data = bytesFromFile(bundledFontPath.c_str(), PathType::internal, &dataSize, m_sceneResourceRoot.c_str()))) { const std::string sysFontPath = systemFontPath(_family, _weight, _style); if (!(data = bytesFromFile(sysFontPath.c_str(), PathType::absolute, &dataSize, m_sceneResourceRoot.c_str())) ) { LOGE("Could not load font file %s", fontName.c_str()); // add fallbacks from default font font->addFaces(*m_font[sizeIndex]); return font; } } font->addFace(m_alfons.addFontFace(alfons::InputSource(reinterpret_cast<char*>(data), dataSize), fontSize)); free(data); // add fallbacks from default font font->addFaces(*m_font[sizeIndex]); return font; } } <commit_msg>LOG => LOGD<commit_after>#include "fontContext.h" #include "platform.h" #define SDF_IMPLEMENTATION #include "sdf.h" #include <memory> #define DEFAULT "fonts/NotoSans-Regular.ttf" #define FONT_AR "fonts/NotoNaskh-Regular.ttf" #define FONT_HE "fonts/NotoSansHebrew-Regular.ttf" #define FONT_JA "fonts/DroidSansJapanese.ttf" #define FALLBACK "fonts/DroidSansFallback.ttf" #if defined(PLATFORM_ANDROID) #define ANDROID_FONT_PATH "/system/fonts/" #endif #define BASE_SIZE 16 #define STEP_SIZE 12 #define SDF_WIDTH 6 #define MIN_LINE_WIDTH 4 namespace Tangram { FontContext::FontContext() : m_sdfRadius(SDF_WIDTH), m_atlas(*this, GlyphTexture::size, m_sdfRadius), m_batch(m_atlas, m_scratch), m_sceneResourceRoot("") { // TODO: make this platform independent #if defined(PLATFORM_ANDROID) auto fontPath = systemFontPath("sans-serif", "400", "normal"); LOGD("FONT %s", fontPath.c_str()); int size = BASE_SIZE; for (int i = 0; i < 3; i++, size += STEP_SIZE) { m_font[i] = m_alfons.addFont("default", alfons::InputSource(fontPath), size); } std::string fallback = ""; int importance = 0; while (importance < 100) { fallback = systemFontFallbackPath(importance++, 400); if (fallback.empty()) { break; } if (fallback.find("UI-") != std::string::npos) { continue; } fontPath = ANDROID_FONT_PATH; fontPath += fallback; LOGD("FALLBACK %s", fontPath.c_str()); int size = BASE_SIZE; for (int i = 0; i < 3; i++, size += STEP_SIZE) { m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(fontPath), size)); } } #elif defined(PLATFORM_IOS) int size = BASE_SIZE; auto loadFonts = [&](const char* path) { unsigned int dataSize; char* data = reinterpret_cast<char*>(bytesFromFile(path, PathType::resource, &dataSize, m_sceneResourceRoot.c_str())); if (data) { for (int i = 0; i < 3; i++, size += STEP_SIZE) { m_font[i] = m_alfons.addFont("default", alfons::InputSource(data, dataSize), size); } free(data); } }; auto addFaces = [&](const char* path) { unsigned int dataSize; char* data = reinterpret_cast<char*>(bytesFromFile(path, PathType::resource, &dataSize, m_sceneResourceRoot.c_str())); if (data) { for (int i = 0; i < 3; i++, size += STEP_SIZE) { m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(data, dataSize), size)); } free(data); } }; loadFonts(DEFAULT); addFaces(FONT_AR); addFaces(FONT_HE); addFaces(FONT_JA); addFaces(FALLBACK); #else int size = BASE_SIZE; for (int i = 0; i < 3; i++, size += STEP_SIZE) { m_font[i] = m_alfons.addFont("default", alfons::InputSource(DEFAULT), size); m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_AR), size)); m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_HE), size)); m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_JA), size)); m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FALLBACK), size)); } #endif } // Synchronized on m_mutex in layoutText(), called on tile-worker threads void FontContext::addTexture(alfons::AtlasID id, uint16_t width, uint16_t height) { if (m_textures.size() == max_textures) { LOGE("Way too many glyph textures!"); return; } m_textures.emplace_back(); } // Synchronized on m_mutex in layoutText(), called on tile-worker threads void FontContext::addGlyph(alfons::AtlasID id, uint16_t gx, uint16_t gy, uint16_t gw, uint16_t gh, const unsigned char* src, uint16_t pad) { if (id >= max_textures) { return; } auto& texData = m_textures[id].texData; auto& texture = m_textures[id].texture; m_textures[id].dirty = true; uint16_t stride = GlyphTexture::size; uint16_t width = GlyphTexture::size; unsigned char* dst = &texData[(gx + pad) + (gy + pad) * stride]; for (size_t y = 0, pos = 0; y < gh; y++, pos += gw) { std::memcpy(dst + y * stride, src + pos, gw); } dst = &texData[gx + gy * width]; gw += pad * 2; gh += pad * 2; size_t bytes = gw * gh * sizeof(float) * 3; if (m_sdfBuffer.size() < bytes) { m_sdfBuffer.resize(bytes); } sdfBuildDistanceFieldNoAlloc(dst, width, m_sdfRadius, dst, gw, gh, width, &m_sdfBuffer[0]); texture.setDirty(gy, gh); } void FontContext::releaseAtlas(std::bitset<max_textures> _refs) { if (!_refs.any()) { return; } std::lock_guard<std::mutex> lock(m_mutex); for (size_t i = 0; i < m_textures.size(); i++) { if (!_refs[i]) { continue; } if (--m_atlasRefCount[i] == 0) { LOGD("CLEAR ATLAS %d", i); m_atlas.clear(i); m_textures[i].texData.assign(GlyphTexture::size * GlyphTexture::size, 0); } } } void FontContext::updateTextures() { std::lock_guard<std::mutex> lock(m_mutex); for (auto& gt : m_textures) { if (gt.dirty || !gt.texture.isValid()) { gt.dirty = false; auto td = reinterpret_cast<const GLuint*>(gt.texData.data()); gt.texture.update(0, td); } } } void FontContext::bindTexture(alfons::AtlasID _id, GLuint _unit) { std::lock_guard<std::mutex> lock(m_mutex); m_textures[_id].texture.bind(_unit); } bool FontContext::layoutText(TextStyle::Parameters& _params, const std::string& _text, std::vector<GlyphQuad>& _quads, std::bitset<max_textures>& _refs, glm::vec2& _size) { std::lock_guard<std::mutex> lock(m_mutex); alfons::LineLayout line = m_shaper.shape(_params.font, _text); if (line.shapes().size() == 0) { LOGD("Empty text line"); return false; } line.setScale(_params.fontScale); // m_batch.drawShapeRange() calls FontContext's TextureCallback for new glyphs // and MeshCallback (drawGlyph) for vertex quads of each glyph in LineLayout. m_scratch.quads = &_quads; size_t quadsStart = _quads.size(); alfons::LineMetrics metrics; if (_params.wordWrap) { m_textWrapper.draw(m_batch, line, MIN_LINE_WIDTH, _params.maxLineWidth, _params.align, _params.lineSpacing, metrics); } else { glm::vec2 position(0); m_batch.drawShapeRange(line, 0, line.shapes().size(), position, metrics); } // TextLabel parameter: Dimension float width = metrics.aabb.z - metrics.aabb.x; float height = metrics.aabb.w - metrics.aabb.y; // Offset to center all glyphs around 0/0 glm::vec2 offset((metrics.aabb.x + width * 0.5) * TextVertex::position_scale, (metrics.aabb.y + height * 0.5) * TextVertex::position_scale); auto it = _quads.begin() + quadsStart; if (it == _quads.end()) { // No glyphs added return false; } while (it != _quads.end()) { if (!_refs[it->atlas]) { _refs[it->atlas] = true; m_atlasRefCount[it->atlas]++; } it->quad[0].pos -= offset; it->quad[1].pos -= offset; it->quad[2].pos -= offset; it->quad[3].pos -= offset; ++it; } _size = glm::vec2(width, height); return true; } void FontContext::ScratchBuffer::drawGlyph(const alfons::Rect& q, const alfons::AtlasGlyph& atlasGlyph) { if (atlasGlyph.atlas >= max_textures) { return; } auto& g = *atlasGlyph.glyph; quads->push_back({ atlasGlyph.atlas, {{glm::vec2{q.x1, q.y1} * TextVertex::position_scale, {g.u1, g.v1}}, {glm::vec2{q.x1, q.y2} * TextVertex::position_scale, {g.u1, g.v2}}, {glm::vec2{q.x2, q.y1} * TextVertex::position_scale, {g.u2, g.v1}}, {glm::vec2{q.x2, q.y2} * TextVertex::position_scale, {g.u2, g.v2}}}}); } auto FontContext::getFont(const std::string& _family, const std::string& _style, const std::string& _weight, float _size) -> std::shared_ptr<alfons::Font> { int sizeIndex = 0; // Pick the smallest font that does not scale down too much float fontSize = BASE_SIZE; for (int i = 0; i < 3; i++) { sizeIndex = i; if (_size <= fontSize) { break; } fontSize += STEP_SIZE; } //LOG(">> %f - %d ==> %f", _size, sizeIndex, _size / ((sizeIndex+1) * BASE_SIZE)); std::lock_guard<std::mutex> lock(m_mutex); static std::string fontName; fontName.clear(); fontName += _family; fontName += '_'; fontName += _weight; fontName += '_'; fontName += _style; auto font = m_alfons.getFont(fontName, fontSize); if (font->hasFaces()) { return font; } unsigned int dataSize = 0; unsigned char* data = nullptr; // Assuming bundled ttf file follows this convention auto bundledFontPath = "fonts/" + _family + "-" + _weight + _style + ".ttf"; if (!(data = bytesFromFile(bundledFontPath.c_str(), PathType::resource, &dataSize, m_sceneResourceRoot.c_str())) && !(data = bytesFromFile(bundledFontPath.c_str(), PathType::internal, &dataSize, m_sceneResourceRoot.c_str()))) { const std::string sysFontPath = systemFontPath(_family, _weight, _style); if (!(data = bytesFromFile(sysFontPath.c_str(), PathType::absolute, &dataSize, m_sceneResourceRoot.c_str())) ) { LOGE("Could not load font file %s", fontName.c_str()); // add fallbacks from default font font->addFaces(*m_font[sizeIndex]); return font; } } font->addFace(m_alfons.addFontFace(alfons::InputSource(reinterpret_cast<char*>(data), dataSize), fontSize)); free(data); // add fallbacks from default font font->addFaces(*m_font[sizeIndex]); return font; } } <|endoftext|>
<commit_before><commit_msg>Verbose view now shows track-level data<commit_after><|endoftext|>
<commit_before><commit_msg>added missing function implementation<commit_after><|endoftext|>
<commit_before>// secondary.C --- Secondary domain for solute transport. // // Copyright 2008 Per Abrahamsen, Mikkel Mollerup and KU. // // This file is part of Daisy. // // Daisy is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser Public License as published by // the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // Daisy 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 Public License for more details. // // You should have received a copy of the GNU Lesser Public License // along with Daisy; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #define BUILD_DLL #include "secondary.h" #include "block_model.h" #include "librarian.h" #include "assertion.h" #include "frame.h" #include "soil.h" // secondary component. const char *const Secondary::component = "secondary"; symbol Secondary::library_id () const { static const symbol id (component); return id; } Secondary::Secondary (const BlockModel& al) : name (al.type_name ()) { } Secondary::Secondary (const symbol name_) : name (name_) { } Secondary::~Secondary () { } static struct SecondaryInit : public DeclareComponent { SecondaryInit () : DeclareComponent (Secondary::component, "\ Specify secondary domain.\n\ \n\ The secondary domain consist typically of soil fractures or other\n\ inter-aggregate pores small enough to be dominated by capillarity, yet\n\ so large that water moves fast enough that the solute equilibrium with\n\ the primary domain (typically intra-aggregate pores) can not be maintained.\n\ \n\ This allows a pulse of water to be move through saturated or near\n\ saturated soil without solutes in the new water being mixed with\n\ solutes in the old water. The effects are twofold: It allows solutes\n\ applied to the surface to reach deeper soil layers much faster than it\n\ would otherwise, and it protects solutes in the soil matrix from being\n\ washed out with fast moving new water.") { } } Secondary_init; // "none" model. struct SecondaryNone : public Secondary { double h_lim (const size_t, const Soil&) const // Pressure act. secondary domain. [cm] { return 0.0; } double K (const size_t, const Soil&, const double h) const // Conductivity in sec. dom. [cm/h] { return 0.0; } double alpha () const // Exchange rate between domain [h^-1] { return 0.0; } explicit SecondaryNone (const BlockModel& al) : Secondary (al) {} SecondaryNone () : Secondary ("none") {} }; std::auto_ptr<Secondary> Secondary::create_none () { return std::auto_ptr<Secondary> (new SecondaryNone ()); } static struct SecondaryNoneSyntax : public DeclareModel { Model* make (const BlockModel& al) const { return new SecondaryNone (al); } SecondaryNoneSyntax () : DeclareModel (Secondary::component, "none", "No secondary domain.\n\ \n\ There is always full equilibrium between solute in different size\n\ matrix pores.") { } void load_frame (Frame& frame) const { } } SecondaryNone_syntax; // "alpha" model. struct SecondaryAlpha : public Secondary { const double alpha_; double alpha () const // The value of the 'alpha' parameter. { return alpha_; } SecondaryAlpha (const BlockModel& al) : Secondary (al), alpha_ (al.number ("alpha")) {} }; static struct SecondaryAlphaSyntax : public DeclareBase { SecondaryAlphaSyntax () : DeclareBase (Secondary::component, "alpha", "Shared base class for non-empty secondary domains.") { } void load_frame (Frame& frame) const { frame.declare ("alpha", "h^-1", Attribute::Const, "\ Exchange rate between primary and secondary water."); } } SecondaryAlpha_syntax; // "pressure" model. struct SecondaryPressure : public SecondaryAlpha { const double h_lim_; const double K_; double h_lim (const size_t, const Soil&) const // The value of the 'h_lim' parameter. { return h_lim_; } double K (const size_t cell, const Soil& soil, const double h) const { if (h < h_lim (cell, soil)) return 0.0; else return K_; } SecondaryPressure (const BlockModel& al) : SecondaryAlpha (al), h_lim_ (al.number ("h_lim")), K_ (al.number ("K")) {} }; static struct SecondaryPressureSyntax : public DeclareModel { Model* make (const BlockModel& al) const { return new SecondaryPressure (al); } SecondaryPressureSyntax () : DeclareModel (Secondary::component, "pressure", "alpha", "\ Horizon has secondary domain specifyed by pressure thresshold.\n\ \n\ The secondary domain consist of water in matrix pores larger than\n\ what corresponds to the specified pressure. ") { } void load_frame (Frame& frame) const { frame.declare ("h_lim", "cm", Attribute::Const, "\ Minimal pressure needed for activating secondary domain."); frame.declare ("K", "cm/h", Attribute::Const, "\ Water conductivity when secondary domain is active.\n\ If the secondary domain is already included in the normal conductivity\n\ curve, specify 0.0 use that value instead."); frame.set ("K", 0.0); } } SecondaryPressure_syntax; // "cracks" model. struct SecondaryCracks : public SecondaryAlpha { const double aperture; // [m] const double density; // [m^-1] const double Theta_crack; // [] const double K_crack; // [cm/h] double h_lim (const size_t cell, const Soil& soil) const { const double Theta_sat = soil.Theta (cell, 0.0, 0.0); if (Theta_crack >= Theta_sat) throw "Space occupied by cracks larger than soil porosity"; const double Theta_lim = Theta_sat - Theta_crack; daisy_assert (Theta_lim > 0.0); return soil.h (cell, Theta_lim); } double K (const size_t cell, const Soil& soil, const double h) const { if (h < h_lim (cell, soil)) return 0.0; else return K_crack; } static double find_K (const double aperture, const double density) { return -42.42e42; } SecondaryCracks (const BlockModel& al) : SecondaryAlpha (al), aperture (al.number ("h_aperture")), density (al.number ("density")), Theta_crack (aperture * density), K_crack (find_K (aperture, density)) { daisy_assert (Theta_crack >= 0.0); daisy_assert (Theta_crack <= 1.0); } }; static struct SecondaryCracksSyntax : public DeclareModel { Model* make (const BlockModel& al) const { return new SecondaryCracks (al); } SecondaryCracksSyntax () : DeclareModel (Secondary::component, "aperture", "alpha", "\ Secondary domain specified by aperture and density of soil cracks.") { } void load_frame (Frame& frame) const { frame.declare ("aperture", "m", Attribute::Const, "\ Average distance between walls in cracks."); frame.declare ("density", "m^-1", Attribute::Const, "\ Density of cracks."); } } SecondaryCracks_syntax; // secondary.C ends here. <commit_msg>x61<commit_after>// secondary.C --- Secondary domain for solute transport. // // Copyright 2008 Per Abrahamsen, Mikkel Mollerup and KU. // // This file is part of Daisy. // // Daisy is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser Public License as published by // the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // Daisy 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 Public License for more details. // // You should have received a copy of the GNU Lesser Public License // along with Daisy; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #define BUILD_DLL #include "secondary.h" #include "block_model.h" #include "librarian.h" #include "assertion.h" #include "frame.h" #include "soil.h" #include "check.h" // secondary component. const char *const Secondary::component = "secondary"; symbol Secondary::library_id () const { static const symbol id (component); return id; } Secondary::Secondary (const BlockModel& al) : name (al.type_name ()) { } Secondary::Secondary (const symbol name_) : name (name_) { } Secondary::~Secondary () { } static struct SecondaryInit : public DeclareComponent { SecondaryInit () : DeclareComponent (Secondary::component, "\ Specify secondary domain.\n\ \n\ The secondary domain consist typically of soil fractures or other\n\ inter-aggregate pores small enough to be dominated by capillarity, yet\n\ so large that water moves fast enough that the solute equilibrium with\n\ the primary domain (typically intra-aggregate pores) can not be maintained.\n\ \n\ This allows a pulse of water to be move through saturated or near\n\ saturated soil without solutes in the new water being mixed with\n\ solutes in the old water. The effects are twofold: It allows solutes\n\ applied to the surface to reach deeper soil layers much faster than it\n\ would otherwise, and it protects solutes in the soil matrix from being\n\ washed out with fast moving new water.") { } } Secondary_init; // "none" model. struct SecondaryNone : public Secondary { double h_lim (const size_t, const Soil&) const // Pressure act. secondary domain. [cm] { return 0.0; } double K (const size_t, const Soil&, const double h) const // Conductivity in sec. dom. [cm/h] { return 0.0; } double alpha () const // Exchange rate between domain [h^-1] { return 0.0; } explicit SecondaryNone (const BlockModel& al) : Secondary (al) {} SecondaryNone () : Secondary ("none") {} }; std::auto_ptr<Secondary> Secondary::create_none () { return std::auto_ptr<Secondary> (new SecondaryNone ()); } static struct SecondaryNoneSyntax : public DeclareModel { Model* make (const BlockModel& al) const { return new SecondaryNone (al); } SecondaryNoneSyntax () : DeclareModel (Secondary::component, "none", "No secondary domain.\n\ \n\ There is always full equilibrium between solute in different size\n\ matrix pores.") { } void load_frame (Frame& frame) const { } } SecondaryNone_syntax; // "alpha" model. struct SecondaryAlpha : public Secondary { const double alpha_; double alpha () const // The value of the 'alpha' parameter. { return alpha_; } SecondaryAlpha (const BlockModel& al) : Secondary (al), alpha_ (al.number ("alpha")) {} }; static struct SecondaryAlphaSyntax : public DeclareBase { SecondaryAlphaSyntax () : DeclareBase (Secondary::component, "alpha", "Shared base class for non-empty secondary domains.") { } void load_frame (Frame& frame) const { frame.declare ("alpha", "h^-1", Attribute::Const, "\ Exchange rate between primary and secondary water."); } } SecondaryAlpha_syntax; // "pressure" model. struct SecondaryPressure : public SecondaryAlpha { const double h_lim_; const double K_; double h_lim (const size_t, const Soil&) const // The value of the 'h_lim' parameter. { return h_lim_; } double K (const size_t cell, const Soil& soil, const double h) const { if (h < h_lim (cell, soil)) return 0.0; else return K_; } SecondaryPressure (const BlockModel& al) : SecondaryAlpha (al), h_lim_ (al.number ("h_lim")), K_ (al.number ("K")) {} }; static struct SecondaryPressureSyntax : public DeclareModel { Model* make (const BlockModel& al) const { return new SecondaryPressure (al); } SecondaryPressureSyntax () : DeclareModel (Secondary::component, "pressure", "alpha", "\ Horizon has secondary domain specifyed by pressure thresshold.\n\ \n\ The secondary domain consist of water in matrix pores larger than\n\ what corresponds to the specified pressure. ") { } void load_frame (Frame& frame) const { frame.declare ("h_lim", "cm", Check::positive (), Attribute::Const, "\ Minimal pressure needed for activating secondary domain."); frame.declare ("K", "cm/h", Check::non_negative (), Attribute::Const, "\ Water conductivity when secondary domain is active.\n\ If the secondary domain is already included in the normal conductivity\n\ curve, specify 0.0 use that value instead."); frame.set ("K", 0.0); } } SecondaryPressure_syntax; // "cracks" model. struct SecondaryCracks : public SecondaryAlpha { const double aperture; // [m] const double density; // [m^-1] const double Theta_crack; // [] const double K_crack; // [cm/h] double h_lim (const size_t cell, const Soil& soil) const { const double Theta_sat = soil.Theta (cell, 0.0, 0.0); if (Theta_crack >= Theta_sat) throw "Space occupied by cracks larger than soil porosity"; const double Theta_lim = Theta_sat - Theta_crack; daisy_assert (Theta_lim > 0.0); return soil.h (cell, Theta_lim); } double K (const size_t cell, const Soil& soil, const double h) const { if (h < h_lim (cell, soil)) return 0.0; else return K_crack; } static double find_K (const double aperture, const double density) { return -42.42e42; } SecondaryCracks (const BlockModel& al) : SecondaryAlpha (al), aperture (al.number ("h_aperture")), density (al.number ("density")), Theta_crack (aperture * density), K_crack (find_K (aperture, density)) { daisy_assert (Theta_crack >= 0.0); daisy_assert (Theta_crack <= 1.0); } }; static struct SecondaryCracksSyntax : public DeclareModel { Model* make (const BlockModel& al) const { return new SecondaryCracks (al); } SecondaryCracksSyntax () : DeclareModel (Secondary::component, "aperture", "alpha", "\ Secondary domain specified by aperture and density of soil cracks.") { } static bool check_alist (const Metalib&, const Frame& al, Treelog& msg) { bool ok = true; const double Theta = al.number ("aperture") * al.number ("density"); if (Theta >= 1.0) { ok = false; msg.error ("Volume fraction of cracks exceed 1.0"); } return ok; } void load_frame (Frame& frame) const { frame.add_check (check_alist); frame.declare ("aperture", "m", Check::positive (), Attribute::Const, "\ Average distance between walls in cracks."); frame.declare ("density", "m^-1", Check::positive (), Attribute::Const, "\ Density of cracks."); } } SecondaryCracks_syntax; // secondary.C ends here. <|endoftext|>
<commit_before>#include "eigen_solver.hpp" #include <iomanip> #include "error.hpp" #include "files.hpp" using std::endl; using std::cout; using std::cin; const static int out_w = 14; namespace mocc{ EigenSolver::EigenSolver( const pugi::xml_node &input, const CoreMesh &mesh ): fss_( input, mesh ), fission_source_( fss_.n_reg() ), fission_source_prev_( fss_.n_reg() ), min_iterations_( 0 ) { LogFile << "Initializing Eigenvalue solver..." << std::endl; if( input.empty() ) { throw EXCEPT("No input specified for the eigenvalue solver."); } // grab the convergence constraints from the XML int in_int = 0; real_t in_float = 0.0; // K tolerance in_float = input.attribute("k_tol").as_float(-1.0); if( in_float <= 0.0 ) { throw EXCEPT("Invalid k tolerance."); } tolerance_k_ = in_float; // Psi tolerance in_float = input.attribute("psi_tol").as_float(-1.0); if( in_float <= 0.0 ) { throw EXCEPT("Invalid psi tolerance."); } tolerance_psi_ = in_float; // Max iterations in_int = input.attribute("max_iter").as_int(-1); if( in_int < 0 ) { throw EXCEPT("Invalid number of maximum iterations."); } max_iterations_ = in_int; // Min iterations if( !input.attribute("min_iter").empty() ) { in_int = input.attribute("min_iter").as_int(-1); if( (in_int < 0) || (in_int > (int)max_iterations_) ) { throw EXCEPT("Invalid number of minimum iterations."); } min_iterations_ = in_int; } // CMFD acceleration bool do_cmfd = input.attribute("cmfd").as_bool(false); if( do_cmfd ) { // construct the CMFD solver using the mesh from the transport // sweeper cmfd_.reset( new CMFD( input.child("cmfd"), (Mesh*)&mesh, fss_.sweeper()->get_homogenized_xsmesh() ) ); // Associate the sweeper with the coarse data from the CMFD solver CoarseData * const cd = cmfd_->get_data(); fss_.sweeper()->set_coarse_data( cd ); } LogFile << "Done initializing Eigenvalue solver." << std::endl; return; } // Perform a full-blown eigenvalue solve. Start with a guess for the // fission source (flat), start doing power iteration. Once we have that // working, we will start factoring in CMFD and other fancy tricks void EigenSolver::solve() { keff_ = 1.0; keff_prev_ = 1.0; // initialize the fixed source solver and calculation the initial // fission source fss_.initialize(); // Hand a reference to the fission source to the fixed source solver fss_.set_fission_source(&fission_source_); error_k_ = tolerance_k_; // K residual error_psi_ = tolerance_psi_; // L-2 norm of the fission source residual fss_.sweeper()->calc_fission_source(keff_, fission_source_); cout << std::setw(out_w) << "Time" << std::setw(out_w) << "Iter." << std::setw(out_w) << "k" << std::setw(out_w) << "k error" << std::setw(out_w) << "psi error" << endl; for( size_t n_iterations=0; n_iterations < max_iterations_; n_iterations++ ) { this->step(); // Check for convergence error_k_ = fabs(keff_-keff_prev_); // use the old fission source to store the difference between new // and old, since we will be filling it with new in the next // iteration anyways. real_t e = 0.0; for( int i=0; i<(int)fission_source_.size(); i++ ) { e += std::pow((fission_source_(i)-fission_source_prev_(i)), 2); } error_psi_ = std::sqrt( e ); convergence_.push_back( ConvergenceCriteria(keff_, error_k_, error_psi_) ); this->print( n_iterations+1, convergence_.back() ); if( n_iterations >= max_iterations_ ) { std::cout << "Maximum number of iterations reached!" << std::endl; break; } if( (error_k_ < tolerance_k_) && (error_psi_ < tolerance_psi_ ) && (n_iterations >= min_iterations_) ) { std::cout << "Convergence criteria met!" << std::endl; break; } } } void EigenSolver::step() { // Store the old fission source fission_source_prev_ = fission_source_; if( cmfd_ && cmfd_->is_enabled() ) { this->do_cmfd(); } // Perform a group sweep with the FSS fss_.sweeper()->calc_fission_source(keff_, fission_source_); fss_.step(); // Get the total fission sources real_t tfis1 = fss_.sweeper()->total_fission(false); real_t tfis2 = fss_.sweeper()->total_fission(true); // update estimate for k keff_prev_ = keff_; keff_ = keff_ * tfis1/tfis2; } void EigenSolver::print( int iter, ConvergenceCriteria conv ) { teestream tee(std::cout, LogFile); LogScreen << std::setw(out_w) << std::fixed << std::setprecision(5) << RootTimer.time() << std::setw(out_w) << iter << conv << endl; return; } void EigenSolver::do_cmfd() { assert(cmfd_); assert(cmfd_->is_enabled()); // push homogenized flux onto the coarse mesh, solve, and pull it // back. cmfd_->coarse_data().flux = fss_.sweeper()->get_pin_flux(); // Set the convergence criteria for this solve, there are a few ways we // can do this CMFDConvergence conv = CMFDConvergence::FIXED; switch( conv ) { case CMFDConvergence::FIXED: cmfd_->set_k_tolerance(tolerance_k_/10.0); cmfd_->set_psi_tolerance(tolerance_psi_/10.0); break; case CMFDConvergence::FLOAT: real_t k_tol = std::max(error_k_/1000.0, tolerance_k_/10.0); cmfd_->set_k_tolerance( k_tol ); real_t psi_tol = std::max(error_psi_/1000.0, tolerance_psi_/10.0); cmfd_->set_psi_tolerance( psi_tol ); break; } cmfd_->solve(keff_, fss_.sweeper()->flux()); fss_.sweeper()->set_pin_flux( cmfd_->flux() ); return; } std::ostream& operator<<( std::ostream &os, ConvergenceCriteria conv) { std::ios::fmtflags flags = os.flags(); os << std::setw(out_w) << std::fixed << std::setprecision(10) << conv.k << std::setw(out_w) << std::scientific << std::setprecision(6) << conv.error_k << std::setw(out_w) << std::setiosflags(std::ios::scientific) << std::setprecision(6) << conv.error_psi; os.flags(flags); return os; } }; <commit_msg>Tighten fixed CMFD convergence criteria<commit_after>#include "eigen_solver.hpp" #include <iomanip> #include "error.hpp" #include "files.hpp" using std::endl; using std::cout; using std::cin; const static int out_w = 14; namespace mocc{ EigenSolver::EigenSolver( const pugi::xml_node &input, const CoreMesh &mesh ): fss_( input, mesh ), fission_source_( fss_.n_reg() ), fission_source_prev_( fss_.n_reg() ), min_iterations_( 0 ) { LogFile << "Initializing Eigenvalue solver..." << std::endl; if( input.empty() ) { throw EXCEPT("No input specified for the eigenvalue solver."); } // grab the convergence constraints from the XML int in_int = 0; real_t in_float = 0.0; // K tolerance in_float = input.attribute("k_tol").as_float(-1.0); if( in_float <= 0.0 ) { throw EXCEPT("Invalid k tolerance."); } tolerance_k_ = in_float; // Psi tolerance in_float = input.attribute("psi_tol").as_float(-1.0); if( in_float <= 0.0 ) { throw EXCEPT("Invalid psi tolerance."); } tolerance_psi_ = in_float; // Max iterations in_int = input.attribute("max_iter").as_int(-1); if( in_int < 0 ) { throw EXCEPT("Invalid number of maximum iterations."); } max_iterations_ = in_int; // Min iterations if( !input.attribute("min_iter").empty() ) { in_int = input.attribute("min_iter").as_int(-1); if( (in_int < 0) || (in_int > (int)max_iterations_) ) { throw EXCEPT("Invalid number of minimum iterations."); } min_iterations_ = in_int; } // CMFD acceleration bool do_cmfd = input.attribute("cmfd").as_bool(false); if( do_cmfd ) { // construct the CMFD solver using the mesh from the transport // sweeper cmfd_.reset( new CMFD( input.child("cmfd"), (Mesh*)&mesh, fss_.sweeper()->get_homogenized_xsmesh() ) ); // Associate the sweeper with the coarse data from the CMFD solver CoarseData * const cd = cmfd_->get_data(); fss_.sweeper()->set_coarse_data( cd ); } LogFile << "Done initializing Eigenvalue solver." << std::endl; return; } // Perform a full-blown eigenvalue solve. Start with a guess for the // fission source (flat), start doing power iteration. Once we have that // working, we will start factoring in CMFD and other fancy tricks void EigenSolver::solve() { keff_ = 1.0; keff_prev_ = 1.0; // initialize the fixed source solver and calculation the initial // fission source fss_.initialize(); // Hand a reference to the fission source to the fixed source solver fss_.set_fission_source(&fission_source_); error_k_ = tolerance_k_; // K residual error_psi_ = tolerance_psi_; // L-2 norm of the fission source residual fss_.sweeper()->calc_fission_source(keff_, fission_source_); cout << std::setw(out_w) << "Time" << std::setw(out_w) << "Iter." << std::setw(out_w) << "k" << std::setw(out_w) << "k error" << std::setw(out_w) << "psi error" << endl; for( size_t n_iterations=0; n_iterations < max_iterations_; n_iterations++ ) { this->step(); // Check for convergence error_k_ = fabs(keff_-keff_prev_); // use the old fission source to store the difference between new // and old, since we will be filling it with new in the next // iteration anyways. real_t e = 0.0; for( int i=0; i<(int)fission_source_.size(); i++ ) { e += std::pow((fission_source_(i)-fission_source_prev_(i)), 2); } error_psi_ = std::sqrt( e ); convergence_.push_back( ConvergenceCriteria(keff_, error_k_, error_psi_) ); this->print( n_iterations+1, convergence_.back() ); if( n_iterations >= max_iterations_ ) { std::cout << "Maximum number of iterations reached!" << std::endl; break; } if( (error_k_ < tolerance_k_) && (error_psi_ < tolerance_psi_ ) && (n_iterations >= min_iterations_) ) { std::cout << "Convergence criteria met!" << std::endl; break; } } } void EigenSolver::step() { // Store the old fission source fission_source_prev_ = fission_source_; if( cmfd_ && cmfd_->is_enabled() ) { this->do_cmfd(); } // Perform a group sweep with the FSS fss_.sweeper()->calc_fission_source(keff_, fission_source_); fss_.step(); // Get the total fission sources real_t tfis1 = fss_.sweeper()->total_fission(false); real_t tfis2 = fss_.sweeper()->total_fission(true); // update estimate for k keff_prev_ = keff_; keff_ = keff_ * tfis1/tfis2; } void EigenSolver::print( int iter, ConvergenceCriteria conv ) { LogScreen << std::setw(out_w) << std::fixed << std::setprecision(5) << RootTimer.time() << std::setw(out_w) << iter << conv << endl; return; } void EigenSolver::do_cmfd() { assert(cmfd_); assert(cmfd_->is_enabled()); // push homogenized flux onto the coarse mesh, solve, and pull it // back. cmfd_->coarse_data().flux = fss_.sweeper()->get_pin_flux(); // Set the convergence criteria for this solve, there are a few ways we // can do this CMFDConvergence conv = CMFDConvergence::FIXED; switch( conv ) { case CMFDConvergence::FIXED: cmfd_->set_k_tolerance(tolerance_k_/100.0); cmfd_->set_psi_tolerance(tolerance_psi_/100.0); break; case CMFDConvergence::FLOAT: real_t k_tol = std::max(error_k_/1000.0, tolerance_k_/10.0); cmfd_->set_k_tolerance( k_tol ); real_t psi_tol = std::max(error_psi_/1000.0, tolerance_psi_/10.0); cmfd_->set_psi_tolerance( psi_tol ); break; } cmfd_->solve(keff_, fss_.sweeper()->flux()); fss_.sweeper()->set_pin_flux( cmfd_->flux() ); return; } std::ostream& operator<<( std::ostream &os, ConvergenceCriteria conv) { std::ios::fmtflags flags = os.flags(); os << std::setw(out_w) << std::fixed << std::setprecision(10) << conv.k << std::setw(out_w) << std::scientific << std::setprecision(6) << conv.error_k << std::setw(out_w) << std::setiosflags(std::ios::scientific) << std::setprecision(6) << conv.error_psi; os.flags(flags); return os; } }; <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2015-2016 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "version.h" const TCHAR* PluginVersionString = _T("0.1.3-alpha"); <commit_msg>Bump plugin version to 0.1.4-alpha<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2015-2016 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "version.h" const TCHAR* PluginVersionString = _T("0.1.4-alpha"); <|endoftext|>
<commit_before>// $Id: RDFSection.C,v 1.5 2000/10/18 12:53:17 oliver Exp $ #include <BALL/STRUCTURE/RDFSection.h> #include <BALL/FORMAT/parameters.h> using namespace std; namespace BALL { RDFSection::RDFSection() : ParameterSection(), rdf_() { } RDFSection::RDFSection(const RDFSection& rdf_section) : ParameterSection(), rdf_(rdf_section.rdf_) { } RDFSection::~RDFSection() throw() { } void RDFSection::destroy() { clear(); } void RDFSection::clear() throw() { rdf_.clear(); } void RDFSection::set(const RDFSection& rdf_section) { rdf_.set(rdf_section.rdf_); } const RDFSection& RDFSection::operator = (const RDFSection& rdf_section) { rdf_.set(rdf_section.rdf_); return *this; } RadialDistributionFunction RDFSection::getRDF() const { return rdf_; } bool RDFSection::extractSection(Parameters& parameters, const String& section_name) { if (!parameters.isValid()) { return false; } int type; // extract the basis information ParameterSection::extractSection(parameters, section_name); if (options.has("type")) { if (options.get("type") == "piecewise_polynomial") { type = PIECEWISE_POLYNOMIAL; } else { Log.error() << "RDFSection::extractSection(): " << "Unknown type."; return false; } } else { Log.warn() << "RDFSection::extractSection(): " << "no type given, assuming piecewise_polynomial." << endl; type = PIECEWISE_POLYNOMIAL; } PiecewisePolynomial poly; Interval interval; std::vector<Interval> intervals; Size number_of_intervals; Size degree; Coefficients coeffs; std::vector<Coefficients> coefficients; String upper_limit; switch(type) { case PIECEWISE_POLYNOMIAL: if (options.has("degree")) { degree = options.get("degree").toInt(); } else { Log.warn() << "RDFSection::extractSection(): " << "No degree given, assuming 4." << endl; degree = 4; } coeffs.resize(degree); number_of_intervals = getNumberOfKeys(); intervals.resize(number_of_intervals); coefficients.resize(number_of_intervals); for (Size i = 0; i < number_of_intervals; ++i) { interval.first = getValue(i, 0).toFloat(); // special case: an upper limit can be infinity upper_limit = getValue(i, 1); if (upper_limit == "inf") { interval.second = INFINITY; } else { interval.second = getValue(i, 1).toFloat(); } for (Size col = 0; col < degree; ++col) { coeffs[col] = getValue(i, col + 2).toFloat(); } intervals[i] = interval; coefficients[i] = coeffs; } poly.set(degree, intervals, coefficients); rdf_ = RadialDistributionFunction(poly); return true; default: Log.error() << "RDFSection::extractSection(): " << "Unknown type." << endl; return false; } } } // namespace BALL <commit_msg>fixed: throw()s fixed: merge conflicts changed: canonified interface<commit_after>// $Id: RDFSection.C,v 1.6 2000/10/18 13:54:36 anker Exp $ #include <BALL/STRUCTURE/RDFSection.h> #include <BALL/FORMAT/parameters.h> using namespace std; namespace BALL { RDFSection::RDFSection() throw() : ParameterSection(), rdf_() { } RDFSection::RDFSection(const RDFSection& rdf_section) throw() : ParameterSection(), rdf_(rdf_section.rdf_) { } RDFSection::~RDFSection() throw() { clear(); valid_ = false; } void RDFSection::clear() throw() { rdf_.clear(); ParameterSection::clear(); } const RDFSection& RDFSection::operator = (const RDFSection& rdf_section) throw() { ParameterSection::operator = (rdf_section); rdf_ = rdf_section.rdf_; return *this; } const RadialDistributionFunction& RDFSection::getRDF() const throw() { return rdf_; } bool RDFSection::operator == (const RDFSection& section) const throw() { return (ParameterSection::operator == (section) && (rdf_ == section.rdf_)); } bool RDFSection::extractSection(Parameters& parameters, const String& section_name) throw() { if (!parameters.isValid()) { return false; } int type; // extract the basis information ParameterSection::extractSection(parameters, section_name); if (options.has("type")) { if (options.get("type") == "piecewise_polynomial") { type = PIECEWISE_POLYNOMIAL; } else { Log.error() << "RDFSection::extractSection(): " << "Unknown type."; return false; } } else { Log.warn() << "RDFSection::extractSection(): " << "no type given, assuming piecewise_polynomial." << endl; type = PIECEWISE_POLYNOMIAL; } PiecewisePolynomial poly; Interval interval; std::vector<Interval> intervals; Size number_of_intervals; Size degree; Coefficients coeffs; std::vector<Coefficients> coefficients; String upper_limit; switch(type) { case PIECEWISE_POLYNOMIAL: if (options.has("degree")) { degree = options.get("degree").toInt(); } else { Log.warn() << "RDFSection::extractSection(): " << "No degree given, assuming 4." << endl; degree = 4; } coeffs.resize(degree); number_of_intervals = getNumberOfKeys(); intervals.resize(number_of_intervals); coefficients.resize(number_of_intervals); for (Size i = 0; i < number_of_intervals; ++i) { interval.first = getValue(i, 0).toFloat(); // special case: an upper limit can be infinity upper_limit = getValue(i, 1); if (upper_limit == "inf") { interval.second = INFINITY; } else { interval.second = getValue(i, 1).toFloat(); } for (Size col = 0; col < degree; ++col) { coeffs[col] = getValue(i, col + 2).toFloat(); } intervals[i] = interval; coefficients[i] = coeffs; } poly.set(degree, intervals, coefficients); rdf_ = RadialDistributionFunction(poly); return true; default: Log.error() << "RDFSection::extractSection(): " << "Unknown type." << endl; return false; } } } // namespace BALL <|endoftext|>
<commit_before>/** * @file ProcedualTerrain.cpp */ #include "ProcedualTerrain.h" #include "Texture.h" #include "d3dx12.h" #include "PSO.h" #include "Texture.h" #include "Graphics.h" #include "GamePad.h" #include <DirectXMath.h> using Microsoft::WRL::ComPtr; using namespace DirectX; /** * n``p_f[^^. */ struct Vertex { XMFLOAT3 position; }; /** * 葱In`. * * @param commandAllocator R}hXg쐬p̃AP[^. * * @retval true . * @retval false s. */ bool ProcedualTerrain::Init(const ComPtr<ID3D12Device>& device, const ComPtr<ID3D12DescriptorHeap>& csuDescriptorHeap) { if (FAILED(device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(vertexCount * sizeof(Vertex)), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&vertexBuffer) ))) { return false; } vertexBuffer->SetName(L"ProcedualTerrain Vertex Buffer"); CD3DX12_RANGE range(0, 0); void* vertexBufferAddress; if (FAILED(vertexBuffer->Map(0, &range, &vertexBufferAddress))) { return false; } Vertex* pVertex = static_cast<Vertex*>(vertexBufferAddress); // lp`𓙕_f[^쐬. const XMVECTORF32 factor = { 100.0f / static_cast<float>(width - 1), 1, -100.0f / static_cast<float>(height - 1), 1 }; const XMVECTORF32 offset = { -50, 0, 50, 0 }; for (size_t z = 0; z < height; ++z) { for (size_t x = 0; x < width; ++x) { const XMVECTORF32 ipos = { static_cast<float>(x), 0, static_cast<float>(z), 1 }; const XMVECTOR pos = ipos * factor + offset; XMStoreFloat3(&pVertex->position, pos); ++pVertex; } } vertexBuffer->Unmap(0, nullptr); vertexBufferView.BufferLocation = vertexBuffer->GetGPUVirtualAddress(); vertexBufferView.StrideInBytes = sizeof(Vertex); vertexBufferView.SizeInBytes = static_cast<UINT>(vertexCount * sizeof(Vertex)); const int indexListSize = static_cast<int>(indexCount * sizeof(uint16_t)); if (FAILED(device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(indexListSize), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&indexBuffer) ))) { return false; } indexBuffer->SetName(L"ProcedualTerrain Index Buffer"); void* indexBufferAddress; if (FAILED(indexBuffer->Map(0, &range, &indexBufferAddress))) { return false; } uint16_t* pIndexBuffer = static_cast<uint16_t*>(indexBufferAddress); for (size_t z = 0; z < height - 1; ++z) { for (size_t x = 0; x < width - 1; ++x) { pIndexBuffer[0] = static_cast<uint16_t>(x + z * width); pIndexBuffer[1] = static_cast<uint16_t>((x + 1) + z * width); pIndexBuffer[2] = static_cast<uint16_t>(x + (z + 1) * width); pIndexBuffer[3] = static_cast<uint16_t>((x + 1) + (z + 1) * width); pIndexBuffer += 4; } } indexBuffer->Unmap(0, nullptr); indexBufferView.BufferLocation = indexBuffer->GetGPUVirtualAddress(); indexBufferView.Format = DXGI_FORMAT_R16_UINT; indexBufferView.SizeInBytes = indexListSize; const size_t constantBufferSize = (sizeof(ConstantBuffer) + 255) & ~255; if (FAILED(device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(constantBufferSize), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&constantBuffer) ))) { return false; } indexBuffer->SetName(L"ProcedualTerrain Constant Buffer"); void* constantBufferAddress; if (FAILED(constantBuffer->Map(0, &range, &constantBufferAddress))) { return false; } pConstantBuffer = static_cast<ConstantBuffer*>(constantBufferAddress); Update(); constantBufferView.BufferLocation = constantBuffer->GetGPUVirtualAddress(); constantBufferView.SizeInBytes = constantBufferSize; const UINT handleSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); cbGPUAddress = CD3DX12_GPU_DESCRIPTOR_HANDLE(csuDescriptorHeap->GetGPUDescriptorHandleForHeapStart(), 10, handleSize); cbCPUAddress = CD3DX12_CPU_DESCRIPTOR_HANDLE(csuDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), 10, handleSize); device->CreateConstantBufferView(&constantBufferView, cbCPUAddress); return true; } /** * XV */ void ProcedualTerrain::Update() { if (!pConstantBuffer) { return; } #if 0 const GamePad& gamepad = GetGamePad(0); if (gamepad.buttons & GamePad::DPAD_LEFT) { rotEye.y -= 2.0f / 180.0f * 3.1415926f; } if (gamepad.buttons & GamePad::DPAD_RIGHT) { rotEye.y += 2.0f / 180.0f * 3.1415926f; } if (gamepad.buttons & GamePad::DPAD_UP) { rotEye.x -= 2.0f / 180.0f * 3.1415926f; } if (gamepad.buttons & GamePad::DPAD_DOWN) { rotEye.x += 2.0f / 180.0f * 3.1415926f; } #endif Graphics::Graphics& graphics = Graphics::Graphics::Get(); ConstantBuffer& constant = *pConstantBuffer; rotEye = { 3.14159265f / 3.0f, 0 }; const XMMATRIX matEye = XMMatrixRotationX(rotEye.x) * XMMatrixRotationY(rotEye.y); const XMVECTOR eyePos = XMVector4Transform(XMVECTOR{ 0, 0, -70, 1 }, matEye); const XMVECTOR eyeUp = XMVector4Transform(XMVECTOR{ 0, 1, 0, 1 }, matEye); const XMMATRIX matView = XMMatrixLookAtLH(eyePos, XMVECTOR{ 0, 0, 0, 1 }, eyeUp); const XMMATRIX matProjection = XMMatrixPerspectiveFovLH(45.0f*(3.14f / 180.0f), graphics.viewport.Width / graphics.viewport.Height, 1.0f, 1000.0f); XMStoreFloat3(&constant.cbFrame.eye, eyePos); XMStoreFloat3(&constant.cbFrame.lightDir, XMVECTOR{1.0f / 1.41421356f, -1.0f / 1.41421356f, 0, 1}); constant.cbFrame.lightDiffuse = XMFLOAT3A(0.8f, 0.8f, 0.7f); constant.cbFrame.lightSpecular = XMFLOAT3A(0.8f, 0.8f, 0.7f); constant.cbFrame.lightAmbient = XMFLOAT3A(0.1f, 0.05f, 0.1f); static float base = 0; base += 0.005f; constant.cbTerrain = { 25, 100, 100, base }; XMStoreFloat4x4A(&constant.cbFrame.matViewProjection, XMMatrixTranspose(matView * matProjection)); } /** * `. * * @param commandList `R}hs̃R}hXg. * @param cbTableIndex 萔obt@蓖Ă郋[gfXNv^e[ũCfbNX. */ void ProcedualTerrain::Draw(ID3D12GraphicsCommandList* commandList, uint32_t cbTableIndex) const { Graphics::Graphics& graphics = Graphics::Graphics::Get(); const PSO& pso = GetPSO(PSOType_Terrain); commandList->SetGraphicsRootSignature(pso.rootSignature.Get()); commandList->SetPipelineState(pso.pso.Get()); ID3D12DescriptorHeap* heapList[] = { graphics.csuDescriptorHeap.Get() }; commandList->SetDescriptorHeaps(_countof(heapList), heapList); commandList->RSSetViewports(1, &graphics.viewport); commandList->RSSetScissorRects(1, &graphics.scissorRect); commandList->SetGraphicsRootDescriptorTable(cbTableIndex, cbGPUAddress); commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST); commandList->IASetVertexBuffers(0, 1, &vertexBufferView); commandList->IASetIndexBuffer(&indexBufferView); commandList->DrawIndexedInstanced(indexCount, 1, 0, 0, 0); } <commit_msg>視点移動と組み合わせた疑似無限スクロールを実装.<commit_after>/** * @file ProcedualTerrain.cpp */ #include "ProcedualTerrain.h" #include "Texture.h" #include "d3dx12.h" #include "PSO.h" #include "Texture.h" #include "Graphics.h" #include "GamePad.h" #include <DirectXMath.h> using Microsoft::WRL::ComPtr; using namespace DirectX; /** * n``p_f[^^. */ struct Vertex { XMFLOAT3 position; }; /** * 葱In`. * * @param commandAllocator R}hXg쐬p̃AP[^. * * @retval true . * @retval false s. */ bool ProcedualTerrain::Init(const ComPtr<ID3D12Device>& device, const ComPtr<ID3D12DescriptorHeap>& csuDescriptorHeap) { if (FAILED(device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(vertexCount * sizeof(Vertex)), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&vertexBuffer) ))) { return false; } vertexBuffer->SetName(L"ProcedualTerrain Vertex Buffer"); CD3DX12_RANGE range(0, 0); void* vertexBufferAddress; if (FAILED(vertexBuffer->Map(0, &range, &vertexBufferAddress))) { return false; } Vertex* pVertex = static_cast<Vertex*>(vertexBufferAddress); // lp`𓙕_f[^쐬. const XMVECTORF32 factor = { 100.0f / static_cast<float>(width - 1), 1, -100.0f / static_cast<float>(height - 1), 1 }; const XMVECTORF32 offset = { -50, 0, 50, 0 }; for (size_t z = 0; z < height; ++z) { for (size_t x = 0; x < width; ++x) { const XMVECTORF32 ipos = { static_cast<float>(x), 0, static_cast<float>(z), 1 }; const XMVECTOR pos = ipos * factor + offset; XMStoreFloat3(&pVertex->position, pos); ++pVertex; } } vertexBuffer->Unmap(0, nullptr); vertexBufferView.BufferLocation = vertexBuffer->GetGPUVirtualAddress(); vertexBufferView.StrideInBytes = sizeof(Vertex); vertexBufferView.SizeInBytes = static_cast<UINT>(vertexCount * sizeof(Vertex)); const int indexListSize = static_cast<int>(indexCount * sizeof(uint16_t)); if (FAILED(device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(indexListSize), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&indexBuffer) ))) { return false; } indexBuffer->SetName(L"ProcedualTerrain Index Buffer"); void* indexBufferAddress; if (FAILED(indexBuffer->Map(0, &range, &indexBufferAddress))) { return false; } uint16_t* pIndexBuffer = static_cast<uint16_t*>(indexBufferAddress); for (size_t z = 0; z < height - 1; ++z) { for (size_t x = 0; x < width - 1; ++x) { pIndexBuffer[0] = static_cast<uint16_t>(x + z * width); pIndexBuffer[1] = static_cast<uint16_t>((x + 1) + z * width); pIndexBuffer[2] = static_cast<uint16_t>(x + (z + 1) * width); pIndexBuffer[3] = static_cast<uint16_t>((x + 1) + (z + 1) * width); pIndexBuffer += 4; } } indexBuffer->Unmap(0, nullptr); indexBufferView.BufferLocation = indexBuffer->GetGPUVirtualAddress(); indexBufferView.Format = DXGI_FORMAT_R16_UINT; indexBufferView.SizeInBytes = indexListSize; const size_t constantBufferSize = (sizeof(ConstantBuffer) + 255) & ~255; if (FAILED(device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(constantBufferSize), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&constantBuffer) ))) { return false; } indexBuffer->SetName(L"ProcedualTerrain Constant Buffer"); void* constantBufferAddress; if (FAILED(constantBuffer->Map(0, &range, &constantBufferAddress))) { return false; } pConstantBuffer = static_cast<ConstantBuffer*>(constantBufferAddress); Update(); constantBufferView.BufferLocation = constantBuffer->GetGPUVirtualAddress(); constantBufferView.SizeInBytes = constantBufferSize; const UINT handleSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); cbGPUAddress = CD3DX12_GPU_DESCRIPTOR_HANDLE(csuDescriptorHeap->GetGPUDescriptorHandleForHeapStart(), 10, handleSize); cbCPUAddress = CD3DX12_CPU_DESCRIPTOR_HANDLE(csuDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), 10, handleSize); device->CreateConstantBufferView(&constantBufferView, cbCPUAddress); rotEye = { 3.14159265f / 3.0f, 0 }; return true; } /** * XV */ void ProcedualTerrain::Update() { if (!pConstantBuffer) { return; } #if 0 const GamePad& gamepad = GetGamePad(0); if (gamepad.buttons & GamePad::DPAD_LEFT) { rotEye.y -= 2.0f / 180.0f * 3.1415926f; } if (gamepad.buttons & GamePad::DPAD_RIGHT) { rotEye.y += 2.0f / 180.0f * 3.1415926f; } if (gamepad.buttons & GamePad::DPAD_UP) { rotEye.x -= 2.0f / 180.0f * 3.1415926f; } if (gamepad.buttons & GamePad::DPAD_DOWN) { rotEye.x += 2.0f / 180.0f * 3.1415926f; } #endif static float offsetZ = 0; static float base = 0; const float limitOffsetZ = 100.0f / static_cast<float>(height - 1); offsetZ += 0.1f; if (offsetZ >= limitOffsetZ) { offsetZ -= limitOffsetZ; base += limitOffsetZ; } Graphics::Graphics& graphics = Graphics::Graphics::Get(); ConstantBuffer& constant = *pConstantBuffer; const XMMATRIX matEye = XMMatrixRotationX(rotEye.x) * XMMatrixRotationY(rotEye.y) * XMMatrixTranslation(0, 0, offsetZ); const XMVECTOR eyePos = XMVector4Transform(XMVECTOR{ 0, 0, -70, 1 }, matEye); const XMVECTOR eyeForcus = XMVector4Transform(XMVECTOR{ 0, 0, 0, 1 }, matEye); const XMVECTOR eyeUp = XMVector4Transform(XMVECTOR{ 0, 1, 0, 1 }, matEye); const XMMATRIX matView = XMMatrixLookAtLH(eyePos, eyeForcus, eyeUp); const XMMATRIX matProjection = XMMatrixPerspectiveFovLH(45.0f*(3.14f / 180.0f), graphics.viewport.Width / graphics.viewport.Height, 1.0f, 1000.0f); XMStoreFloat3(&constant.cbFrame.eye, eyePos); XMStoreFloat3(&constant.cbFrame.lightDir, XMVECTOR{1.0f / 1.41421356f, -1.0f / 1.41421356f, 0, 1}); constant.cbFrame.lightDiffuse = XMFLOAT3A(0.8f, 0.8f, 0.7f); constant.cbFrame.lightSpecular = XMFLOAT3A(0.8f, 0.8f, 0.7f); constant.cbFrame.lightAmbient = XMFLOAT3A(0.1f, 0.05f, 0.1f); constant.cbTerrain = { 25, 100, 100, base }; XMStoreFloat4x4A(&constant.cbFrame.matViewProjection, XMMatrixTranspose(matView * matProjection)); } /** * `. * * @param commandList `R}hs̃R}hXg. * @param cbTableIndex 萔obt@蓖Ă郋[gfXNv^e[ũCfbNX. */ void ProcedualTerrain::Draw(ID3D12GraphicsCommandList* commandList, uint32_t cbTableIndex) const { Graphics::Graphics& graphics = Graphics::Graphics::Get(); const PSO& pso = GetPSO(PSOType_Terrain); commandList->SetGraphicsRootSignature(pso.rootSignature.Get()); commandList->SetPipelineState(pso.pso.Get()); ID3D12DescriptorHeap* heapList[] = { graphics.csuDescriptorHeap.Get() }; commandList->SetDescriptorHeaps(_countof(heapList), heapList); commandList->RSSetViewports(1, &graphics.viewport); commandList->RSSetScissorRects(1, &graphics.scissorRect); commandList->SetGraphicsRootDescriptorTable(cbTableIndex, cbGPUAddress); commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST); commandList->IASetVertexBuffers(0, 1, &vertexBufferView); commandList->IASetIndexBuffer(&indexBufferView); commandList->DrawIndexedInstanced(indexCount, 1, 0, 0, 0); } <|endoftext|>
<commit_before>#include <vector> #include "caffe/filler.hpp" #include "caffe/layers/bias_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void BiasLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { if (bottom.size() == 1 && this->blobs_.size() > 0) { LOG(INFO) << "Skipping parameter initialization"; } else if (bottom.size() == 1) { // bias is a learned parameter; initialize it const BiasParameter& param = this->layer_param_.bias_param(); const int axis = bottom[0]->CanonicalAxisIndex(param.axis()); const int num_axes = param.num_axes(); CHECK_GE(num_axes, -1) << "num_axes must be non-negative, " << "or -1 to extend to the end of bottom[0]"; if (num_axes >= 0) { CHECK_GE(bottom[0]->num_axes(), axis + num_axes) << "bias blob's shape extends past bottom[0]'s shape when applied " << "starting with bottom[0] axis = " << axis; } this->blobs_.resize(1); const vector<int>::const_iterator& shape_start = bottom[0]->shape().begin() + axis; const vector<int>::const_iterator& shape_end = (num_axes == -1) ? bottom[0]->shape().end() : (shape_start + num_axes); vector<int> bias_shape(shape_start, shape_end); this->blobs_[0].reset(new Blob<Dtype>(bias_shape)); shared_ptr<Filler<Dtype> > filler(GetFiller<Dtype>(param.filler())); filler->Fill(this->blobs_[0].get()); } this->param_propagate_down_.resize(this->blobs_.size(), true); } template <typename Dtype> void BiasLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const BiasParameter& param = this->layer_param_.bias_param(); Blob<Dtype>* bias = (bottom.size() > 1) ? bottom[1] : this->blobs_[0].get(); // Always set axis == 0 in special case where bias is a scalar // (num_axes == 0). Mathematically equivalent for any choice of axis, so the // actual setting can be safely ignored; and computation is most efficient // with axis == 0 and (therefore) outer_dim_ == 1. const int axis = (bias->num_axes() == 0) ? 0 : bottom[0]->CanonicalAxisIndex(param.axis()); CHECK_GE(bottom[0]->num_axes(), axis + bias->num_axes()) << "bias blob's shape extends past bottom[0]'s shape when applied " << "starting with bottom[0] axis = " << axis; for (int i = 0; i < bias->num_axes(); ++i) { CHECK_EQ(bottom[0]->shape(axis + i), bias->shape(i)) << "dimension mismatch between bottom[0]->shape(" << axis + i << ") and bias->shape(" << i << ")"; } outer_dim_ = bottom[0]->count(0, axis); bias_dim_ = bias->count(); inner_dim_ = bottom[0]->count(axis + bias->num_axes()); dim_ = bias_dim_ * inner_dim_; if (bottom[0] != top[0]) { top[0]->ReshapeLike(*bottom[0]); } bias_multiplier_.Reshape(vector<int>(1, inner_dim_)); if (bias_multiplier_.cpu_data()[inner_dim_ - 1] != Dtype(1)) { caffe_set(inner_dim_, Dtype(1), bias_multiplier_.mutable_cpu_data()); } } template <typename Dtype> void BiasLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bias_data = ((bottom.size() > 1) ? bottom[1] : this->blobs_[0].get())->cpu_data(); Dtype* top_data = top[0]->mutable_cpu_data(); if (bottom[0] != top[0]) { const Dtype* bottom_data = bottom[0]->cpu_data(); caffe_copy(bottom[0]->count(), bottom_data, top_data); } for (int n = 0; n < outer_dim_; ++n) { caffe_cpu_gemm(CblasNoTrans, CblasNoTrans, bias_dim_, inner_dim_, Dtype(1), Dtype(1), bias_data, bias_multiplier_.cpu_data(), Dtype(1), top_data); top_data += dim_; } } template <typename Dtype> void BiasLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[0] && bottom[0] != top[0]) { const Dtype* top_diff = top[0]->cpu_diff(); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); caffe_copy(bottom[0]->count(), top_diff, bottom_diff); } // in-place, we don't need to do anything with the data diff const bool bias_param = (bottom.size() == 1); if ((!bias_param && propagate_down[1]) || (bias_param && this->param_propagate_down_[0])) { const Dtype* top_diff = top[0]->cpu_diff(); Dtype* bias_diff = (bias_param ? this->blobs_[0].get() : bottom[1]) ->mutable_cpu_diff(); bool accum = bias_param; for (int n = 0; n < outer_dim_; ++n) { caffe_cpu_gemv(CblasNoTrans, bias_dim_, inner_dim_, Dtype(1), top_diff, bias_multiplier_.cpu_data(), Dtype(accum), bias_diff); top_diff += dim_; accum = true; } } } #ifdef CPU_ONLY STUB_GPU(BiasLayer); #endif INSTANTIATE_CLASS(BiasLayer); REGISTER_LAYER_CLASS(Bias); } // namespace caffe <commit_msg>Remove incorrect cast of gemm int arg to Dtype in BiasLayer<commit_after>#include <vector> #include "caffe/filler.hpp" #include "caffe/layers/bias_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void BiasLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { if (bottom.size() == 1 && this->blobs_.size() > 0) { LOG(INFO) << "Skipping parameter initialization"; } else if (bottom.size() == 1) { // bias is a learned parameter; initialize it const BiasParameter& param = this->layer_param_.bias_param(); const int axis = bottom[0]->CanonicalAxisIndex(param.axis()); const int num_axes = param.num_axes(); CHECK_GE(num_axes, -1) << "num_axes must be non-negative, " << "or -1 to extend to the end of bottom[0]"; if (num_axes >= 0) { CHECK_GE(bottom[0]->num_axes(), axis + num_axes) << "bias blob's shape extends past bottom[0]'s shape when applied " << "starting with bottom[0] axis = " << axis; } this->blobs_.resize(1); const vector<int>::const_iterator& shape_start = bottom[0]->shape().begin() + axis; const vector<int>::const_iterator& shape_end = (num_axes == -1) ? bottom[0]->shape().end() : (shape_start + num_axes); vector<int> bias_shape(shape_start, shape_end); this->blobs_[0].reset(new Blob<Dtype>(bias_shape)); shared_ptr<Filler<Dtype> > filler(GetFiller<Dtype>(param.filler())); filler->Fill(this->blobs_[0].get()); } this->param_propagate_down_.resize(this->blobs_.size(), true); } template <typename Dtype> void BiasLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const BiasParameter& param = this->layer_param_.bias_param(); Blob<Dtype>* bias = (bottom.size() > 1) ? bottom[1] : this->blobs_[0].get(); // Always set axis == 0 in special case where bias is a scalar // (num_axes == 0). Mathematically equivalent for any choice of axis, so the // actual setting can be safely ignored; and computation is most efficient // with axis == 0 and (therefore) outer_dim_ == 1. const int axis = (bias->num_axes() == 0) ? 0 : bottom[0]->CanonicalAxisIndex(param.axis()); CHECK_GE(bottom[0]->num_axes(), axis + bias->num_axes()) << "bias blob's shape extends past bottom[0]'s shape when applied " << "starting with bottom[0] axis = " << axis; for (int i = 0; i < bias->num_axes(); ++i) { CHECK_EQ(bottom[0]->shape(axis + i), bias->shape(i)) << "dimension mismatch between bottom[0]->shape(" << axis + i << ") and bias->shape(" << i << ")"; } outer_dim_ = bottom[0]->count(0, axis); bias_dim_ = bias->count(); inner_dim_ = bottom[0]->count(axis + bias->num_axes()); dim_ = bias_dim_ * inner_dim_; if (bottom[0] != top[0]) { top[0]->ReshapeLike(*bottom[0]); } bias_multiplier_.Reshape(vector<int>(1, inner_dim_)); if (bias_multiplier_.cpu_data()[inner_dim_ - 1] != Dtype(1)) { caffe_set(inner_dim_, Dtype(1), bias_multiplier_.mutable_cpu_data()); } } template <typename Dtype> void BiasLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bias_data = ((bottom.size() > 1) ? bottom[1] : this->blobs_[0].get())->cpu_data(); Dtype* top_data = top[0]->mutable_cpu_data(); if (bottom[0] != top[0]) { const Dtype* bottom_data = bottom[0]->cpu_data(); caffe_copy(bottom[0]->count(), bottom_data, top_data); } for (int n = 0; n < outer_dim_; ++n) { caffe_cpu_gemm(CblasNoTrans, CblasNoTrans, bias_dim_, inner_dim_, 1, Dtype(1), bias_data, bias_multiplier_.cpu_data(), Dtype(1), top_data); top_data += dim_; } } template <typename Dtype> void BiasLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[0] && bottom[0] != top[0]) { const Dtype* top_diff = top[0]->cpu_diff(); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); caffe_copy(bottom[0]->count(), top_diff, bottom_diff); } // in-place, we don't need to do anything with the data diff const bool bias_param = (bottom.size() == 1); if ((!bias_param && propagate_down[1]) || (bias_param && this->param_propagate_down_[0])) { const Dtype* top_diff = top[0]->cpu_diff(); Dtype* bias_diff = (bias_param ? this->blobs_[0].get() : bottom[1]) ->mutable_cpu_diff(); bool accum = bias_param; for (int n = 0; n < outer_dim_; ++n) { caffe_cpu_gemv(CblasNoTrans, bias_dim_, inner_dim_, Dtype(1), top_diff, bias_multiplier_.cpu_data(), Dtype(accum), bias_diff); top_diff += dim_; accum = true; } } } #ifdef CPU_ONLY STUB_GPU(BiasLayer); #endif INSTANTIATE_CLASS(BiasLayer); REGISTER_LAYER_CLASS(Bias); } // namespace caffe <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: textsearch.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: obo $ $Date: 2006-09-17 01:26: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_unotools.hxx" #ifndef INCLUDED_I18NPOOL_MSLANGID_HXX #include <i18npool/mslangid.hxx> #endif #ifndef _DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _INTN_HXX //autogen //#include <tools/intn.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HDL_ #include <com/sun/star/util/SearchFlags.hdl> #endif #ifndef _COM_SUN_STAR_I18N_TRANSLITERATIONMODULES_HPP_ #include <com/sun/star/i18n/TransliterationModules.hpp> #endif #ifndef _UNOTOOLS_CHARCLASS_HXX #include <unotools/charclass.hxx> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _UNOTOOLS_TEXTSEARCH_HXX #include <unotools/textsearch.hxx> #endif using namespace ::com::sun::star::util; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; // ............................................................................ namespace utl { // ............................................................................ SearchParam::SearchParam( const String &rText, SearchType eType, BOOL bCaseSensitive, BOOL bWrdOnly, BOOL bSearchInSel ) { sSrchStr = rText; eSrchType = eType; bWordOnly = bWrdOnly; bSrchInSel = bSearchInSel; bCaseSense = bCaseSensitive; nTransliterationFlags = 0; // Werte fuer "Gewichtete Levenshtein-Distanz" bLEV_Relaxed = TRUE; nLEV_OtherX = 2; nLEV_ShorterY = 1; nLEV_LongerZ = 3; } SearchParam::SearchParam( const SearchParam& rParam ) { sSrchStr = rParam.sSrchStr; sReplaceStr = rParam.sReplaceStr; eSrchType = rParam.eSrchType; bWordOnly = rParam.bWordOnly; bSrchInSel = rParam.bSrchInSel; bCaseSense = rParam.bCaseSense; bLEV_Relaxed = rParam.bLEV_Relaxed; nLEV_OtherX = rParam.nLEV_OtherX; nLEV_ShorterY = rParam.nLEV_ShorterY; nLEV_LongerZ = rParam.nLEV_LongerZ; nTransliterationFlags = rParam.nTransliterationFlags; } // Klasse zum Suchen eines Strings in einem Text. Es wird genau nach // dem String gesucht. // ( Die Unterscheidung der Gross/Klein-Schreibung kann mit einen Flag // unterdrueckt werden ) TextSearch::TextSearch(const SearchParam & rParam, LanguageType eLang ) { if( LANGUAGE_NONE == eLang ) eLang = LANGUAGE_SYSTEM; ::com::sun::star::lang::Locale aLocale( MsLangId::convertLanguageToLocale( LanguageType(eLang))); Init( rParam, aLocale); } TextSearch::TextSearch(const SearchParam & rParam, const CharClass& rCClass ) { Init( rParam, rCClass.getLocale() ); } TextSearch::TextSearch( const SearchOptions& rPara ) { try { Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory(); xTextSearch = Reference< XTextSearch > ( xMSF->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.TextSearch" ) ) ), UNO_QUERY ); xTextSearch->setOptions( rPara ); } catch ( Exception& ) { DBG_ERRORFILE( "TextSearch ctor: Exception caught!" ); } } void TextSearch::Init( const SearchParam & rParam, const ::com::sun::star::lang::Locale& rLocale ) { // convert SearchParam to the UNO SearchOptions SearchOptions aSOpt; switch( rParam.GetSrchType() ) { case SearchParam::SRCH_REGEXP: aSOpt.algorithmType = SearchAlgorithms_REGEXP; if( rParam.IsSrchInSelection() ) aSOpt.searchFlag |= SearchFlags::REG_NOT_BEGINOFLINE | SearchFlags::REG_NOT_ENDOFLINE; break; case SearchParam::SRCH_LEVDIST: aSOpt.algorithmType = SearchAlgorithms_APPROXIMATE; aSOpt.changedChars = rParam.GetLEVOther(); aSOpt.deletedChars = rParam.GetLEVLonger(); aSOpt.insertedChars = rParam.GetLEVShorter(); if( rParam.IsSrchRelaxed() ) aSOpt.searchFlag |= SearchFlags::LEV_RELAXED; break; // case SearchParam::SRCH_NORMAL: default: aSOpt.algorithmType = SearchAlgorithms_ABSOLUTE; if( rParam.IsSrchWordOnly() ) aSOpt.searchFlag |= SearchFlags::NORM_WORD_ONLY; break; } aSOpt.searchString = rParam.GetSrchStr(); aSOpt.replaceString = rParam.GetReplaceStr(); aSOpt.Locale = rLocale; aSOpt.transliterateFlags = rParam.GetTransliterationFlags(); if( !rParam.IsCaseSensitive() ) { aSOpt.searchFlag |= SearchFlags::ALL_IGNORE_CASE; aSOpt.transliterateFlags |= ::com::sun::star::i18n::TransliterationModules_IGNORE_CASE; } try { Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory(); xTextSearch = Reference< XTextSearch > ( xMSF->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.TextSearch" ) ) ), UNO_QUERY ); xTextSearch->setOptions( aSOpt ); } catch ( Exception& ) { DBG_ERRORFILE( "TextSearch ctor: Exception caught!" ); } } void TextSearch::SetLocale( const ::com::sun::star::util::SearchOptions& rOptions, const ::com::sun::star::lang::Locale& rLocale ) { // convert SearchParam to the UNO SearchOptions SearchOptions aSOpt( rOptions ); aSOpt.Locale = rLocale; try { Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory(); xTextSearch = Reference< XTextSearch > ( xMSF->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.TextSearch" ) ) ), UNO_QUERY ); xTextSearch->setOptions( aSOpt ); } catch ( Exception& ) { DBG_ERRORFILE( "TextSearch ctor: Exception caught!" ); } } TextSearch::~TextSearch() { } /* * Die allgemeinen Methoden zu Suchen. Diese rufen dann die entpsrecheden * Methoden fuer die normale Suche oder der Suche nach Regular-Expressions * ueber die MethodenPointer auf. */ #if defined _MSC_VER #pragma optimize("", off) #endif int TextSearch::SearchFrwrd( const String & rStr, xub_StrLen* pStart, xub_StrLen* pEnde, SearchResult* pRes ) { int nRet = 0; try { if( xTextSearch.is() ) { SearchResult aRet( xTextSearch->searchForward( rStr, *pStart, *pEnde )); if( 1 == aRet.subRegExpressions ) { nRet = 1; // the XTextsearch returns in startOffset the higher position // and the endposition is allways exclusive. // The caller of this function will have in startPos the // lower pos. and end *pStart = (xub_StrLen)aRet.startOffset[ 0 ]; *pEnde = (xub_StrLen)aRet.endOffset[ 0 ]; if( pRes ) *pRes = aRet; } } } catch ( Exception& ) { DBG_ERRORFILE( "SearchForward: Exception caught!" ); } return nRet; } int TextSearch::SearchBkwrd( const String & rStr, xub_StrLen* pStart, xub_StrLen* pEnde, SearchResult* pRes ) { int nRet = 0; try { if( xTextSearch.is() ) { SearchResult aRet( xTextSearch->searchBackward( rStr, *pStart, *pEnde )); if( aRet.subRegExpressions ) { nRet = 1; // the XTextsearch returns in startOffset the higher position // and the endposition is allways exclusive. // The caller of this function will have in startPos the // lower pos. and end *pEnde = (xub_StrLen)aRet.startOffset[ 0 ]; *pStart = (xub_StrLen)aRet.endOffset[ 0 ]; if( pRes ) *pRes = aRet; } } } catch ( Exception& ) { DBG_ERRORFILE( "SearchBackward: Exception caught!" ); } return nRet; } #if defined _MSC_VER #pragma optimize("", on) #endif // ............................................................................ } // namespace utl // ............................................................................ <commit_msg>INTEGRATION: CWS c15v2_SRC680 (1.12.22); FILE MERGED 2007/03/16 10:27:17 dr 1.12.22.1: #146394# #146464# creating object may fail<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: textsearch.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: ihi $ $Date: 2007-03-26 12:46:42 $ * * 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_unotools.hxx" #ifndef INCLUDED_I18NPOOL_MSLANGID_HXX #include <i18npool/mslangid.hxx> #endif #ifndef _DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _INTN_HXX //autogen //#include <tools/intn.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HDL_ #include <com/sun/star/util/SearchFlags.hdl> #endif #ifndef _COM_SUN_STAR_I18N_TRANSLITERATIONMODULES_HPP_ #include <com/sun/star/i18n/TransliterationModules.hpp> #endif #ifndef _UNOTOOLS_CHARCLASS_HXX #include <unotools/charclass.hxx> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _UNOTOOLS_TEXTSEARCH_HXX #include <unotools/textsearch.hxx> #endif using namespace ::com::sun::star::util; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; // ............................................................................ namespace utl { // ............................................................................ SearchParam::SearchParam( const String &rText, SearchType eType, BOOL bCaseSensitive, BOOL bWrdOnly, BOOL bSearchInSel ) { sSrchStr = rText; eSrchType = eType; bWordOnly = bWrdOnly; bSrchInSel = bSearchInSel; bCaseSense = bCaseSensitive; nTransliterationFlags = 0; // Werte fuer "Gewichtete Levenshtein-Distanz" bLEV_Relaxed = TRUE; nLEV_OtherX = 2; nLEV_ShorterY = 1; nLEV_LongerZ = 3; } SearchParam::SearchParam( const SearchParam& rParam ) { sSrchStr = rParam.sSrchStr; sReplaceStr = rParam.sReplaceStr; eSrchType = rParam.eSrchType; bWordOnly = rParam.bWordOnly; bSrchInSel = rParam.bSrchInSel; bCaseSense = rParam.bCaseSense; bLEV_Relaxed = rParam.bLEV_Relaxed; nLEV_OtherX = rParam.nLEV_OtherX; nLEV_ShorterY = rParam.nLEV_ShorterY; nLEV_LongerZ = rParam.nLEV_LongerZ; nTransliterationFlags = rParam.nTransliterationFlags; } // Klasse zum Suchen eines Strings in einem Text. Es wird genau nach // dem String gesucht. // ( Die Unterscheidung der Gross/Klein-Schreibung kann mit einen Flag // unterdrueckt werden ) TextSearch::TextSearch(const SearchParam & rParam, LanguageType eLang ) { if( LANGUAGE_NONE == eLang ) eLang = LANGUAGE_SYSTEM; ::com::sun::star::lang::Locale aLocale( MsLangId::convertLanguageToLocale( LanguageType(eLang))); Init( rParam, aLocale); } TextSearch::TextSearch(const SearchParam & rParam, const CharClass& rCClass ) { Init( rParam, rCClass.getLocale() ); } TextSearch::TextSearch( const SearchOptions& rPara ) { try { Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory(); xTextSearch = Reference< XTextSearch > ( xMSF->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.TextSearch" ) ) ), UNO_QUERY_THROW ); xTextSearch->setOptions( rPara ); } catch ( Exception& ) { DBG_ERRORFILE( "TextSearch ctor: Exception caught!" ); } } void TextSearch::Init( const SearchParam & rParam, const ::com::sun::star::lang::Locale& rLocale ) { // convert SearchParam to the UNO SearchOptions SearchOptions aSOpt; switch( rParam.GetSrchType() ) { case SearchParam::SRCH_REGEXP: aSOpt.algorithmType = SearchAlgorithms_REGEXP; if( rParam.IsSrchInSelection() ) aSOpt.searchFlag |= SearchFlags::REG_NOT_BEGINOFLINE | SearchFlags::REG_NOT_ENDOFLINE; break; case SearchParam::SRCH_LEVDIST: aSOpt.algorithmType = SearchAlgorithms_APPROXIMATE; aSOpt.changedChars = rParam.GetLEVOther(); aSOpt.deletedChars = rParam.GetLEVLonger(); aSOpt.insertedChars = rParam.GetLEVShorter(); if( rParam.IsSrchRelaxed() ) aSOpt.searchFlag |= SearchFlags::LEV_RELAXED; break; // case SearchParam::SRCH_NORMAL: default: aSOpt.algorithmType = SearchAlgorithms_ABSOLUTE; if( rParam.IsSrchWordOnly() ) aSOpt.searchFlag |= SearchFlags::NORM_WORD_ONLY; break; } aSOpt.searchString = rParam.GetSrchStr(); aSOpt.replaceString = rParam.GetReplaceStr(); aSOpt.Locale = rLocale; aSOpt.transliterateFlags = rParam.GetTransliterationFlags(); if( !rParam.IsCaseSensitive() ) { aSOpt.searchFlag |= SearchFlags::ALL_IGNORE_CASE; aSOpt.transliterateFlags |= ::com::sun::star::i18n::TransliterationModules_IGNORE_CASE; } try { Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory(); xTextSearch = Reference< XTextSearch > ( xMSF->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.TextSearch" ) ) ), UNO_QUERY_THROW ); xTextSearch->setOptions( aSOpt ); } catch ( Exception& ) { DBG_ERRORFILE( "TextSearch ctor: Exception caught!" ); } } void TextSearch::SetLocale( const ::com::sun::star::util::SearchOptions& rOptions, const ::com::sun::star::lang::Locale& rLocale ) { // convert SearchParam to the UNO SearchOptions SearchOptions aSOpt( rOptions ); aSOpt.Locale = rLocale; try { Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory(); xTextSearch = Reference< XTextSearch > ( xMSF->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.TextSearch" ) ) ), UNO_QUERY_THROW ); xTextSearch->setOptions( aSOpt ); } catch ( Exception& ) { DBG_ERRORFILE( "TextSearch ctor: Exception caught!" ); } } TextSearch::~TextSearch() { } /* * Die allgemeinen Methoden zu Suchen. Diese rufen dann die entpsrecheden * Methoden fuer die normale Suche oder der Suche nach Regular-Expressions * ueber die MethodenPointer auf. */ #if defined _MSC_VER #pragma optimize("", off) #endif int TextSearch::SearchFrwrd( const String & rStr, xub_StrLen* pStart, xub_StrLen* pEnde, SearchResult* pRes ) { int nRet = 0; try { if( xTextSearch.is() ) { SearchResult aRet( xTextSearch->searchForward( rStr, *pStart, *pEnde )); if( 1 == aRet.subRegExpressions ) { nRet = 1; // the XTextsearch returns in startOffset the higher position // and the endposition is allways exclusive. // The caller of this function will have in startPos the // lower pos. and end *pStart = (xub_StrLen)aRet.startOffset[ 0 ]; *pEnde = (xub_StrLen)aRet.endOffset[ 0 ]; if( pRes ) *pRes = aRet; } } } catch ( Exception& ) { DBG_ERRORFILE( "SearchForward: Exception caught!" ); } return nRet; } int TextSearch::SearchBkwrd( const String & rStr, xub_StrLen* pStart, xub_StrLen* pEnde, SearchResult* pRes ) { int nRet = 0; try { if( xTextSearch.is() ) { SearchResult aRet( xTextSearch->searchBackward( rStr, *pStart, *pEnde )); if( aRet.subRegExpressions ) { nRet = 1; // the XTextsearch returns in startOffset the higher position // and the endposition is allways exclusive. // The caller of this function will have in startPos the // lower pos. and end *pEnde = (xub_StrLen)aRet.startOffset[ 0 ]; *pStart = (xub_StrLen)aRet.endOffset[ 0 ]; if( pRes ) *pRes = aRet; } } } catch ( Exception& ) { DBG_ERRORFILE( "SearchBackward: Exception caught!" ); } return nRet; } #if defined _MSC_VER #pragma optimize("", on) #endif // ............................................................................ } // namespace utl // ............................................................................ <|endoftext|>
<commit_before>//===--- StatisticsRequired.cpp - "Statistics To Gather" Related Typing ---===// // // This file is part of the Election Method Mathematics // Application (EMMA) project. // // Copyright (c) 2015 - 2016 Frank D. Martinez and the EMMA project authors // Licensed under the GNU Affero General Public License, version 3.0. // // See the file called "LICENSE" included with this distribution // for license information. // //===----------------------------------------------------------------------===// // // Typing relating to statistics the application should gather. // Keeps track of which information the application should // collect. // //===----------------------------------------------------------------------===// #include "StatisticsRequired.h" #include <iostream> namespace Emma { StatisticsRequired::StatisticsRequired() {} StatisticsRequired::StatisticsRequired(const RawParsedOptions rpo) { std::cout << "only collecting the default baseline statistics for now" << std::endl; } IndividualElectionStatistics StatisticsRequired::getIndividualElectionStatistics() const { return each_election; } OverviewStatistics StatisticsRequired::getOverviewStatistics() const { return simulation_wide; } } <commit_msg>presenting commentary to Users in a way which does not look as careless<commit_after>//===--- StatisticsRequired.cpp - "Statistics To Gather" Related Typing ---===// // // This file is part of the Election Method Mathematics // Application (EMMA) project. // // Copyright (c) 2015 - 2016 Frank D. Martinez and the EMMA project authors // Licensed under the GNU Affero General Public License, version 3.0. // // See the file called "LICENSE" included with this distribution // for license information. // //===----------------------------------------------------------------------===// // // Typing relating to statistics the application should gather. // Keeps track of which information the application should // collect. // //===----------------------------------------------------------------------===// #include "StatisticsRequired.h" #include <iostream> namespace Emma { StatisticsRequired::StatisticsRequired() {} StatisticsRequired::StatisticsRequired(const RawParsedOptions rpo) { std::cout << "Note: We are only collecting the default baseline statistics for now" << std::endl; } IndividualElectionStatistics StatisticsRequired::getIndividualElectionStatistics() const { return each_election; } OverviewStatistics StatisticsRequired::getOverviewStatistics() const { return simulation_wide; } } <|endoftext|>
<commit_before>// Copyright (c) 2017-2018 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "cbtx.h" #include "deterministicmns.h" #include "llmq/quorums.h" #include "llmq/quorums_blockprocessor.h" #include "llmq/quorums_commitment.h" #include "simplifiedmns.h" #include "specialtx.h" #include "chainparams.h" #include "consensus/merkle.h" #include "univalue.h" #include "validation.h" bool CheckCbTx(const CTransaction& tx, const CBlockIndex* pindexPrev, CValidationState& state) { if (tx.nType != TRANSACTION_COINBASE) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-type"); } if (!tx.IsCoinBase()) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-invalid"); } CCbTx cbTx; if (!GetTxPayload(tx, cbTx)) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-payload"); } if (cbTx.nVersion == 0 || cbTx.nVersion > CCbTx::CURRENT_VERSION) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-version"); } if (pindexPrev && pindexPrev->nHeight + 1 != cbTx.nHeight) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-height"); } if (pindexPrev) { bool fDIP0008Active = VersionBitsState(pindexPrev, Params().GetConsensus(), Consensus::DEPLOYMENT_DIP0008, versionbitscache) == THRESHOLD_ACTIVE; if (fDIP0008Active && cbTx.nVersion < 2) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-version"); } } return true; } // This can only be done after the block has been fully processed, as otherwise we won't have the finished MN list bool CheckCbTxMerkleRoots(const CBlock& block, const CBlockIndex* pindex, CValidationState& state) { if (block.vtx[0]->nType != TRANSACTION_COINBASE) { return true; } static int64_t nTimePayload = 0; static int64_t nTimeMerkleMNL = 0; static int64_t nTimeMerkleQuorum = 0; int64_t nTime1 = GetTimeMicros(); CCbTx cbTx; if (!GetTxPayload(*block.vtx[0], cbTx)) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-payload"); } int64_t nTime2 = GetTimeMicros(); nTimePayload += nTime2 - nTime1; LogPrint("bench", " - GetTxPayload: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimePayload * 0.000001); if (pindex) { uint256 calculatedMerkleRoot; if (!CalcCbTxMerkleRootMNList(block, pindex->pprev, calculatedMerkleRoot, state)) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-mnmerkleroot"); } if (calculatedMerkleRoot != cbTx.merkleRootMNList) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-mnmerkleroot"); } int64_t nTime3 = GetTimeMicros(); nTimeMerkleMNL += nTime3 - nTime2; LogPrint("bench", " - CalcCbTxMerkleRootMNList: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeMerkleMNL * 0.000001); if (cbTx.nVersion >= 2) { if (!CalcCbTxMerkleRootQuorums(block, pindex->pprev, calculatedMerkleRoot, state)) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-quorummerkleroot"); } if (calculatedMerkleRoot != cbTx.merkleRootQuorums) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-quorummerkleroot"); } } int64_t nTime4 = GetTimeMicros(); nTimeMerkleQuorum += nTime4 - nTime3; LogPrint("bench", " - CalcCbTxMerkleRootQuorums: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeMerkleQuorum * 0.000001); } return true; } bool CalcCbTxMerkleRootMNList(const CBlock& block, const CBlockIndex* pindexPrev, uint256& merkleRootRet, CValidationState& state) { LOCK(deterministicMNManager->cs); static int64_t nTimeDMN = 0; static int64_t nTimeSMNL = 0; static int64_t nTimeMerkle = 0; int64_t nTime1 = GetTimeMicros(); CDeterministicMNList tmpMNList; if (!deterministicMNManager->BuildNewListFromBlock(block, pindexPrev, state, tmpMNList, false)) { return false; } int64_t nTime2 = GetTimeMicros(); nTimeDMN += nTime2 - nTime1; LogPrint("bench", " - BuildNewListFromBlock: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeDMN * 0.000001); CSimplifiedMNList sml(tmpMNList); int64_t nTime3 = GetTimeMicros(); nTimeSMNL += nTime3 - nTime2; LogPrint("bench", " - CSimplifiedMNList: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeSMNL * 0.000001); bool mutated = false; merkleRootRet = sml.CalcMerkleRoot(&mutated); int64_t nTime4 = GetTimeMicros(); nTimeMerkle += nTime4 - nTime3; LogPrint("bench", " - CalcMerkleRoot: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeMerkle * 0.000001); return !mutated; } bool CalcCbTxMerkleRootQuorums(const CBlock& block, const CBlockIndex* pindexPrev, uint256& merkleRootRet, CValidationState& state) { static int64_t nTimeMinedAndActive = 0; static int64_t nTimeMined = 0; static int64_t nTimeLoop = 0; static int64_t nTimeMerkle = 0; int64_t nTime1 = GetTimeMicros(); auto quorums = llmq::quorumBlockProcessor->GetMinedAndActiveCommitmentsUntilBlock(pindexPrev); std::map<Consensus::LLMQType, std::vector<uint256>> qcHashes; size_t hashCount = 0; int64_t nTime2 = GetTimeMicros(); nTimeMinedAndActive += nTime2 - nTime1; LogPrint("bench", " - GetMinedAndActiveCommitmentsUntilBlock: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeMinedAndActive * 0.000001); for (const auto& p : quorums) { auto& v = qcHashes[p.first]; v.reserve(p.second.size()); for (const auto& p2 : p.second) { llmq::CFinalCommitment qc; uint256 minedBlockHash; bool found = llmq::quorumBlockProcessor->GetMinedCommitment(p.first, p2->GetBlockHash(), qc, minedBlockHash); assert(found); v.emplace_back(::SerializeHash(qc)); hashCount++; } } int64_t nTime3 = GetTimeMicros(); nTimeMined += nTime3 - nTime2; LogPrint("bench", " - GetMinedCommitment: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeMined * 0.000001); // now add the commitments from the current block, which are not returned by GetMinedAndActiveCommitmentsUntilBlock // due to the use of pindexPrev (we don't have the tip index here) for (size_t i = 1; i < block.vtx.size(); i++) { auto& tx = block.vtx[i]; if (tx->nVersion == 3 && tx->nType == TRANSACTION_QUORUM_COMMITMENT) { llmq::CFinalCommitmentTxPayload qc; if (!GetTxPayload(*tx, qc)) { assert(false); } if (qc.commitment.IsNull()) { continue; } auto qcHash = ::SerializeHash(qc.commitment); const auto& params = Params().GetConsensus().llmqs.at((Consensus::LLMQType)qc.commitment.llmqType); auto& v = qcHashes[params.type]; if (v.size() == params.signingActiveQuorumCount) { v.pop_back(); } v.emplace_back(qcHash); hashCount++; assert(v.size() <= params.signingActiveQuorumCount); } } std::vector<uint256> qcHashesVec; qcHashesVec.reserve(hashCount); for (const auto& p : qcHashes) { for (const auto& h : p.second) { qcHashesVec.emplace_back(h); } } std::sort(qcHashesVec.begin(), qcHashesVec.end()); int64_t nTime4 = GetTimeMicros(); nTimeLoop += nTime4 - nTime3; LogPrint("bench", " - Loop: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeLoop * 0.000001); bool mutated = false; merkleRootRet = ComputeMerkleRoot(qcHashesVec, &mutated); int64_t nTime5 = GetTimeMicros(); nTimeMerkle += nTime5 - nTime4; LogPrint("bench", " - ComputeMerkleRoot: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeMerkle * 0.000001); return !mutated; } std::string CCbTx::ToString() const { return strprintf("CCbTx(nHeight=%d, nVersion=%d, merkleRootMNList=%s, merkleRootQuorums=%s)", nVersion, nHeight, merkleRootMNList.ToString(), merkleRootQuorums.ToString()); } void CCbTx::ToJson(UniValue& obj) const { obj.clear(); obj.setObject(); obj.push_back(Pair("version", (int)nVersion)); obj.push_back(Pair("height", (int)nHeight)); obj.push_back(Pair("merkleRootMNList", merkleRootMNList.ToString())); if (nVersion >= 2) { obj.push_back(Pair("merkleRootQuorums", merkleRootQuorums.ToString())); } } <commit_msg>Cache heavy parts of CalcCbTxMerkleRoot* (#2885)<commit_after>// Copyright (c) 2017-2018 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "cbtx.h" #include "deterministicmns.h" #include "llmq/quorums.h" #include "llmq/quorums_blockprocessor.h" #include "llmq/quorums_commitment.h" #include "simplifiedmns.h" #include "specialtx.h" #include "chainparams.h" #include "consensus/merkle.h" #include "univalue.h" #include "validation.h" bool CheckCbTx(const CTransaction& tx, const CBlockIndex* pindexPrev, CValidationState& state) { if (tx.nType != TRANSACTION_COINBASE) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-type"); } if (!tx.IsCoinBase()) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-invalid"); } CCbTx cbTx; if (!GetTxPayload(tx, cbTx)) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-payload"); } if (cbTx.nVersion == 0 || cbTx.nVersion > CCbTx::CURRENT_VERSION) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-version"); } if (pindexPrev && pindexPrev->nHeight + 1 != cbTx.nHeight) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-height"); } if (pindexPrev) { bool fDIP0008Active = VersionBitsState(pindexPrev, Params().GetConsensus(), Consensus::DEPLOYMENT_DIP0008, versionbitscache) == THRESHOLD_ACTIVE; if (fDIP0008Active && cbTx.nVersion < 2) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-version"); } } return true; } // This can only be done after the block has been fully processed, as otherwise we won't have the finished MN list bool CheckCbTxMerkleRoots(const CBlock& block, const CBlockIndex* pindex, CValidationState& state) { if (block.vtx[0]->nType != TRANSACTION_COINBASE) { return true; } static int64_t nTimePayload = 0; static int64_t nTimeMerkleMNL = 0; static int64_t nTimeMerkleQuorum = 0; int64_t nTime1 = GetTimeMicros(); CCbTx cbTx; if (!GetTxPayload(*block.vtx[0], cbTx)) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-payload"); } int64_t nTime2 = GetTimeMicros(); nTimePayload += nTime2 - nTime1; LogPrint("bench", " - GetTxPayload: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimePayload * 0.000001); if (pindex) { uint256 calculatedMerkleRoot; if (!CalcCbTxMerkleRootMNList(block, pindex->pprev, calculatedMerkleRoot, state)) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-mnmerkleroot"); } if (calculatedMerkleRoot != cbTx.merkleRootMNList) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-mnmerkleroot"); } int64_t nTime3 = GetTimeMicros(); nTimeMerkleMNL += nTime3 - nTime2; LogPrint("bench", " - CalcCbTxMerkleRootMNList: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeMerkleMNL * 0.000001); if (cbTx.nVersion >= 2) { if (!CalcCbTxMerkleRootQuorums(block, pindex->pprev, calculatedMerkleRoot, state)) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-quorummerkleroot"); } if (calculatedMerkleRoot != cbTx.merkleRootQuorums) { return state.DoS(100, false, REJECT_INVALID, "bad-cbtx-quorummerkleroot"); } } int64_t nTime4 = GetTimeMicros(); nTimeMerkleQuorum += nTime4 - nTime3; LogPrint("bench", " - CalcCbTxMerkleRootQuorums: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeMerkleQuorum * 0.000001); } return true; } bool CalcCbTxMerkleRootMNList(const CBlock& block, const CBlockIndex* pindexPrev, uint256& merkleRootRet, CValidationState& state) { LOCK(deterministicMNManager->cs); static int64_t nTimeDMN = 0; static int64_t nTimeSMNL = 0; static int64_t nTimeMerkle = 0; int64_t nTime1 = GetTimeMicros(); CDeterministicMNList tmpMNList; if (!deterministicMNManager->BuildNewListFromBlock(block, pindexPrev, state, tmpMNList, false)) { return false; } int64_t nTime2 = GetTimeMicros(); nTimeDMN += nTime2 - nTime1; LogPrint("bench", " - BuildNewListFromBlock: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeDMN * 0.000001); CSimplifiedMNList sml(tmpMNList); int64_t nTime3 = GetTimeMicros(); nTimeSMNL += nTime3 - nTime2; LogPrint("bench", " - CSimplifiedMNList: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeSMNL * 0.000001); static CSimplifiedMNList smlCached; static uint256 merkleRootCached; static bool mutatedCached{false}; if (sml.mnList == smlCached.mnList) { merkleRootRet = merkleRootCached; return !mutatedCached; } bool mutated = false; merkleRootRet = sml.CalcMerkleRoot(&mutated); int64_t nTime4 = GetTimeMicros(); nTimeMerkle += nTime4 - nTime3; LogPrint("bench", " - CalcMerkleRoot: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeMerkle * 0.000001); smlCached = std::move(sml); merkleRootCached = merkleRootRet; mutatedCached = mutated; return !mutated; } bool CalcCbTxMerkleRootQuorums(const CBlock& block, const CBlockIndex* pindexPrev, uint256& merkleRootRet, CValidationState& state) { static int64_t nTimeMinedAndActive = 0; static int64_t nTimeMined = 0; static int64_t nTimeLoop = 0; static int64_t nTimeMerkle = 0; int64_t nTime1 = GetTimeMicros(); static std::map<Consensus::LLMQType, std::vector<const CBlockIndex*>> quorumsCached; static std::map<Consensus::LLMQType, std::vector<uint256>> qcHashesCached; auto quorums = llmq::quorumBlockProcessor->GetMinedAndActiveCommitmentsUntilBlock(pindexPrev); std::map<Consensus::LLMQType, std::vector<uint256>> qcHashes; size_t hashCount = 0; int64_t nTime2 = GetTimeMicros(); nTimeMinedAndActive += nTime2 - nTime1; LogPrint("bench", " - GetMinedAndActiveCommitmentsUntilBlock: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeMinedAndActive * 0.000001); if (quorums == quorumsCached) { qcHashes = qcHashesCached; } else { for (const auto& p : quorums) { auto& v = qcHashes[p.first]; v.reserve(p.second.size()); for (const auto& p2 : p.second) { llmq::CFinalCommitment qc; uint256 minedBlockHash; bool found = llmq::quorumBlockProcessor->GetMinedCommitment(p.first, p2->GetBlockHash(), qc, minedBlockHash); assert(found); v.emplace_back(::SerializeHash(qc)); hashCount++; } } quorumsCached = quorums; qcHashesCached = qcHashes; } int64_t nTime3 = GetTimeMicros(); nTimeMined += nTime3 - nTime2; LogPrint("bench", " - GetMinedCommitment: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeMined * 0.000001); // now add the commitments from the current block, which are not returned by GetMinedAndActiveCommitmentsUntilBlock // due to the use of pindexPrev (we don't have the tip index here) for (size_t i = 1; i < block.vtx.size(); i++) { auto& tx = block.vtx[i]; if (tx->nVersion == 3 && tx->nType == TRANSACTION_QUORUM_COMMITMENT) { llmq::CFinalCommitmentTxPayload qc; if (!GetTxPayload(*tx, qc)) { assert(false); } if (qc.commitment.IsNull()) { continue; } auto qcHash = ::SerializeHash(qc.commitment); const auto& params = Params().GetConsensus().llmqs.at((Consensus::LLMQType)qc.commitment.llmqType); auto& v = qcHashes[params.type]; if (v.size() == params.signingActiveQuorumCount) { v.pop_back(); } v.emplace_back(qcHash); hashCount++; assert(v.size() <= params.signingActiveQuorumCount); } } std::vector<uint256> qcHashesVec; qcHashesVec.reserve(hashCount); for (const auto& p : qcHashes) { for (const auto& h : p.second) { qcHashesVec.emplace_back(h); } } std::sort(qcHashesVec.begin(), qcHashesVec.end()); int64_t nTime4 = GetTimeMicros(); nTimeLoop += nTime4 - nTime3; LogPrint("bench", " - Loop: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeLoop * 0.000001); bool mutated = false; merkleRootRet = ComputeMerkleRoot(qcHashesVec, &mutated); int64_t nTime5 = GetTimeMicros(); nTimeMerkle += nTime5 - nTime4; LogPrint("bench", " - ComputeMerkleRoot: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeMerkle * 0.000001); return !mutated; } std::string CCbTx::ToString() const { return strprintf("CCbTx(nHeight=%d, nVersion=%d, merkleRootMNList=%s, merkleRootQuorums=%s)", nVersion, nHeight, merkleRootMNList.ToString(), merkleRootQuorums.ToString()); } void CCbTx::ToJson(UniValue& obj) const { obj.clear(); obj.setObject(); obj.push_back(Pair("version", (int)nVersion)); obj.push_back(Pair("height", (int)nHeight)); obj.push_back(Pair("merkleRootMNList", merkleRootMNList.ToString())); if (nVersion >= 2) { obj.push_back(Pair("merkleRootQuorums", merkleRootQuorums.ToString())); } } <|endoftext|>
<commit_before>#pragma once #include "../IState.hpp" #include <SFML/Graphics/Font.hpp> #include <list> class LoadingScreen : public IState { public: LoadingScreen(); ~LoadingScreen(); bool load(); void unload(); inline std::string getLoadState() const { return ""; } inline bool event(const sf::Event&) { return false; } void update(float dt); inline void draw(sf::RenderTarget&) { } void drawUi(sf::RenderTarget& target); void setLoadingText(const std::string& text); private: float mTime; std::string mCurrentString; std::list<std::string> mLastMessages; std::shared_ptr<sf::Font> mFont; std::shared_ptr<sf::Texture> mSpinner; }; <commit_msg>Fix compiling on Linux<commit_after>#pragma once #include "../IState.hpp" #include <SFML/Graphics/Font.hpp> #include <memory> #include <list> class LoadingScreen : public IState { public: LoadingScreen(); ~LoadingScreen(); bool load(); void unload(); inline std::string getLoadState() const { return ""; } inline bool event(const sf::Event&) { return false; } void update(float dt); inline void draw(sf::RenderTarget&) { } void drawUi(sf::RenderTarget& target); void setLoadingText(const std::string& text); private: float mTime; std::string mCurrentString; std::list<std::string> mLastMessages; std::shared_ptr<sf::Font> mFont; std::shared_ptr<sf::Texture> mSpinner; }; <|endoftext|>
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_OS_RAW_ARGV_HPP__ #define __STOUT_OS_RAW_ARGV_HPP__ #include <string.h> #include <string> #include <vector> #include <stout/foreach.hpp> namespace os { namespace raw { /** * Represent the argument list expected by `execv` routines. The * argument list is an array of pointers that point to null-terminated * strings. The array of pointers must be terminated by a nullptr. To * use this abstraction, see the following example: * * vector<string> args = {"arg0", "arg1"}; * os::raw::Argv argv(args); * execvp("my_binary", argv); */ class Argv { public: template <typename Iterable> explicit Argv(const Iterable& iterable) { foreach (const std::string& arg, iterable) { args.emplace_back(arg); } argv = new char*[args.size() + 1]; for (size_t i = 0; i < args.size(); i++) { argv[i] = const_cast<char*>(args[i].c_str()); } argv[args.size()] = nullptr; } ~Argv() { delete[] argv; } operator char**() const { return argv; } operator std::vector<std::string>() const { return args; } private: std::vector<std::string> args; // NOTE: This points to strings in the vector `args`. char** argv; }; } // namespace raw { } // namespace os { #endif // __STOUT_OS_RAW_ARGV_HPP__ <commit_msg>Deleted Argv copy constructor and assignment members.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_OS_RAW_ARGV_HPP__ #define __STOUT_OS_RAW_ARGV_HPP__ #include <string.h> #include <string> #include <vector> #include <stout/foreach.hpp> namespace os { namespace raw { /** * Represent the argument list expected by `execv` routines. The * argument list is an array of pointers that point to null-terminated * strings. The array of pointers must be terminated by a nullptr. To * use this abstraction, see the following example: * * vector<string> args = {"arg0", "arg1"}; * os::raw::Argv argv(args); * execvp("my_binary", argv); */ class Argv { public: Argv(const Argv&) = delete; Argv& operator=(const Argv&) = delete; template <typename Iterable> explicit Argv(const Iterable& iterable) { foreach (const std::string& arg, iterable) { args.emplace_back(arg); } argv = new char*[args.size() + 1]; for (size_t i = 0; i < args.size(); i++) { argv[i] = const_cast<char*>(args[i].c_str()); } argv[args.size()] = nullptr; } ~Argv() { delete[] argv; } operator char**() const { return argv; } operator std::vector<std::string>() const { return args; } private: std::vector<std::string> args; // NOTE: This points to strings in the vector `args`. char** argv; }; } // namespace raw { } // namespace os { #endif // __STOUT_OS_RAW_ARGV_HPP__ <|endoftext|>
<commit_before>#include "../../../include/cutehmi/internal/singleton.hpp" #include <QList> namespace { class SingletonDestroyWrapper { public: SingletonDestroyWrapper(cutehmi::internal::singletonDestroyCallback callback): m_callback(callback) { } [[gnu::unused]] bool operator ==(const SingletonDestroyWrapper & other) const { return m_callback == other.m_callback; } void call() { m_callback(); } operator uintptr_t() const { return reinterpret_cast<uintptr_t>(m_callback); } private: cutehmi::internal::singletonDestroyCallback m_callback; }; [[gnu::unused]] uint qHash(const SingletonDestroyWrapper & key) { return ::qHash(static_cast<uintptr_t>(key)); } //<cutehmi::destroySingletonInstances-determined_destruction_order.principle> // Container should prserve order in which elements were added, so that singletons can be destroyed in reverse order as they // were added. This disqualifies QSet. typedef QList<SingletonDestroyWrapper> SingletonDestroyFunctionsContainer; // Elements are prepended to this list (see storeSingletonDestroyCallback()). SingletonDestroyFunctionsContainer singletonDestroyFunctions; //</cutehmi::destroySingletonInstances-determined_destruction_order.principle> } namespace cutehmi { namespace internal { void destroySingletonInstances() { //<cutehmi::destroySingletonInstances-determined_destruction_order.principle> SingletonDestroyFunctionsContainer copy = singletonDestroyFunctions; //<cutehmi::Singleton-singleton_class_will_not_call_Destroy_from_destructor.assumption> // If Singleton called Destroy() it would invalidate copy and its iterators. for (auto it = copy.begin(); it != copy.end(); ++it) it->call(); // Call Singleton::Destroy(), which will remove callback from original singletonDestroyFunctions. //</cutehmi::Singleton-singleton_class_will_not_call_Destroy_from_destructor.assumption> //</cutehmi::destroySingletonInstances-determined_destruction_order.principle> } void storeSingletonDestroyCallback(singletonDestroyCallback callback) { //<cutehmi::destroySingletonInstances-determined_destruction_order.principle> // Callbacks should be removed in reverse order as they were added. With prepending removeSingletonDestroyCallback() should be // able to remove callbacks pretty fast, if accessed through destroySingletonInstances(), because QList::removeOne() will find // each removed callback at the beginning of the list. singletonDestroyFunctions.prepend(callback); //</cutehmi::destroySingletonInstances-determined_destruction_order.principle> } void removeSingletonDestroyCallback(singletonDestroyCallback callback) { singletonDestroyFunctions.removeOne(callback); } } } //(c)C: Copyright © 2019-2020, Michał Policht <michal@policht.pl>, Yuri Chornoivan <yurchor@ukr.net>. All rights reserved. //(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT //(c)C: This file is a part of CuteHMI. //(c)C: CuteHMI 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. //(c)C: CuteHMI 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. //(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>. //(c)C: Additionally, this file is licensed under terms of MIT license as expressed below. //(c)C: 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: //(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. //(c)C: 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. <commit_msg>Implement singletonDestroyFunctions() to avoid warning about static non-POD<commit_after>#include "../../../include/cutehmi/internal/singleton.hpp" #include <QList> namespace { class SingletonDestroyWrapper { public: SingletonDestroyWrapper(cutehmi::internal::singletonDestroyCallback callback): m_callback(callback) { } [[gnu::unused]] bool operator ==(const SingletonDestroyWrapper & other) const { return m_callback == other.m_callback; } void call() { m_callback(); } operator uintptr_t() const { return reinterpret_cast<uintptr_t>(m_callback); } private: cutehmi::internal::singletonDestroyCallback m_callback; }; [[gnu::unused]] uint qHash(const SingletonDestroyWrapper & key) { return ::qHash(static_cast<uintptr_t>(key)); } //<cutehmi::destroySingletonInstances-determined_destruction_order.principle> // Container should prserve order in which elements were added, so that singletons can be destroyed in reverse order as they // were added. This disqualifies QSet. typedef QList<SingletonDestroyWrapper> SingletonDestroyFunctionsContainer; // Elements are prepended to this list (see storeSingletonDestroyCallback()). SingletonDestroyFunctionsContainer & singletonDestroyFunctions() { static SingletonDestroyFunctionsContainer container; return container; } //</cutehmi::destroySingletonInstances-determined_destruction_order.principle> } namespace cutehmi { namespace internal { void destroySingletonInstances() { //<cutehmi::destroySingletonInstances-determined_destruction_order.principle> SingletonDestroyFunctionsContainer copy = singletonDestroyFunctions(); //<cutehmi::Singleton-singleton_class_will_not_call_Destroy_from_destructor.assumption> // If Singleton called Destroy() it would invalidate copy and its iterators. for (auto it = copy.begin(); it != copy.end(); ++it) it->call(); // Call Singleton::Destroy(), which will remove callback from original singletonDestroyFunctions. //</cutehmi::Singleton-singleton_class_will_not_call_Destroy_from_destructor.assumption> //</cutehmi::destroySingletonInstances-determined_destruction_order.principle> } void storeSingletonDestroyCallback(singletonDestroyCallback callback) { //<cutehmi::destroySingletonInstances-determined_destruction_order.principle> // Callbacks should be removed in reverse order as they were added. With prepending removeSingletonDestroyCallback() should be // able to remove callbacks pretty fast, if accessed through destroySingletonInstances(), because QList::removeOne() will find // each removed callback at the beginning of the list. singletonDestroyFunctions().prepend(callback); //</cutehmi::destroySingletonInstances-determined_destruction_order.principle> } void removeSingletonDestroyCallback(singletonDestroyCallback callback) { singletonDestroyFunctions().removeOne(callback); } } } //(c)C: Copyright © 2019-2020, Michał Policht <michal@policht.pl>, Yuri Chornoivan <yurchor@ukr.net>. All rights reserved. //(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT //(c)C: This file is a part of CuteHMI. //(c)C: CuteHMI 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. //(c)C: CuteHMI 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. //(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>. //(c)C: Additionally, this file is licensed under terms of MIT license as expressed below. //(c)C: 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: //(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. //(c)C: 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. <|endoftext|>
<commit_before>/* * Copyright 2011 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Box.h" #include <jpeglib.h> #include <png.h> #include <stdio.h> #include <GL/gl.h> #include <boost/bind.hpp> #include "utf.h" namespace org { namespace w3c { namespace dom { namespace bootstrap { // image/png - 89 50 4E 47 0D 0A 1A 0A // image/gif - "GIF87a" or "GIF89a" // image/jpeg - FF D8 // image/bmp - "BM" // image/vnd.microsoft.icon - 00 00 01 00 (.ico), 00 00 02 00 (.cur) namespace { unsigned char* readAsPng(FILE* file, unsigned& width, unsigned& height, unsigned& format) { png_byte header[8]; if (fread(header, 1, 8, file) != 8 || png_sig_cmp(header, 0, 8)) return 0; png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) return 0; png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); return 0; } png_infop end_info = png_create_info_struct(png_ptr); if (!end_info) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return 0; } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); return 0; } png_init_io(png_ptr, file); png_set_sig_bytes(png_ptr, 8); png_read_info(png_ptr, info_ptr); width = png_get_image_width(png_ptr, info_ptr); height = png_get_image_height(png_ptr, info_ptr); unsigned bit_depth = png_get_bit_depth(png_ptr, info_ptr); unsigned color_type = png_get_color_type(png_ptr, info_ptr); if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png_ptr); if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); if (bit_depth == 16) png_set_strip_16(png_ptr); switch (color_type) { case PNG_COLOR_TYPE_RGB: case PNG_COLOR_TYPE_GRAY: case PNG_COLOR_TYPE_PALETTE: format = GL_RGB; break; default: format = GL_RGBA; break; } png_set_interlace_handling(png_ptr); png_read_update_info(png_ptr, info_ptr); unsigned rowbytes = png_get_rowbytes(png_ptr, info_ptr); png_bytep data = (png_bytep) malloc(rowbytes * height); png_bytep* row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height); for (unsigned i = 0; i < height; i++) row_pointers[i] = &data[rowbytes * i]; png_read_image(png_ptr, row_pointers); free(row_pointers); png_read_end(png_ptr, end_info); png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); return data; } unsigned char* readAsJpeg(FILE* file, unsigned& width, unsigned& height, unsigned& format) { unsigned char sig[2]; if (fread(sig, 1, 2, file) != 2 || sig[0] != 0xFF || sig[1] != 0xD8) return 0; rewind(file); JSAMPARRAY img; struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); // TODO: set our own error handdler jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo, file); jpeg_read_header(&cinfo, true); width = cinfo.image_width; height = cinfo.image_height; jpeg_start_decompress(&cinfo); unsigned char* data = (unsigned char*) malloc(height * width * cinfo.out_color_components); img = (JSAMPARRAY) malloc(sizeof(JSAMPROW) * height); for (unsigned i = 0; i < height; ++i) img[i] = (JSAMPROW) &data[cinfo.out_color_components * width * i]; while(cinfo.output_scanline < cinfo.output_height) jpeg_read_scanlines(&cinfo, img + cinfo.output_scanline, cinfo.output_height - cinfo.output_scanline); jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(img); if (cinfo.out_color_components == 1) format = GL_LUMINANCE; else format = GL_RGB; return data; } } // namespace BoxImage::BoxImage(Box* box) : box(box), state(Unavailable), pixels(0), naturalWidth(0), naturalHeight(0), repeat(0), format(GL_RGBA), img(static_cast<html::HTMLImageElement*>(0) /* nullptr */) { } BoxImage::BoxImage(Box* box, const std::u16string& base, const std::u16string& url, unsigned repeat) : box(box), state(Unavailable), pixels(0), naturalWidth(0), naturalHeight(0), repeat(repeat), format(GL_RGBA), img(static_cast<html::HTMLImageElement*>(0) /* nullptr */), request(base) { open(url); } BoxImage::BoxImage(Box* box, const std::u16string& base, html::HTMLImageElement& img) : box(box), state(Unavailable), pixels(0), naturalWidth(0), naturalHeight(0), repeat(Clamp), format(GL_RGBA), img(img), request(base) { open(img.getSrc()); } void BoxImage::open(const std::u16string& url) { request.open(u"GET", url); request.setHanndler(boost::bind(&BoxImage::notify, this)); request.send(); state = Sent; if (request.getReadyState() != HttpRequest::DONE) return; if (request.getErrorFlag()) { state = Broken; return; } FILE* file = request.openFile(); if (!file) { state = Broken; return; } pixels = readAsPng(file, naturalWidth, naturalHeight, format); if (!pixels) { rewind(file); pixels = readAsJpeg(file, naturalWidth, naturalHeight, format); } if (pixels) state = CompletelyAvailable; else state = Broken; fclose(file); } void BoxImage::notify() { if (state == Sent) { if (request.getStatus() == 200) box->flags = 1; // for updating render tree. else state = Unavailable; } } }}}} // org::w3c::dom::bootstrap <commit_msg>(readAsPng) : Support palette images with transparency.<commit_after>/* * Copyright 2011 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Box.h" #include <jpeglib.h> #include <png.h> #include <stdio.h> #include <GL/gl.h> #include <boost/bind.hpp> #include "utf.h" namespace org { namespace w3c { namespace dom { namespace bootstrap { // image/png - 89 50 4E 47 0D 0A 1A 0A // image/gif - "GIF87a" or "GIF89a" // image/jpeg - FF D8 // image/bmp - "BM" // image/vnd.microsoft.icon - 00 00 01 00 (.ico), 00 00 02 00 (.cur) namespace { unsigned char* readAsPng(FILE* file, unsigned& width, unsigned& height, unsigned& format) { png_byte header[8]; if (fread(header, 1, 8, file) != 8 || png_sig_cmp(header, 0, 8)) return 0; png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) return 0; png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); return 0; } png_infop end_info = png_create_info_struct(png_ptr); if (!end_info) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return 0; } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); return 0; } png_init_io(png_ptr, file); png_set_sig_bytes(png_ptr, 8); png_read_info(png_ptr, info_ptr); width = png_get_image_width(png_ptr, info_ptr); height = png_get_image_height(png_ptr, info_ptr); unsigned bit_depth = png_get_bit_depth(png_ptr, info_ptr); unsigned color_type = png_get_color_type(png_ptr, info_ptr); if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png_ptr); if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { png_set_tRNS_to_alpha(png_ptr); color_type = GL_RGBA; } if (bit_depth == 16) png_set_strip_16(png_ptr); switch (color_type) { case PNG_COLOR_TYPE_RGB: case PNG_COLOR_TYPE_GRAY: case PNG_COLOR_TYPE_PALETTE: format = GL_RGB; break; default: format = GL_RGBA; break; } png_set_interlace_handling(png_ptr); png_read_update_info(png_ptr, info_ptr); unsigned rowbytes = png_get_rowbytes(png_ptr, info_ptr); png_bytep data = (png_bytep) malloc(rowbytes * height); png_bytep* row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height); for (unsigned i = 0; i < height; i++) row_pointers[i] = &data[rowbytes * i]; png_read_image(png_ptr, row_pointers); free(row_pointers); png_read_end(png_ptr, end_info); png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); return data; } unsigned char* readAsJpeg(FILE* file, unsigned& width, unsigned& height, unsigned& format) { unsigned char sig[2]; if (fread(sig, 1, 2, file) != 2 || sig[0] != 0xFF || sig[1] != 0xD8) return 0; rewind(file); JSAMPARRAY img; struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); // TODO: set our own error handdler jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo, file); jpeg_read_header(&cinfo, true); width = cinfo.image_width; height = cinfo.image_height; jpeg_start_decompress(&cinfo); unsigned char* data = (unsigned char*) malloc(height * width * cinfo.out_color_components); img = (JSAMPARRAY) malloc(sizeof(JSAMPROW) * height); for (unsigned i = 0; i < height; ++i) img[i] = (JSAMPROW) &data[cinfo.out_color_components * width * i]; while(cinfo.output_scanline < cinfo.output_height) jpeg_read_scanlines(&cinfo, img + cinfo.output_scanline, cinfo.output_height - cinfo.output_scanline); jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(img); if (cinfo.out_color_components == 1) format = GL_LUMINANCE; else format = GL_RGB; return data; } } // namespace BoxImage::BoxImage(Box* box) : box(box), state(Unavailable), pixels(0), naturalWidth(0), naturalHeight(0), repeat(0), format(GL_RGBA), img(static_cast<html::HTMLImageElement*>(0) /* nullptr */) { } BoxImage::BoxImage(Box* box, const std::u16string& base, const std::u16string& url, unsigned repeat) : box(box), state(Unavailable), pixels(0), naturalWidth(0), naturalHeight(0), repeat(repeat), format(GL_RGBA), img(static_cast<html::HTMLImageElement*>(0) /* nullptr */), request(base) { open(url); } BoxImage::BoxImage(Box* box, const std::u16string& base, html::HTMLImageElement& img) : box(box), state(Unavailable), pixels(0), naturalWidth(0), naturalHeight(0), repeat(Clamp), format(GL_RGBA), img(img), request(base) { open(img.getSrc()); } void BoxImage::open(const std::u16string& url) { request.open(u"GET", url); request.setHanndler(boost::bind(&BoxImage::notify, this)); request.send(); state = Sent; if (request.getReadyState() != HttpRequest::DONE) return; if (request.getErrorFlag()) { state = Broken; return; } FILE* file = request.openFile(); if (!file) { state = Broken; return; } pixels = readAsPng(file, naturalWidth, naturalHeight, format); if (!pixels) { rewind(file); pixels = readAsJpeg(file, naturalWidth, naturalHeight, format); } if (pixels) state = CompletelyAvailable; else state = Broken; fclose(file); } void BoxImage::notify() { if (state == Sent) { if (request.getStatus() == 200) box->flags = 1; // for updating render tree. else state = Unavailable; } } }}}} // org::w3c::dom::bootstrap <|endoftext|>
<commit_before>// Filename: luiBaseElement_ext.cxx // Created by: tobspr (18Sep14) // #include "luiBaseElement_ext.h" #include "extension.h" #ifdef HAVE_PYTHON int Extension<LUIBaseElement>::__setattr__(PyObject *self, PyObject *name, PyObject *value) { cout << "__setattr__ (LUIBaseElement) called for '" << name << "'" << endl; PyObject *setter_name = PyString_FromString("set_"); PyString_Concat(&setter_name, name); PyObject *result = PyObject_CallMethodObjArgs(self, setter_name, value, NULL); if (result == NULL) { Py_DECREF(setter_name); return -1; } Py_DECREF(setter_name); Py_DECREF(result); return 0; } PyObject *Extension<LUIBaseElement>::__getattr__(PyObject *self, PyObject *name) { cout << "__getattr__ (LUIBaseElement) called for '" << name << "'" << endl; PyObject *getter_name = PyString_FromString("get_"); PyString_Concat(&getter_name, name); PyObject *getter = PyObject_GenericGetAttr(self, getter_name); if (getter == NULL) { Py_DECREF(getter_name); return NULL; } PyObject *return_value = PyObject_CallObject(getter, NULL); Py_DECREF(getter_name); // Py_DECREF(getter); return return_value; } #endif <commit_msg>Updated the luiBaseElement __setattr_<commit_after>// Filename: luiBaseElement_ext.cxx // Created by: tobspr (18Sep14) // #include "luiBaseElement_ext.h" #include "extension.h" #ifdef HAVE_PYTHON int Extension<LUIBaseElement>::__setattr__(PyObject *self, PyObject *name, PyObject *value) { // Try to find a method called "set_<name>" PyObject *str = PyObject_Str(name); string name_as_str; if (str != NULL) { name_as_str = PyString_AS_STRING(str); } cout << "__setattr__ (LUIBaseElement) called for '" << name_as_str << "'" << endl; if (str != NULL) { Py_DECREF(str); } PyObject *setter_name = PyString_FromString("set_"); PyString_Concat(&setter_name, name); PyObject *result = PyObject_CallMethodObjArgs(self, setter_name, value, NULL); // Did not find any method, that means we save the value in the class dict if (result == NULL) { Py_DECREF(setter_name); // Write to class dictionary cout << "Could not find element, saving in class dict" << endl; PyObject* __dict__ = PyObject_GenericGetAttr(self, (char *)string("__dict__").c_str()); PyDict_SetItem(__dict__, name, value); Py_DECREF(__dict__); return 0; } Py_DECREF(setter_name); Py_DECREF(result); return 0; } PyObject *Extension<LUIBaseElement>::__getattr__(PyObject *self, PyObject *name) { // Try to find a method called "get_<name>" PyObject *str = PyObject_Str(name); string name_as_str; if (str != NULL) { name_as_str = PyString_AS_STRING(str); } cout << "__getattr__ (LUIBaseElement) called for '" << name_as_str << "'" << endl; if (str != NULL) { Py_DECREF(str); } PyObject *getter_name = PyString_FromString("get_"); PyString_Concat(&getter_name, name); PyObject *getter = PyObject_GenericGetAttr(self, getter_name); // No method found, just return, interrogate will fix this for us if (getter == NULL) { Py_DECREF(getter_name); return NULL; } // Calls the "get_<name>" and returns the result PyObject *return_value = PyObject_CallObject(getter, NULL); Py_DECREF(getter_name); return return_value; } #endif <|endoftext|>
<commit_before>/* * TTBlue Audio Signal Class * Copyright © 2008, Timothy Place * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "TTAudioSignal.h" #define thisTTClass TTAudioSignal /****************************************************************************************************/ TTAudioSignal::TTAudioSignal(const TTUInt16 initialMaxNumChannels) : TTObject("audiosignal"), isLocallyOwned(false), maxNumChannels(0), vectorSize(0), numChannels(0), sampleVectors(NULL) { registerAttributeWithSetter(vectorSize, kTypeUInt16); registerAttributeWithSetter(numChannels, kTypeUInt16); registerAttributeWithSetter(maxNumChannels, kTypeUInt16); registerAttributeSimple(bitdepth, kTypeUInt8); addAttributeProperty(bitdepth, readOnly, kTTVal1); registerMessageSimple(clear); registerMessageSimple(alloc); registerMessageWithArgument(allocWithNewVectorSize); registerMessageWithArgument(setVector32); registerMessageWithArgument(getVector32); registerMessageWithArgument(setVector64); registerMessageWithArgument(getVector64); setAttributeValue(TT("maxNumChannels"), initialMaxNumChannels); setAttributeValue(TT("numChannels"), initialMaxNumChannels); } TTAudioSignal::~TTAudioSignal() { chuck(); } void TTAudioSignal::chuck() { TTUInt32 i; if(isLocallyOwned){ for(i=0; i<maxNumChannels; i++){ free(sampleVectors[i]); sampleVectors[i] = NULL; } isLocallyOwned = false; } free(sampleVectors); maxNumChannels = 0; sampleVectors = NULL; } TTErr TTAudioSignal::setmaxNumChannels(const TTValue& newMaxNumChannels) { TTUInt32 i; chuck(); maxNumChannels = newMaxNumChannels; if(maxNumChannels) { sampleVectors = (TTSampleVector *)malloc(sizeof(TTSampleVector) * maxNumChannels); for(i=0; i<maxNumChannels; i++) sampleVectors[i] = NULL; } return kTTErrNone; } TTErr TTAudioSignal::setVector(const TTUInt16 channel, const TTUInt16 newVectorSize, const TTSampleVector newVector) { TTUInt32 i; // could check against maxnumchannels here bitdepth = 64; vectorSize = newVectorSize; if(isLocallyOwned){ for(i=0; i<maxNumChannels; i++){ free(sampleVectors[i]); sampleVectors[i] = NULL; } isLocallyOwned = false; } sampleVectors[channel] = newVector; return kTTErrNone; } TTErr TTAudioSignal::setVector64(const TTValue& v) { TTUInt16 channel; TTUInt16 newVectorSize; TTPtr newVector; if(v.getSize() == 3){ v.get(0, channel); v.get(1, newVectorSize); v.get(2, &newVector); return setVector(channel, newVectorSize, TTSampleVector(newVector)); } return kTTErrGeneric; } /* It sucks if someone sets a 32-bit audio vector, since we have translate it into a 64-bit buffer. There may be a better way to do this... For now, we don't simply reference the data passed in. Instead we allocate our own buffer and copy the data. Unfortunately, this is very slow. Also note that we are relying on the vector size already being set! If we passed the vs in to this method, we could avoid having to realloc the memory every single time. This would probably be a very good idea. */ TTErr TTAudioSignal::setVector(const TTUInt16 channel, const TTUInt16 newVectorSize, const TTFloat32* newVector) { TTUInt32 i; // 1. could check against maxnumchannels here // 2. allocate the vector if need be if(bitdepth != 32 || !isLocallyOwned || newVectorSize != vectorSize) { bitdepth = 32; vectorSize = newVectorSize; alloc(); } // 3. copy the vector (from 32-bits to 64-bits) for(i=0; i<vectorSize; i++) sampleVectors[channel][i] = newVector[i]; return kTTErrNone; } TTErr TTAudioSignal::setVector32(const TTValue& v) { TTUInt16 channel; TTUInt16 newVectorSize; TTPtr newVector; if(v.getSize() == 3){ v.get(0, channel); v.get(1, newVectorSize); v.get(2, &newVector); return setVector(channel, newVectorSize, (TTFloat32*)newVector); } return kTTErrGeneric; } TTErr TTAudioSignal::getVector(const TTUInt16 channel, const TTUInt16 vectorSize, TTSampleVector returnedVector) { returnedVector = sampleVectors[channel]; return kTTErrNone; } TTErr TTAudioSignal::getVector64(TTValue& v) { TTUInt16 channel; TTUInt16 theVectorSize; TTPtr returnedVector; if(v.getSize() == 3){ v.get(0, channel); v.get(1, theVectorSize); v.get(2, &returnedVector); return setVector(channel, theVectorSize, TTSampleVector(returnedVector)); } return kTTErrGeneric; } TTErr TTAudioSignal::getVector(const TTUInt16 channel, const TTUInt16 theVectorSize, TTFloat32* returnedVector) { TTUInt16 i; for(i=0; i<theVectorSize; i++) returnedVector[i] = (TTFloat32)sampleVectors[channel][i]; return kTTErrNone; } TTErr TTAudioSignal::getVector32(TTValue& v) { TTUInt16 channel; TTUInt16 theVectorSize; TTPtr returnedVector; if(v.getSize() == 3){ v.get(0, channel); v.get(1, theVectorSize); v.get(2, &returnedVector); return setVector(channel, theVectorSize, (TTFloat32*)returnedVector); } return kTTErrGeneric; } TTErr TTAudioSignal::alloc() { TTUInt32 i; if(isLocallyOwned){ for(i=0; i<maxNumChannels; i++){ free(sampleVectors[i]); sampleVectors[i] = NULL; } } for(i=0; i<maxNumChannels; i++) { sampleVectors[i] = (TTSampleVector)malloc(sizeof(TTSampleValue) * vectorSize); } isLocallyOwned = maxNumChannels > 0 ? true : false; return kTTErrNone; } TTErr TTAudioSignal::allocWithVectorSize(const TTUInt16 newVectorSize) { if(newVectorSize != vectorSize){ vectorSize = newVectorSize; return alloc(); } else return kTTErrNone; } TTErr TTAudioSignal::allocWithNewVectorSize(const TTValue& newVectorSize) { return allocWithVectorSize(TTUInt16(newVectorSize)); } TTUInt16 TTAudioSignal::getMinChannelCount(const TTAudioSignal& signal1, const TTAudioSignal& signal2) { if(signal1.numChannels > signal2.numChannels) return signal2.numChannels; else return signal1.numChannels; } TTUInt16 TTAudioSignal::getMinChannelCount(const TTAudioSignal& signal1, const TTAudioSignal& signal2, const TTAudioSignal& signal3) { TTUInt16 numChannels = signal1.numChannels; if(signal2.numChannels < numChannels) numChannels = signal2.numChannels; if(signal3.numChannels < numChannels) numChannels = signal3.numChannels; return numChannels; } TTUInt16 TTAudioSignal::getMaxChannelCount(const TTAudioSignal& signal1, const TTAudioSignal& signal2) { if(signal1.numChannels < signal2.numChannels) return signal2.numChannels; else return signal1.numChannels; } TTUInt16 TTAudioSignal::getMaxChannelCount(const TTAudioSignal& signal1, const TTAudioSignal& signal2, const TTAudioSignal& signal3) { TTUInt16 numChannels = signal1.numChannels; if(signal2.numChannels > numChannels) numChannels = signal2.numChannels; if(signal3.numChannels > numChannels) numChannels = signal3.numChannels; return numChannels; } TTUInt16 TTAudioSignal::getNumChannels(const TTAudioSignal& signal) { return signal.numChannels; } // TODO: The old tt audio signal could point to external memory, or allocate its own for the vectors // This enum was used to keep trac of which was the case: // enum selectors{ // k_mode_local = 1, // k_mode_external = 0, //}; // TODO: implement clear() method -- ZERO OUT A VECTOR'S CONTENTS TTErr TTAudioSignal::clear() { TTUInt8 channel; TTUInt16 i; if(!sampleVectors) return kTTErrGeneric; for(channel=0; channel<numChannels; channel++){ for(i=0; i<vectorSize; i++) sampleVectors[channel][i] = 0.0; } return kTTErrNone; } // TODO: implement fill() method --- SET ALL VALUES IN THE SIGNAL TO A CONSTANT <commit_msg>Addressing a shadowed variable warning.<commit_after>/* * TTBlue Audio Signal Class * Copyright © 2008, Timothy Place * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "TTAudioSignal.h" #define thisTTClass TTAudioSignal /****************************************************************************************************/ TTAudioSignal::TTAudioSignal(const TTUInt16 initialMaxNumChannels) : TTObject("audiosignal"), isLocallyOwned(false), maxNumChannels(0), vectorSize(0), numChannels(0), sampleVectors(NULL) { registerAttributeWithSetter(vectorSize, kTypeUInt16); registerAttributeWithSetter(numChannels, kTypeUInt16); registerAttributeWithSetter(maxNumChannels, kTypeUInt16); registerAttributeSimple(bitdepth, kTypeUInt8); addAttributeProperty(bitdepth, readOnly, kTTVal1); registerMessageSimple(clear); registerMessageSimple(alloc); registerMessageWithArgument(allocWithNewVectorSize); registerMessageWithArgument(setVector32); registerMessageWithArgument(getVector32); registerMessageWithArgument(setVector64); registerMessageWithArgument(getVector64); setAttributeValue(TT("maxNumChannels"), initialMaxNumChannels); setAttributeValue(TT("numChannels"), initialMaxNumChannels); } TTAudioSignal::~TTAudioSignal() { chuck(); } void TTAudioSignal::chuck() { TTUInt32 i; if(isLocallyOwned){ for(i=0; i<maxNumChannels; i++){ free(sampleVectors[i]); sampleVectors[i] = NULL; } isLocallyOwned = false; } free(sampleVectors); maxNumChannels = 0; sampleVectors = NULL; } TTErr TTAudioSignal::setmaxNumChannels(const TTValue& newMaxNumChannels) { TTUInt32 i; chuck(); maxNumChannels = newMaxNumChannels; if(maxNumChannels) { sampleVectors = (TTSampleVector *)malloc(sizeof(TTSampleVector) * maxNumChannels); for(i=0; i<maxNumChannels; i++) sampleVectors[i] = NULL; } return kTTErrNone; } TTErr TTAudioSignal::setVector(const TTUInt16 channel, const TTUInt16 newVectorSize, const TTSampleVector newVector) { TTUInt32 i; // could check against maxnumchannels here bitdepth = 64; vectorSize = newVectorSize; if(isLocallyOwned){ for(i=0; i<maxNumChannels; i++){ free(sampleVectors[i]); sampleVectors[i] = NULL; } isLocallyOwned = false; } sampleVectors[channel] = newVector; return kTTErrNone; } TTErr TTAudioSignal::setVector64(const TTValue& v) { TTUInt16 channel; TTUInt16 newVectorSize; TTPtr newVector; if(v.getSize() == 3){ v.get(0, channel); v.get(1, newVectorSize); v.get(2, &newVector); return setVector(channel, newVectorSize, TTSampleVector(newVector)); } return kTTErrGeneric; } /* It sucks if someone sets a 32-bit audio vector, since we have translate it into a 64-bit buffer. There may be a better way to do this... For now, we don't simply reference the data passed in. Instead we allocate our own buffer and copy the data. Unfortunately, this is very slow. Also note that we are relying on the vector size already being set! If we passed the vs in to this method, we could avoid having to realloc the memory every single time. This would probably be a very good idea. */ TTErr TTAudioSignal::setVector(const TTUInt16 channel, const TTUInt16 newVectorSize, const TTFloat32* newVector) { TTUInt32 i; // 1. could check against maxnumchannels here // 2. allocate the vector if need be if(bitdepth != 32 || !isLocallyOwned || newVectorSize != vectorSize) { bitdepth = 32; vectorSize = newVectorSize; alloc(); } // 3. copy the vector (from 32-bits to 64-bits) for(i=0; i<vectorSize; i++) sampleVectors[channel][i] = newVector[i]; return kTTErrNone; } TTErr TTAudioSignal::setVector32(const TTValue& v) { TTUInt16 channel; TTUInt16 newVectorSize; TTPtr newVector; if(v.getSize() == 3){ v.get(0, channel); v.get(1, newVectorSize); v.get(2, &newVector); return setVector(channel, newVectorSize, (TTFloat32*)newVector); } return kTTErrGeneric; } TTErr TTAudioSignal::getVector(const TTUInt16 channel, const TTUInt16 returnedVectorSize, TTSampleVector returnedVector) { returnedVector = sampleVectors[channel]; return kTTErrNone; } TTErr TTAudioSignal::getVector64(TTValue& v) { TTUInt16 channel; TTUInt16 theVectorSize; TTPtr returnedVector; if(v.getSize() == 3){ v.get(0, channel); v.get(1, theVectorSize); v.get(2, &returnedVector); return setVector(channel, theVectorSize, TTSampleVector(returnedVector)); } return kTTErrGeneric; } TTErr TTAudioSignal::getVector(const TTUInt16 channel, const TTUInt16 theVectorSize, TTFloat32* returnedVector) { TTUInt16 i; for(i=0; i<theVectorSize; i++) returnedVector[i] = (TTFloat32)sampleVectors[channel][i]; return kTTErrNone; } TTErr TTAudioSignal::getVector32(TTValue& v) { TTUInt16 channel; TTUInt16 theVectorSize; TTPtr returnedVector; if(v.getSize() == 3){ v.get(0, channel); v.get(1, theVectorSize); v.get(2, &returnedVector); return setVector(channel, theVectorSize, (TTFloat32*)returnedVector); } return kTTErrGeneric; } TTErr TTAudioSignal::alloc() { TTUInt32 i; if(isLocallyOwned){ for(i=0; i<maxNumChannels; i++){ free(sampleVectors[i]); sampleVectors[i] = NULL; } } for(i=0; i<maxNumChannels; i++) { sampleVectors[i] = (TTSampleVector)malloc(sizeof(TTSampleValue) * vectorSize); } isLocallyOwned = maxNumChannels > 0 ? true : false; return kTTErrNone; } TTErr TTAudioSignal::allocWithVectorSize(const TTUInt16 newVectorSize) { if(newVectorSize != vectorSize){ vectorSize = newVectorSize; return alloc(); } else return kTTErrNone; } TTErr TTAudioSignal::allocWithNewVectorSize(const TTValue& newVectorSize) { return allocWithVectorSize(TTUInt16(newVectorSize)); } TTUInt16 TTAudioSignal::getMinChannelCount(const TTAudioSignal& signal1, const TTAudioSignal& signal2) { if(signal1.numChannels > signal2.numChannels) return signal2.numChannels; else return signal1.numChannels; } TTUInt16 TTAudioSignal::getMinChannelCount(const TTAudioSignal& signal1, const TTAudioSignal& signal2, const TTAudioSignal& signal3) { TTUInt16 numChannels = signal1.numChannels; if(signal2.numChannels < numChannels) numChannels = signal2.numChannels; if(signal3.numChannels < numChannels) numChannels = signal3.numChannels; return numChannels; } TTUInt16 TTAudioSignal::getMaxChannelCount(const TTAudioSignal& signal1, const TTAudioSignal& signal2) { if(signal1.numChannels < signal2.numChannels) return signal2.numChannels; else return signal1.numChannels; } TTUInt16 TTAudioSignal::getMaxChannelCount(const TTAudioSignal& signal1, const TTAudioSignal& signal2, const TTAudioSignal& signal3) { TTUInt16 numChannels = signal1.numChannels; if(signal2.numChannels > numChannels) numChannels = signal2.numChannels; if(signal3.numChannels > numChannels) numChannels = signal3.numChannels; return numChannels; } TTUInt16 TTAudioSignal::getNumChannels(const TTAudioSignal& signal) { return signal.numChannels; } // TODO: The old tt audio signal could point to external memory, or allocate its own for the vectors // This enum was used to keep trac of which was the case: // enum selectors{ // k_mode_local = 1, // k_mode_external = 0, //}; // TODO: implement clear() method -- ZERO OUT A VECTOR'S CONTENTS TTErr TTAudioSignal::clear() { TTUInt8 channel; TTUInt16 i; if(!sampleVectors) return kTTErrGeneric; for(channel=0; channel<numChannels; channel++){ for(i=0; i<vectorSize; i++) sampleVectors[channel][i] = 0.0; } return kTTErrNone; } // TODO: implement fill() method --- SET ALL VALUES IN THE SIGNAL TO A CONSTANT <|endoftext|>
<commit_before>/* * Jamoma Dataspace Library * Copyright © 2007 * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTDataspaceConverter.h" #define thisTTClass TTDataspaceConverter #define thisTTClassName "dataspace" #define thisTTClassTags "dataspace.converter" TT_OBJECT_CONSTRUCTOR, mDataspaceTTObject(NULL), mDataspaceObject(NULL) { addAttributeWithSetter(Dataspace, kTypeSymbol); addAttributeWithGetterAndSetter(InputUnit, kTypeSymbol); addAttributeWithGetterAndSetter(OutputUnit, kTypeSymbol); addMessageWithArgument(dictionary); addMessageWithArgument(convert); addMessageWithArgument(getAvailableUnits); addMessageWithArgument(getAvailableDataspaces); setAttributeValue(TT("dataspace"), TT("none")); } TTDataspaceConverter::~TTDataspaceConverter() { TTObjectRelease((TTObjectPtr*)&mDataspaceTTObject); } TTErr TTDataspaceConverter::setDataspace(const TTValue& newValue) { TTSymbolPtr name; TTErr err; TTString objectName = "dataspace."; newValue.get(0, &name); // TODO: validate the name provided before proceeding objectName += name->getString(); err = TTObjectInstantiate(TT(objectName.c_str()), &mDataspaceTTObject, kTTValNONE); if (err) { // Rather than crashing: //throw TTException("Error trying to load dataspace with that name"); // we set it to "none" and post an error message to the log TTLogError("Error trying to load %s, set to none\n", objectName.c_str()); objectName = "dataspace.none"; TTObjectInstantiate(TT(objectName.c_str()), &mDataspaceTTObject, kTTValNONE); } mDataspaceObject = dynamic_cast<TTDataspacePtr>(mDataspaceTTObject); mDataspace = name; return err; } TTErr TTDataspaceConverter::convert(TTValue& io) { TTValue output; TTErr err; err = mDataspaceObject->convert(io, output); io = output; return err; } TTErr TTDataspaceConverter::dictionary(TTValue& input) { TTDictionaryPtr d = NULL; TTValue v; TTErr err; input.get(0, (TTPtr*)(&d)); d->getValue(v); err = convert(v); d->setValue(v); return err; } TTErr TTDataspaceConverter::getInputUnit(TTValue& inUnitName) { inUnitName = mDataspaceObject->getInputUnit(); return kTTErrNone; } TTErr TTDataspaceConverter::setInputUnit(const TTValue& inUnitName) { return mDataspaceObject->setInputUnit(inUnitName); } TTErr TTDataspaceConverter::getOutputUnit(TTValue& outUnitName) { outUnitName = mDataspaceObject->getOutputUnit(); return kTTErrNone; } TTErr TTDataspaceConverter::setOutputUnit(const TTValue& outUnitName) { return mDataspaceObject->setOutputUnit(outUnitName); } TTErr TTDataspaceConverter::getAvailableUnits(TTValue& unitNames) { return mDataspaceObject->getAvailableUnits(unitNames); } TTErr TTDataspaceConverter::getAvailableDataspaces(TTValue& dataspaceNames) { TTErr err; err = TTGetRegisteredClassNamesForTags(dataspaceNames, TT("dataspace")); if (!err) { // strip the leading "dataspace." prefix off all the names for (int i=0; i < dataspaceNames.getSize(); i++) { TTSymbolPtr s; TTString str; dataspaceNames.get(i, &s); str = s->getString(); str.erase(0, 10); s = TT(str); dataspaceNames.set(i, s); } } return err; } <commit_msg>windows: replacing getString with getCString in TTDataspaceConverter.cpp to prevent crashes<commit_after>/* * Jamoma Dataspace Library * Copyright © 2007 * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTDataspaceConverter.h" #define thisTTClass TTDataspaceConverter #define thisTTClassName "dataspace" #define thisTTClassTags "dataspace.converter" TT_OBJECT_CONSTRUCTOR, mDataspaceTTObject(NULL), mDataspaceObject(NULL) { addAttributeWithSetter(Dataspace, kTypeSymbol); addAttributeWithGetterAndSetter(InputUnit, kTypeSymbol); addAttributeWithGetterAndSetter(OutputUnit, kTypeSymbol); addMessageWithArgument(dictionary); addMessageWithArgument(convert); addMessageWithArgument(getAvailableUnits); addMessageWithArgument(getAvailableDataspaces); setAttributeValue(TT("dataspace"), TT("none")); } TTDataspaceConverter::~TTDataspaceConverter() { TTObjectRelease((TTObjectPtr*)&mDataspaceTTObject); } TTErr TTDataspaceConverter::setDataspace(const TTValue& newValue) { TTSymbolPtr name; TTErr err; TTString objectName = "dataspace."; newValue.get(0, &name); // TODO: validate the name provided before proceeding objectName += name->getString(); err = TTObjectInstantiate(TT(objectName.c_str()), &mDataspaceTTObject, kTTValNONE); if (err) { // Rather than crashing: //throw TTException("Error trying to load dataspace with that name"); // we set it to "none" and post an error message to the log TTLogError("Error trying to load %s, set to none\n", objectName.c_str()); objectName = "dataspace.none"; TTObjectInstantiate(TT(objectName.c_str()), &mDataspaceTTObject, kTTValNONE); } mDataspaceObject = dynamic_cast<TTDataspacePtr>(mDataspaceTTObject); mDataspace = name; return err; } TTErr TTDataspaceConverter::convert(TTValue& io) { TTValue output; TTErr err; err = mDataspaceObject->convert(io, output); io = output; return err; } TTErr TTDataspaceConverter::dictionary(TTValue& input) { TTDictionaryPtr d = NULL; TTValue v; TTErr err; input.get(0, (TTPtr*)(&d)); d->getValue(v); err = convert(v); d->setValue(v); return err; } TTErr TTDataspaceConverter::getInputUnit(TTValue& inUnitName) { inUnitName = mDataspaceObject->getInputUnit(); return kTTErrNone; } TTErr TTDataspaceConverter::setInputUnit(const TTValue& inUnitName) { return mDataspaceObject->setInputUnit(inUnitName); } TTErr TTDataspaceConverter::getOutputUnit(TTValue& outUnitName) { outUnitName = mDataspaceObject->getOutputUnit(); return kTTErrNone; } TTErr TTDataspaceConverter::setOutputUnit(const TTValue& outUnitName) { return mDataspaceObject->setOutputUnit(outUnitName); } TTErr TTDataspaceConverter::getAvailableUnits(TTValue& unitNames) { return mDataspaceObject->getAvailableUnits(unitNames); } TTErr TTDataspaceConverter::getAvailableDataspaces(TTValue& dataspaceNames) { TTErr err; err = TTGetRegisteredClassNamesForTags(dataspaceNames, TT("dataspace")); if (!err) { // strip the leading "dataspace." prefix off all the names for (int i=0; i < dataspaceNames.getSize(); i++) { TTSymbolPtr s; //TTString str; const char* cStr; dataspaceNames.get(i, &s); /* str = s->getString(); // this causes crashes on Windows, need to use C string instead str.erase(0, 10); */ cStr = s->getCString() + 10; s = TT(cStr); dataspaceNames.set(i, s); } } return err; } <|endoftext|>
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "test_roudi_service_discovery.hpp" class RoudiFindService_test : public RouDiServiceDiscoveryTest { public: void SetUp() { } void TearDown() { } iox::runtime::PoshRuntime* senderRuntime{&iox::runtime::PoshRuntime::getInstance("/sender")}; iox::runtime::PoshRuntime* receiverRuntime{&iox::runtime::PoshRuntime::getInstance("/receiver")}; }; TEST_F(RoudiFindService_test, OfferSingleMethodServiceSingleInstance) { senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); iox::runtime::InstanceContainer instanceContainer; receiverRuntime->findService({"service1", "instance1"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance1"))); } ///@todo #359 offereService should return bool signalling success/failure TEST_F(RoudiFindService_test, DISABLED_OfferServiceWithDefaultServiceDescriptionFails) { iox::runtime::InstanceContainer instanceContainer; bool isServiceOffered; ///@todo #359 offerService should not allow invalid ServiceDescriptions // isServiceOffered = senderRuntime->offerService(iox::capro::ServiceDescription()); this->InterOpWait(); ASSERT_EQ(false, isServiceOffered); } TEST_F(RoudiFindService_test, ReofferedServiceWithValidServiceDescriptionCanBeFound) { iox::runtime::InstanceContainer instanceContainer; senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); senderRuntime->stopOfferService({"service1", "instance1"}); this->InterOpWait(); senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); receiverRuntime->findService({"service1", "instance1"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance1"))); } TEST_F(RoudiFindService_test, OfferExsistingServiceMultipleTimesIsRedundant) { InstanceContainer instanceContainer; senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); receiverRuntime->findService({"service1", "instance1"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance1"))); } ///@todo #387 findService to return InstanceContainer directly TEST_F(RoudiFindService_test, DISABLED_FindSameServiceMultipleTimesReturnsSingleInstance) { InstanceContainer instanceContainer; senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); receiverRuntime->findService({"service1", "instance1"}, instanceContainer); this->InterOpWait(); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(instanceContainer.at(0), Eq(IdString("instance1"))); receiverRuntime->findService({"service1", "instance1"}, instanceContainer); this->InterOpWait(); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(instanceContainer.at(0), Eq(IdString("instance1"))); } TEST_F(RoudiFindService_test, DISABLED_OfferMultiMethodServiceSingleInstance_PERFORMANCETEST42) { senderRuntime->offerService({"service1", "instance1"}); senderRuntime->offerService({"service2", "instance1"}); senderRuntime->offerService({"service3", "instance1"}); this->InterOpWait(); iox::runtime::InstanceContainer instanceContainer; receiverRuntime->findService({"service1", "instance1"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance1"))); instanceContainer.clear(); receiverRuntime->findService({"service2", "instance1"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance1"))); instanceContainer.clear(); receiverRuntime->findService({"service3", "instance1"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance1"))); } TEST_F(RoudiFindService_test, SubscribeAnyInstance) { senderRuntime->offerService({"service1", "instance1"}); senderRuntime->offerService({"service1", "instance2"}); senderRuntime->offerService({"service1", "instance3"}); this->InterOpWait(); InstanceContainer instanceContainer; InstanceContainer instanceContainerExp; InitContainer(instanceContainerExp, {"instance1", "instance2", "instance3"}); receiverRuntime->findService({"service1", "65535"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(3u)); EXPECT_TRUE(instanceContainer == instanceContainerExp); } TEST_F(RoudiFindService_test, OfferSingleMethodServiceMultiInstance) { senderRuntime->offerService({"service1", "instance1"}); senderRuntime->offerService({"service1", "instance2"}); senderRuntime->offerService({"service1", "instance3"}); this->InterOpWait(); iox::runtime::InstanceContainer instanceContainer; receiverRuntime->findService({"service1", "instance1"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance1"))); instanceContainer.clear(); receiverRuntime->findService({"service1", "instance2"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance2"))); instanceContainer.clear(); receiverRuntime->findService({"service1", "instance3"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance3"))); } TEST_F(RoudiFindService_test, OfferMultiMethodServiceMultiInstance) { senderRuntime->offerService({"service1", "instance1"}); senderRuntime->offerService({"service1", "instance2"}); senderRuntime->offerService({"service1", "instance3"}); senderRuntime->offerService({"service2", "instance1"}); senderRuntime->offerService({"service2", "instance2"}); senderRuntime->offerService({"service2", "instance3"}); this->InterOpWait(); iox::runtime::InstanceContainer instanceContainer; receiverRuntime->findService({"service1", "instance1"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance1"))); instanceContainer.clear(); receiverRuntime->findService({"service1", "instance2"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance2"))); instanceContainer.clear(); receiverRuntime->findService({"service1", "instance3"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance3"))); instanceContainer.clear(); receiverRuntime->findService({"service2", "instance1"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance1"))); instanceContainer.clear(); receiverRuntime->findService({"service2", "instance2"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance2"))); instanceContainer.clear(); receiverRuntime->findService({"service2", "instance3"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance3"))); } TEST_F(RoudiFindService_test, StopOfferSingleMethodServiceSingleInstance) { senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); senderRuntime->stopOfferService({"service1", "instance1"}); this->InterOpWait(); iox::runtime::InstanceContainer instanceContainer; receiverRuntime->findService({"service1", "instance1"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(0u)); } TEST_F(RoudiFindService_test, StopOfferMultiMethodServiceSingleInstance) { senderRuntime->offerService({"service1", "instance1"}); senderRuntime->offerService({"service2", "instance1"}); senderRuntime->offerService({"service3", "instance1"}); this->InterOpWait(); senderRuntime->stopOfferService({"service1", "instance1"}); senderRuntime->stopOfferService({"service3", "instance1"}); this->InterOpWait(); iox::runtime::InstanceContainer instanceContainer; receiverRuntime->findService({"service1", "instance1"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(0u)); instanceContainer.clear(); receiverRuntime->findService({"service2", "instance1"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1u)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance1"))); instanceContainer.clear(); receiverRuntime->findService({"service3", "instance1"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(0u)); } TEST_F(RoudiFindService_test, StopOfferServiceRedundantCall) { iox::runtime::InstanceContainer instanceContainer; senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); senderRuntime->stopOfferService({"service1", "instance1"}); this->InterOpWait(); senderRuntime->stopOfferService({"service1", "instance1"}); this->InterOpWait(); receiverRuntime->findService({"service1", "instance1"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(0u)); } TEST_F(RoudiFindService_test, StopNonExistingService) { iox::runtime::InstanceContainer instanceContainer; senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); senderRuntime->stopOfferService({"service2", "instance2"}); this->InterOpWait(); receiverRuntime->findService({"service1", "instance1"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(1)); ASSERT_THAT(*instanceContainer.begin(), Eq(IdString("instance1"))); } TEST_F(RoudiFindService_test, FindNonExistingServices) { senderRuntime->offerService({"service1", "instance1"}); senderRuntime->offerService({"service2", "instance1"}); senderRuntime->offerService({"service3", "instance1"}); this->InterOpWait(); iox::runtime::InstanceContainer instanceContainer; receiverRuntime->findService({"service1", "schlomo"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(0u)); receiverRuntime->findService({"ignatz", "instance1"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(0u)); receiverRuntime->findService({"ignatz", "schlomo"}, instanceContainer); ASSERT_THAT(instanceContainer.size(), Eq(0u)); } TEST_F(RoudiFindService_test, InterfacePort) { senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); auto interfacePortData = receiverRuntime->getMiddlewareInterface(iox::capro::Interfaces::SOMEIP); iox::popo::InterfacePort interfacePort(interfacePortData); this->InterOpWait(); bool serviceFound = false; while (auto maybeCaProMessage = interfacePort.tryGetCaProMessage()) { auto caproMessage = maybeCaProMessage.value(); if ((caproMessage.m_serviceDescription.getServiceIDString() == IdString("service1")) && (caproMessage.m_serviceDescription.getInstanceIDString() == IdString("instance1")) && ((caproMessage.m_serviceDescription.getEventIDString() == IdString(iox::capro::AnyEventString)))) { serviceFound = true; break; } } EXPECT_THAT(serviceFound, Eq(true)); } TEST_F(RoudiFindService_test, findServiceMaxInstances) { size_t noOfInstances = iox::MAX_NUMBER_OF_INSTANCES; InstanceContainer instanceContainerExp; for (size_t i = 0; i < noOfInstances; i++) { // Service & Instance string is kept short , to reduce the response size in find service request , // (message queue has a limit of 512) std::string instance = "i" + std::to_string(i); senderRuntime->offerService({"s", IdString(iox::cxx::TruncateToCapacity, instance)}); instanceContainerExp.push_back(IdString(iox::cxx::TruncateToCapacity, instance)); this->InterOpWait(); } iox::runtime::InstanceContainer instanceContainer; auto status = receiverRuntime->findService({"s", "65535"}, instanceContainer); EXPECT_THAT(instanceContainer.size(), Eq(iox::MAX_NUMBER_OF_INSTANCES)); EXPECT_TRUE(instanceContainer == instanceContainerExp); ASSERT_THAT(status.has_error(), Eq(false)); } TEST_F(RoudiFindService_test, findServiceInstanceContainerOverflowError) { size_t noOfInstances = (iox::MAX_NUMBER_OF_INSTANCES + 1); InstanceContainer instanceContainerExp; for (size_t i = 0; i < noOfInstances; i++) { std::string instance = "i" + std::to_string(i); senderRuntime->offerService({"s", IdString(iox::cxx::TruncateToCapacity, instance)}); instanceContainerExp.push_back(IdString(iox::cxx::TruncateToCapacity, instance)); this->InterOpWait(); } iox::runtime::InstanceContainer instanceContainer; auto status = receiverRuntime->findService({"s", "65535"}, instanceContainer); EXPECT_THAT(instanceContainer.size(), Eq(iox::MAX_NUMBER_OF_INSTANCES)); EXPECT_TRUE(instanceContainer == instanceContainerExp); ASSERT_THAT(status.has_error(), Eq(true)); } <commit_msg>iox-#240 adapted signature change of findservice()<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "test_roudi_service_discovery.hpp" class RoudiFindService_test : public RouDiServiceDiscoveryTest { public: void SetUp() { } void TearDown() { } iox::runtime::PoshRuntime* senderRuntime{&iox::runtime::PoshRuntime::getInstance("/sender")}; iox::runtime::PoshRuntime* receiverRuntime{&iox::runtime::PoshRuntime::getInstance("/receiver")}; }; TEST_F(RoudiFindService_test, OfferSingleMethodServiceSingleInstance) { senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); auto instanceContainer = receiverRuntime->findService({"service1", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance1"))); } ///@todo #359 offereService should return bool signalling success/failure TEST_F(RoudiFindService_test, DISABLED_OfferServiceWithDefaultServiceDescriptionFails) { iox::runtime::InstanceContainer instanceContainer; bool isServiceOffered; ///@todo #359 offerService should not allow invalid ServiceDescriptions // isServiceOffered = senderRuntime->offerService(iox::capro::ServiceDescription()); this->InterOpWait(); ASSERT_EQ(false, isServiceOffered); } TEST_F(RoudiFindService_test, ReofferedServiceWithValidServiceDescriptionCanBeFound) { senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); senderRuntime->stopOfferService({"service1", "instance1"}); this->InterOpWait(); senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); auto instanceContainer = receiverRuntime->findService({"service1", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance1"))); } TEST_F(RoudiFindService_test, OfferExsistingServiceMultipleTimesIsRedundant) { senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); auto instanceContainer = receiverRuntime->findService({"service1", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance1"))); } TEST_F(RoudiFindService_test, FindSameServiceMultipleTimesReturnsSingleInstance) { senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); auto instanceContainer = receiverRuntime->findService({"service1", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance1"))); instanceContainer = receiverRuntime->findService({"service1", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance1"))); } TEST_F(RoudiFindService_test, DISABLED_OfferMultiMethodServiceSingleInstance_PERFORMANCETEST42) { senderRuntime->offerService({"service1", "instance1"}); senderRuntime->offerService({"service2", "instance1"}); senderRuntime->offerService({"service3", "instance1"}); this->InterOpWait(); auto instanceContainer = receiverRuntime->findService({"service1", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance1"))); instanceContainer = receiverRuntime->findService({"service2", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance1"))); instanceContainer = receiverRuntime->findService({"service3", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance1"))); } TEST_F(RoudiFindService_test, SubscribeAnyInstance) { senderRuntime->offerService({"service1", "instance1"}); senderRuntime->offerService({"service1", "instance2"}); senderRuntime->offerService({"service1", "instance3"}); this->InterOpWait(); InstanceContainer instanceContainerExp; InitContainer(instanceContainerExp, {"instance1", "instance2", "instance3"}); auto instanceContainer = receiverRuntime->findService({"service1", "65535"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(3u)); EXPECT_TRUE(instanceContainer.get_value() == instanceContainerExp); } TEST_F(RoudiFindService_test, OfferSingleMethodServiceMultiInstance) { senderRuntime->offerService({"service1", "instance1"}); senderRuntime->offerService({"service1", "instance2"}); senderRuntime->offerService({"service1", "instance3"}); this->InterOpWait(); auto instanceContainer = receiverRuntime->findService({"service1", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance1"))); instanceContainer = receiverRuntime->findService({"service1", "instance2"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance2"))); instanceContainer = receiverRuntime->findService({"service1", "instance3"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance3"))); } TEST_F(RoudiFindService_test, OfferMultiMethodServiceMultiInstance) { senderRuntime->offerService({"service1", "instance1"}); senderRuntime->offerService({"service1", "instance2"}); senderRuntime->offerService({"service1", "instance3"}); senderRuntime->offerService({"service2", "instance1"}); senderRuntime->offerService({"service2", "instance2"}); senderRuntime->offerService({"service2", "instance3"}); this->InterOpWait(); auto instanceContainer = receiverRuntime->findService({"service1", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance1"))); instanceContainer = receiverRuntime->findService({"service1", "instance2"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance2"))); instanceContainer = receiverRuntime->findService({"service1", "instance3"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance3"))); instanceContainer = receiverRuntime->findService({"service2", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance1"))); instanceContainer = receiverRuntime->findService({"service2", "instance2"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance2"))); instanceContainer = receiverRuntime->findService({"service2", "instance3"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance3"))); } TEST_F(RoudiFindService_test, StopOfferSingleMethodServiceSingleInstance) { senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); senderRuntime->stopOfferService({"service1", "instance1"}); this->InterOpWait(); auto instanceContainer = receiverRuntime->findService({"service1", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(0u)); } TEST_F(RoudiFindService_test, StopOfferMultiMethodServiceSingleInstance) { senderRuntime->offerService({"service1", "instance1"}); senderRuntime->offerService({"service2", "instance1"}); senderRuntime->offerService({"service3", "instance1"}); this->InterOpWait(); senderRuntime->stopOfferService({"service1", "instance1"}); senderRuntime->stopOfferService({"service3", "instance1"}); this->InterOpWait(); auto instanceContainer = receiverRuntime->findService({"service1", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(0u)); instanceContainer = receiverRuntime->findService({"service2", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance1"))); instanceContainer = receiverRuntime->findService({"service3", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(0u)); } TEST_F(RoudiFindService_test, StopOfferServiceRedundantCall) { senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); senderRuntime->stopOfferService({"service1", "instance1"}); this->InterOpWait(); senderRuntime->stopOfferService({"service1", "instance1"}); this->InterOpWait(); auto instanceContainer = receiverRuntime->findService({"service1", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(0u)); } TEST_F(RoudiFindService_test, StopNonExistingService) { senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); senderRuntime->stopOfferService({"service2", "instance2"}); this->InterOpWait(); auto instanceContainer = receiverRuntime->findService({"service1", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(1)); ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString("instance1"))); } TEST_F(RoudiFindService_test, FindNonExistingServices) { senderRuntime->offerService({"service1", "instance1"}); senderRuntime->offerService({"service2", "instance1"}); senderRuntime->offerService({"service3", "instance1"}); this->InterOpWait(); auto instanceContainer = receiverRuntime->findService({"service1", "schlomo"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(0u)); instanceContainer = receiverRuntime->findService({"ignatz", "instance1"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(0u)); instanceContainer = receiverRuntime->findService({"ignatz", "schlomo"}); ASSERT_THAT(instanceContainer.get_value().size(), Eq(0u)); } TEST_F(RoudiFindService_test, InterfacePort) { senderRuntime->offerService({"service1", "instance1"}); this->InterOpWait(); auto interfacePortData = receiverRuntime->getMiddlewareInterface(iox::capro::Interfaces::SOMEIP); iox::popo::InterfacePort interfacePort(interfacePortData); this->InterOpWait(); bool serviceFound = false; while (auto maybeCaProMessage = interfacePort.tryGetCaProMessage()) { auto caproMessage = maybeCaProMessage.value(); if ((caproMessage.m_serviceDescription.getServiceIDString() == IdString("service1")) && (caproMessage.m_serviceDescription.getInstanceIDString() == IdString("instance1")) && ((caproMessage.m_serviceDescription.getEventIDString() == IdString(iox::capro::AnyEventString)))) { serviceFound = true; break; } } EXPECT_THAT(serviceFound, Eq(true)); } TEST_F(RoudiFindService_test, findServiceMaxInstances) { size_t noOfInstances = iox::MAX_NUMBER_OF_INSTANCES; InstanceContainer instanceContainerExp; for (size_t i = 0; i < noOfInstances; i++) { // Service & Instance string is kept short , to reduce the response size in find service request , // (message queue has a limit of 512) std::string instance = "i" + std::to_string(i); senderRuntime->offerService({"s", IdString(iox::cxx::TruncateToCapacity, instance)}); instanceContainerExp.push_back(IdString(iox::cxx::TruncateToCapacity, instance)); this->InterOpWait(); } auto instanceContainer = receiverRuntime->findService({"s", "65535"}); EXPECT_THAT(instanceContainer.get_value().size(), Eq(iox::MAX_NUMBER_OF_INSTANCES)); EXPECT_TRUE(instanceContainer.get_value() == instanceContainerExp); ASSERT_THAT(instanceContainer.has_error(), Eq(false)); } TEST_F(RoudiFindService_test, findServiceInstanceContainerOverflowError) { size_t noOfInstances = (iox::MAX_NUMBER_OF_INSTANCES + 1); InstanceContainer instanceContainerExp; for (size_t i = 0; i < noOfInstances; i++) { std::string instance = "i" + std::to_string(i); senderRuntime->offerService({"s", IdString(iox::cxx::TruncateToCapacity, instance)}); instanceContainerExp.push_back(IdString(iox::cxx::TruncateToCapacity, instance)); this->InterOpWait(); } auto instanceContainer = receiverRuntime->findService({"s", "65535"}); ASSERT_THAT(instanceContainer.has_error(), Eq(true)); } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperQtWidgetFloatParameter.h" namespace otb { namespace Wrapper { QtWidgetFloatParameter::QtWidgetFloatParameter(FloatParameter* floatParam, QtWidgetModel* m) : QtWidgetParameterBase(floatParam, m), m_FloatParam(floatParam) { } QtWidgetFloatParameter::~QtWidgetFloatParameter() { } void QtWidgetFloatParameter::DoUpdateGUI() { // TODO : search for a better solution m_QDoubleSpinBox->setRange(m_FloatParam->GetMinimumValue(), m_FloatParam->GetMaximumValue()); bool signalsBlocked = m_QDoubleSpinBox->blockSignals( true ); if (m_FloatParam->HasValue()) { m_QDoubleSpinBox->setValue(m_FloatParam->GetValue()); } m_QDoubleSpinBox->blockSignals( signalsBlocked ); QFont font = m_QDoubleSpinBox->font(); if (m_FloatParam->HasUserValue()) { font.setBold(true); } else { font.setBold(false); } m_QDoubleSpinBox->setFont(font); } void QtWidgetFloatParameter::DoCreateWidget() { m_QHBoxLayout = new QHBoxLayout; m_QHBoxLayout->setSpacing(0); m_QHBoxLayout->setContentsMargins(0, 0, 0, 0); m_QDoubleSpinBox = new QDoubleSpinBox; m_QDoubleSpinBox->setDecimals(5); m_QDoubleSpinBox->setSingleStep(0.1); m_QDoubleSpinBox->setRange(m_FloatParam->GetMinimumValue(), m_FloatParam->GetMaximumValue()); m_QDoubleSpinBox->setToolTip(m_FloatParam->GetDescription()); connect( m_QDoubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(SetValue(double)) ); connect( m_QDoubleSpinBox, SIGNAL(valueChanged(double)), GetModel(), SLOT(NotifyUpdate()) ); connect( GetModel(), SIGNAL(UpdateGui()), this, SLOT(UpdateGUI() ) ); m_QHBoxLayout->addWidget(m_QDoubleSpinBox); m_QHBoxLayout->addStretch(); this->setLayout(m_QHBoxLayout); } void QtWidgetFloatParameter::SetValue(double value) { m_FloatParam->SetValue( static_cast<float>(value) ); m_FloatParam->SetUserValue(true); } } } <commit_msg>ENH: turning AutomaticValue to Off when a UserValue is set<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperQtWidgetFloatParameter.h" namespace otb { namespace Wrapper { QtWidgetFloatParameter::QtWidgetFloatParameter(FloatParameter* floatParam, QtWidgetModel* m) : QtWidgetParameterBase(floatParam, m), m_FloatParam(floatParam) { } QtWidgetFloatParameter::~QtWidgetFloatParameter() { } void QtWidgetFloatParameter::DoUpdateGUI() { // TODO : search for a better solution m_QDoubleSpinBox->setRange(m_FloatParam->GetMinimumValue(), m_FloatParam->GetMaximumValue()); bool signalsBlocked = m_QDoubleSpinBox->blockSignals( true ); if (m_FloatParam->HasValue()) { m_QDoubleSpinBox->setValue(m_FloatParam->GetValue()); } m_QDoubleSpinBox->blockSignals( signalsBlocked ); QFont font = m_QDoubleSpinBox->font(); if (m_FloatParam->HasUserValue()) { font.setBold(true); } else { font.setBold(false); } m_QDoubleSpinBox->setFont(font); } void QtWidgetFloatParameter::DoCreateWidget() { m_QHBoxLayout = new QHBoxLayout; m_QHBoxLayout->setSpacing(0); m_QHBoxLayout->setContentsMargins(0, 0, 0, 0); m_QDoubleSpinBox = new QDoubleSpinBox; m_QDoubleSpinBox->setDecimals(5); m_QDoubleSpinBox->setSingleStep(0.1); m_QDoubleSpinBox->setRange(m_FloatParam->GetMinimumValue(), m_FloatParam->GetMaximumValue()); m_QDoubleSpinBox->setToolTip(m_FloatParam->GetDescription()); connect( m_QDoubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(SetValue(double)) ); connect( m_QDoubleSpinBox, SIGNAL(valueChanged(double)), GetModel(), SLOT(NotifyUpdate()) ); connect( GetModel(), SIGNAL(UpdateGui()), this, SLOT(UpdateGUI() ) ); m_QHBoxLayout->addWidget(m_QDoubleSpinBox); m_QHBoxLayout->addStretch(); this->setLayout(m_QHBoxLayout); } void QtWidgetFloatParameter::SetValue(double value) { m_FloatParam->SetValue( static_cast<float>(value) ); m_FloatParam->SetUserValue(true); m_FloatParam->SetAutomaticValue(false); } } } <|endoftext|>
<commit_before>/** ** \file object/object-class.cc ** \brief Creation of the URBI object object. */ //#define ENABLE_DEBUG_TRACES #include <boost/bind.hpp> #include <libport/compiler.hh> #include <libport/containers.hh> #include <libport/escape.hh> #include <libport/foreach.hh> #include <libport/tokenizer.hh> #include <kernel/uconnection.hh> #include <object/cxx-primitive.hh> #include <object/float.hh> #include <object/global.hh> #include <object/list.hh> #include <object/object.hh> #include <object/object.hh> #include <object/string.hh> #include <runner/call.hh> #include <runner/runner.hh> namespace object { rObject object_class; /*--------------------. | Object primitives. | `--------------------*/ static rObject object_class_clone (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 0); return args[0]->clone(); } static rObject object_class_init (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 0); return args[0]; } /// Send dumped self on the connection. /// args[1], if present, can be the tag to use. static rObject object_class_dump (runner::Runner& r, objects_type& args) { check_arg_count(args.size() - 1, 1, 2); // Second argument is max depth. int depth_max = 0; if (args.size() >= 2) { type_check(args[1], Float::proto); const rFloat& arg1 = args[1]->as<Float>(); try { depth_max = libport::ufloat_to_int(arg1->value_get()); } catch (libport::bad_numeric_cast& ue) { throw BadInteger(arg1->value_get(), SYMBOL(dump)); } } // Third argument is the tag name. std::string tag; if (args.size() >= 3) { const rString& arg2 = args[2].unsafe_cast<String>(); assert(arg2); tag = arg2->value_get(); } std::ostringstream os; args[0]->dump(os, r, depth_max); //for now our best choice is to dump line by line in "system" messages. const std::string stream = os.str(); boost::tokenizer< boost::char_separator<char> > tok = libport::make_tokenizer(stream, "\n"); const std::string system_header("*** "); foreach(const std::string& line, tok) r.send_message(tag, system_header+line); return void_class; } /// Return the address of an object as a number, mostly /// for debugging purpose. static rObject object_class_uid (runner::Runner&, objects_type& args) { static boost::format uid("0x%x"); check_arg_count(args.size() - 1, 0); return new String(str(uid % reinterpret_cast<long long>(args[0].get()))); } /// Structural equality static rObject object_class_EQ_EQ(runner::Runner& r, objects_type& args) { // Unless overridden, structural equality is physical equality. check_arg_count(args.size() - 1, 1); return urbi_call(r, args[0], SYMBOL(EQ_EQ_EQ), args[1]); } /// Physical equality static rObject object_class_EQ_EQ_EQ(runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 1); return to_boolean(args[0] == args[1]); } static rObject object_class_apply(runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 1); type_check(args[1], List::proto); const rList& arg1 = args[1]->as<List>(); if (arg1->value_get ().size () != 1 || arg1->value_get().front() != args[0]) throw PrimitiveError(SYMBOL(apply), "first argument must be [this]"); return arg1->value_get().front(); } static rObject object_class_callMessage (runner::Runner& r, objects_type& args) { check_arg_count(args.size() - 1, 1); // We need to set the 'code' slot: make a copy of the call message. rObject call_message = args[1]->clone(); const rObject& message = call_message->slot_get(SYMBOL(message)); type_check(message, String::proto); const libport::Symbol msg = libport::Symbol(message->as<String>()->value_get()); const rObject& target = args[0]; const rObject& code = target->slot_get(msg); call_message->slot_update(r, SYMBOL(code), code); call_message->slot_update(r, SYMBOL(target), target); // FIXME: Sanity checks on the call message are probably required return r.apply_call_message(code, msg, call_message); } /*---------. | Protos. | `---------*/ /// Adding or removing protos. \a Verb is "add" or "remove". #define CHANGE_PARENTS(Verb) \ static rObject \ object_class_ ## Verb ## Proto (runner::Runner&, \ objects_type& args) \ { \ check_arg_count(args.size() - 1, 1); \ args[0]->proto_ ## Verb (args[1]); \ return args[0]; \ } /// Add a proto. CHANGE_PARENTS(add); /// Remove a proto. CHANGE_PARENTS(remove); #undef CHANGE_PARENTS /// Get protos' list. static rObject object_class_protos (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 0); return args[0]->urbi_protos_get (); } /// Recursively get protos list static bool proto_add(List::value_type& protos, const rObject& proto) { protos.push_back(proto); return false; } static rObject object_class_allProtos(runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 0); List::value_type res; for_all_protos(args[0], boost::bind(&proto_add, boost::ref(res), _1)); return new List(res); } /*--------. | Slots. | `--------*/ template <typename F> static inline void for_all_slot_names(const rObject& o, F f) { for (Object::slots_implem::iterator slot = o->slots_get().begin(o.get()); slot != o->slots_get().end(o.get()); ++slot) f(slot->first.second); } static void add_as_rString(List::value_type& l, libport::Symbol slot_name) { l.push_back(new String(slot_name)); } /// List of slot names. static rObject object_class_slotNames (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 0); const rObject& obj = args[0]; List::value_type l; for_all_slot_names(obj, boost::bind(&add_as_rString, boost::ref(l), _1)); return new List(l); } /// Recursive list of slot names. static void maybe_add(std::vector<libport::Symbol>& control, List::value_type& l, libport::Symbol slot_name) { if (!libport::has(control, slot_name)) { control.push_back(slot_name); l.push_back(new String(slot_name)); } } static rObject object_class_allSlotNames(runner::Runner& r, objects_type& args) { check_arg_count(args.size() - 1, 0); std::vector<libport::Symbol> slot_names; List::value_type res; objects_type protos = object_class_allProtos(r, args)->as<List>()->value_get(); foreach (const rObject& proto, protos) { for_all_slot_names(proto, boost::bind(&maybe_add, boost::ref(slot_names), boost::ref(res), _1)); } return new List(res); } /// Get a slot content. static rObject object_class_getSlot (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 1); const rObject& obj = args[0]; const rString& arg1 = args[1].unsafe_cast<String>(); assert(arg1); return obj->slot_get(libport::Symbol(arg1->value_get())); } // self.getLazyLocalSlot(SLOT-NAME, DEFAULT-VALUE, CREATE?). static rObject object_class_getLazyLocalSlot (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 3); const rString& arg1 = args[1].unsafe_cast<String>(); assert(arg1); const Object::key_type& slot_name = libport::Symbol(arg1->value_get()); // If the slot already exists, return its content. if (rObject slot = args[0]->own_slot_get (slot_name)) return slot; // The slot doesn't exist. Should we create it? if (is_true (args[3], SYMBOL(getLazyLocalSlot))) args[0]->slot_set (slot_name, args[2]); // Return the default value for this slot. return args[2]; } /// Remove a slot. static rObject object_class_removeSlot (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 1); const rObject& obj = args[0]; const rString& arg1 = args[1].unsafe_cast<String>(); assert(arg1); obj->slot_remove(libport::Symbol(arg1->value_get())); return obj; } /// Locate a slot. static rObject object_class_locateSlot (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 1); const rString& arg1 = args[1].unsafe_cast<String>(); assert(arg1); rObject o = args[0]->slot_locate(libport::Symbol(arg1->value_get())); return o ? o : nil_class; } static rObject object_class_setSlot (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 2); const rString& arg1 = args[1].unsafe_cast<String>(); assert(arg1); args[0]->slot_set(libport::Symbol(arg1->value_get()), args[2]); return args[2]; } static rObject object_class_createSlot (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 1); const rString& arg1 = args[1].unsafe_cast<String>(); assert(arg1); args[0]->slot_set(libport::Symbol(arg1->value_get()), void_class); return void_class; } static rObject object_class_updateSlot (runner::Runner& r, objects_type& args) { check_arg_count(args.size() - 1, 2); const rString& arg1 = args[1].unsafe_cast<String>(); assert(arg1); return args[0]->slot_update(r, libport::Symbol(arg1->value_get()), args[2]); } static bool object_class_isA(rObject self, rObject proto) { return is_a(self, proto); } void object_class_initialize () { object_class->slot_set(SYMBOL(isA), make_primitive(object_class_isA, SYMBOL(isA))); /// \a Call gives the name of the C++ function, and \a Name that in Urbi. #define DECLARE(Name) \ DECLARE_PRIMITIVE(object, Name) DECLARE(addProto); DECLARE(allProtos); DECLARE(allSlotNames); DECLARE(apply); DECLARE(callMessage); DECLARE(clone); DECLARE(dump); DECLARE(getLazyLocalSlot); DECLARE(getSlot); DECLARE(init); DECLARE(locateSlot); DECLARE(EQ_EQ_EQ); DECLARE(protos); DECLARE(removeProto); DECLARE(removeSlot); DECLARE(EQ_EQ); DECLARE(setSlot); DECLARE(createSlot); DECLARE(slotNames); DECLARE(uid); DECLARE(updateSlot); #undef DECLARE #define DECLARE(Name, Code) \ object_class->slot_set(SYMBOL(Name), make_primitive(Code, SYMBOL(Name))) DECLARE(getProperty, &Object::property_get); DECLARE(hasProperty, &Object::property_has); DECLARE(hasSlot, &Object::slot_has); DECLARE(setProperty, &Object::property_set); DECLARE(removeProperty, &Object::property_remove); #undef DECLARE } }; // namespace object <commit_msg>Formatting changes.<commit_after>/** ** \file object/object-class.cc ** \brief Creation of the URBI object object. */ //#define ENABLE_DEBUG_TRACES #include <boost/bind.hpp> #include <libport/compiler.hh> #include <libport/containers.hh> #include <libport/escape.hh> #include <libport/foreach.hh> #include <libport/tokenizer.hh> #include <kernel/uconnection.hh> #include <object/cxx-primitive.hh> #include <object/float.hh> #include <object/global.hh> #include <object/list.hh> #include <object/object.hh> #include <object/object.hh> #include <object/string.hh> #include <runner/call.hh> #include <runner/runner.hh> namespace object { rObject object_class; /*--------------------. | Object primitives. | `--------------------*/ static rObject object_class_clone (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 0); return args[0]->clone(); } static rObject object_class_init (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 0); return args[0]; } /// Send dumped self on the connection. /// args[1], if present, can be the tag to use. static rObject object_class_dump (runner::Runner& r, objects_type& args) { check_arg_count(args.size() - 1, 1, 2); // Second argument is max depth. int depth_max = 0; if (args.size() >= 2) { type_check(args[1], Float::proto); const rFloat& arg1 = args[1]->as<Float>(); try { depth_max = libport::ufloat_to_int(arg1->value_get()); } catch (libport::bad_numeric_cast& ue) { throw BadInteger(arg1->value_get(), SYMBOL(dump)); } } // Third argument is the tag name. std::string tag; if (args.size() >= 3) { const rString& arg2 = args[2].unsafe_cast<String>(); assert(arg2); tag = arg2->value_get(); } std::ostringstream os; args[0]->dump(os, r, depth_max); //for now our best choice is to dump line by line in "system" messages. const std::string stream = os.str(); boost::tokenizer< boost::char_separator<char> > tok = libport::make_tokenizer(stream, "\n"); const std::string system_header("*** "); foreach(const std::string& line, tok) r.send_message(tag, system_header+line); return void_class; } /// Return the address of an object as a number, mostly /// for debugging purpose. static rObject object_class_uid (runner::Runner&, objects_type& args) { static boost::format uid("0x%x"); check_arg_count(args.size() - 1, 0); return new String(str(uid % reinterpret_cast<long long>(args[0].get()))); } /// Structural equality static rObject object_class_EQ_EQ(runner::Runner& r, objects_type& args) { // Unless overridden, structural equality is physical equality. check_arg_count(args.size() - 1, 1); return urbi_call(r, args[0], SYMBOL(EQ_EQ_EQ), args[1]); } /// Physical equality static rObject object_class_EQ_EQ_EQ(runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 1); return to_boolean(args[0] == args[1]); } static rObject object_class_apply(runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 1); type_check(args[1], List::proto); const rList& arg1 = args[1]->as<List>(); if (arg1->value_get ().size () != 1 || arg1->value_get().front() != args[0]) throw PrimitiveError(SYMBOL(apply), "first argument must be [this]"); return arg1->value_get().front(); } static rObject object_class_callMessage (runner::Runner& r, objects_type& args) { check_arg_count(args.size() - 1, 1); // We need to set the 'code' slot: make a copy of the call message. rObject call_message = args[1]->clone(); const rObject& message = call_message->slot_get(SYMBOL(message)); type_check(message, String::proto); const libport::Symbol msg(message->as<String>()->value_get()); const rObject& target = args[0]; const rObject& code = target->slot_get(msg); call_message->slot_update(r, SYMBOL(code), code); call_message->slot_update(r, SYMBOL(target), target); // FIXME: Sanity checks on the call message are probably required return r.apply_call_message(code, msg, call_message); } /*---------. | Protos. | `---------*/ /// Adding or removing protos. \a Verb is "add" or "remove". #define CHANGE_PARENTS(Verb) \ static rObject \ object_class_ ## Verb ## Proto (runner::Runner&, \ objects_type& args) \ { \ check_arg_count(args.size() - 1, 1); \ args[0]->proto_ ## Verb (args[1]); \ return args[0]; \ } /// Add a proto. CHANGE_PARENTS(add); /// Remove a proto. CHANGE_PARENTS(remove); #undef CHANGE_PARENTS /// Get protos' list. static rObject object_class_protos (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 0); return args[0]->urbi_protos_get (); } /// Recursively get protos list static bool proto_add(List::value_type& protos, const rObject& proto) { protos.push_back(proto); return false; } static rObject object_class_allProtos(runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 0); List::value_type res; for_all_protos(args[0], boost::bind(&proto_add, boost::ref(res), _1)); return new List(res); } /*--------. | Slots. | `--------*/ template <typename F> static inline void for_all_slot_names(const rObject& o, F f) { for (Object::slots_implem::iterator slot = o->slots_get().begin(o.get()); slot != o->slots_get().end(o.get()); ++slot) f(slot->first.second); } static void add_as_rString(List::value_type& l, libport::Symbol slot_name) { l.push_back(new String(slot_name)); } /// List of slot names. static rObject object_class_slotNames (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 0); const rObject& obj = args[0]; List::value_type l; for_all_slot_names(obj, boost::bind(&add_as_rString, boost::ref(l), _1)); return new List(l); } /// Recursive list of slot names. static void maybe_add(std::vector<libport::Symbol>& control, List::value_type& l, libport::Symbol slot_name) { if (!libport::has(control, slot_name)) { control.push_back(slot_name); l.push_back(new String(slot_name)); } } static rObject object_class_allSlotNames(runner::Runner& r, objects_type& args) { check_arg_count(args.size() - 1, 0); std::vector<libport::Symbol> slot_names; List::value_type res; objects_type protos = object_class_allProtos(r, args)->as<List>()->value_get(); foreach (const rObject& proto, protos) { for_all_slot_names(proto, boost::bind(&maybe_add, boost::ref(slot_names), boost::ref(res), _1)); } return new List(res); } /// Get a slot content. static rObject object_class_getSlot (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 1); const rObject& obj = args[0]; const rString& arg1 = args[1].unsafe_cast<String>(); assert(arg1); return obj->slot_get(libport::Symbol(arg1->value_get())); } // self.getLazyLocalSlot(SLOT-NAME, DEFAULT-VALUE, CREATE?). static rObject object_class_getLazyLocalSlot (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 3); const rString& arg1 = args[1].unsafe_cast<String>(); assert(arg1); const Object::key_type& slot_name = libport::Symbol(arg1->value_get()); // If the slot already exists, return its content. if (rObject slot = args[0]->own_slot_get (slot_name)) return slot; // The slot doesn't exist. Should we create it? if (is_true (args[3], SYMBOL(getLazyLocalSlot))) args[0]->slot_set (slot_name, args[2]); // Return the default value for this slot. return args[2]; } /// Remove a slot. static rObject object_class_removeSlot (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 1); const rObject& obj = args[0]; const rString& arg1 = args[1].unsafe_cast<String>(); assert(arg1); obj->slot_remove(libport::Symbol(arg1->value_get())); return obj; } /// Locate a slot. static rObject object_class_locateSlot (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 1); const rString& arg1 = args[1].unsafe_cast<String>(); assert(arg1); rObject o = args[0]->slot_locate(libport::Symbol(arg1->value_get())); return o ? o : nil_class; } static rObject object_class_setSlot (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 2); const rString& arg1 = args[1].unsafe_cast<String>(); assert(arg1); args[0]->slot_set(libport::Symbol(arg1->value_get()), args[2]); return args[2]; } static rObject object_class_createSlot (runner::Runner&, objects_type& args) { check_arg_count(args.size() - 1, 1); const rString& arg1 = args[1].unsafe_cast<String>(); assert(arg1); args[0]->slot_set(libport::Symbol(arg1->value_get()), void_class); return void_class; } static rObject object_class_updateSlot (runner::Runner& r, objects_type& args) { check_arg_count(args.size() - 1, 2); const rString& arg1 = args[1].unsafe_cast<String>(); assert(arg1); return args[0]->slot_update(r, libport::Symbol(arg1->value_get()), args[2]); } static bool object_class_isA(rObject self, rObject proto) { return is_a(self, proto); } void object_class_initialize () { object_class->slot_set(SYMBOL(isA), make_primitive(object_class_isA, SYMBOL(isA))); /// \a Call gives the name of the C++ function, and \a Name that in Urbi. #define DECLARE(Name) \ DECLARE_PRIMITIVE(object, Name) DECLARE(addProto); DECLARE(allProtos); DECLARE(allSlotNames); DECLARE(apply); DECLARE(callMessage); DECLARE(clone); DECLARE(dump); DECLARE(getLazyLocalSlot); DECLARE(getSlot); DECLARE(init); DECLARE(locateSlot); DECLARE(EQ_EQ_EQ); DECLARE(protos); DECLARE(removeProto); DECLARE(removeSlot); DECLARE(EQ_EQ); DECLARE(setSlot); DECLARE(createSlot); DECLARE(slotNames); DECLARE(uid); DECLARE(updateSlot); #undef DECLARE #define DECLARE(Name, Code) \ object_class->slot_set(SYMBOL(Name), make_primitive(Code, SYMBOL(Name))) DECLARE(getProperty, &Object::property_get); DECLARE(hasProperty, &Object::property_has); DECLARE(hasSlot, &Object::slot_has); DECLARE(setProperty, &Object::property_set); DECLARE(removeProperty, &Object::property_remove); #undef DECLARE } }; // namespace object <|endoftext|>
<commit_before>// MathLib.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <unittest.h> #include <neuralnet.h> int _tmain(int /*argc*/, _TCHAR* /*argv[]*/) { //test change run_tests(); return 0; } <commit_msg>Small cleanup<commit_after>// MathLib.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <unittest.h> int _tmain(int /*argc*/, _TCHAR* /*argv[]*/) { //test change run_tests(); return 0; } <|endoftext|>
<commit_before>#include "Engine.h" #include "Game.h" #include "ObjectDummy.h" #include "BodyRigid.h" #include "BodyDummy.h" #include "Physics.h" #include "ShapeCapsule.h" #include "ActorBase.h" #include "Visualizer.h" #include "sys/SysControl.h" using namespace MathLib; #ifdef MEMORY_INFO #define new new(__FILE__, __LINE__) #endif // MEMORY_INFO /* */ #define ACTOR_BASE_IFPS (1.0f / 60.0f) #define ACTOR_BASE_CLAMP 89.9f #define ACTOR_BASE_COLLISIONS 4 /* */ CActorBase::CActorBase() { m_vUp = vec3(0.0f, 0.0f, 1.0f); m_pObject = new CObjectDummy(); m_pDummy = new CBodyDummy(); m_pShape = new CShapeCapsule(1.0f, 1.0f); m_nFlush = 0; m_vPosition = Vec3_zero; m_vVelocity = Vec3_zero; m_fPhiAngle = 0.0f; //倾斜角 二维平面坐标系中,直线向Y周延伸的方向与X轴正向之间的夹角 m_fThetaAngle = 0.0f; //方位角,正北方那条线与当前线条按照顺时针走过的角度 for (int i = 0; i < NUM_STATES; i++) { m_pStates[i] = 0; m_pTimes[i] = 0.0f; } m_pDummy->SetEnabled(1); m_pObject->SetBody(NULL); m_pObject->SetBody(m_pDummy); m_pShape->SetBody(NULL); m_pShape->SetBody(m_pDummy); m_pObject->SetWorldTransform(Get_Body_Transform()); m_pShape->SetRestitution(0.0f); m_pShape->SetCollisionMask(2); SetEnabled(1); SetViewDirection(vec3(0.0f, 1.0f, 0.0f)); SetCollision(1); SetCollisionRadius(0.3f); SetCollisionHeight(1.0f); SetFriction(2.0f); SetMinVelocity(2.0f); SetMaxVelocity(4.0f); SetAcceleration(8.0f); SetDamping(8.0f); SetJumping(1.5f); SetGround(0); SetCeiling(0); } CActorBase::~CActorBase() { m_pDummy->SetObject(NULL); delete m_pObject; delete m_pDummy; } void CActorBase::SetEnabled(int enable) { m_nEnable = enable; m_pDummy->SetEnabled(m_nEnable); } int CActorBase::IsEnabled() const { return m_nEnable; } void CActorBase::Update(float ifps) { if (!m_nEnable) { return; } // impulse vec3 impulse = vec3_zero; // ortho basis vec3 tangent, binormal; OrthoBasis(m_vUp, tangent, binormal); // current basis vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal; vec3 y = Normalize(Cross(m_vUp, x)); vec3 z = Normalize(Cross(x, y)); handle states Update_States(1, ifps); // old velocity float x_velocity = Dot(x, m_vVelocity); float y_velocity = Dot(y, m_vVelocity); float z_velocity = Dot(z, m_vVelocity); }<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "Engine.h" #include "Game.h" #include "ObjectDummy.h" #include "BodyRigid.h" #include "BodyDummy.h" #include "Physics.h" #include "ShapeCapsule.h" #include "ActorBase.h" #include "Visualizer.h" #include "sys/SysControl.h" using namespace MathLib; #ifdef MEMORY_INFO #define new new(__FILE__, __LINE__) #endif // MEMORY_INFO /* */ #define ACTOR_BASE_IFPS (1.0f / 60.0f) #define ACTOR_BASE_CLAMP 89.9f #define ACTOR_BASE_COLLISIONS 4 /* */ CActorBase::CActorBase() { m_vUp = vec3(0.0f, 0.0f, 1.0f); m_pObject = new CObjectDummy(); m_pDummy = new CBodyDummy(); m_pShape = new CShapeCapsule(1.0f, 1.0f); m_nFlush = 0; m_vPosition = Vec3_zero; m_vVelocity = Vec3_zero; m_fPhiAngle = 0.0f; //倾斜角 二维平面坐标系中,直线向Y周延伸的方向与X轴正向之间的夹角 m_fThetaAngle = 0.0f; //方位角,正北方那条线与当前线条按照顺时针走过的角度 for (int i = 0; i < NUM_STATES; i++) { m_pStates[i] = 0; m_pTimes[i] = 0.0f; } m_pDummy->SetEnabled(1); m_pObject->SetBody(NULL); m_pObject->SetBody(m_pDummy); m_pShape->SetBody(NULL); m_pShape->SetBody(m_pDummy); m_pObject->SetWorldTransform(Get_Body_Transform()); m_pShape->SetRestitution(0.0f); m_pShape->SetCollisionMask(2); SetEnabled(1); SetViewDirection(vec3(0.0f, 1.0f, 0.0f)); SetCollision(1); SetCollisionRadius(0.3f); SetCollisionHeight(1.0f); SetFriction(2.0f); SetMinVelocity(2.0f); SetMaxVelocity(4.0f); SetAcceleration(8.0f); SetDamping(8.0f); SetJumping(1.5f); SetGround(0); SetCeiling(0); } CActorBase::~CActorBase() { m_pDummy->SetObject(NULL); delete m_pObject; delete m_pDummy; } void CActorBase::SetEnabled(int enable) { m_nEnable = enable; m_pDummy->SetEnabled(m_nEnable); } int CActorBase::IsEnabled() const { return m_nEnable; } void CActorBase::Update(float ifps) { if (!m_nEnable) { return; } // impulse vec3 impulse = vec3_zero; // ortho basis vec3 tangent, binormal; OrthoBasis(m_vUp, tangent, binormal); // current basis vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal; vec3 y = Normalize(Cross(m_vUp, x)); vec3 z = Normalize(Cross(x, y)); handle states Update_States(1, ifps); // old velocity float x_velocity = Dot(x, m_vVelocity); float y_velocity = Dot(y, m_vVelocity); float z_velocity = Dot(z, m_vVelocity); // movement if (m_pStates[STATE_FORWARD]) impulse += x; if (m_pStates[STATE_BACKWARD]) impulse -= x; if (m_pStates[STATE_MOVE_LEFT]) impulse += y; if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y; impulse.normalize(); }<|endoftext|>
<commit_before>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ----------------------------------------------------------------------------- // File: robots_main.cc // ----------------------------------------------------------------------------- // // Simple binary to assess whether a URL is accessible to a user-agent according // to records found in a local robots.txt file, based on Google's robots.txt // parsing and matching algorithms. // Usage: // robots_main <local_path_to_robotstxt> <user_agent> <url> // Arguments: // local_path_to_robotstxt: local path to a file containing robots.txt records. // For example: /home/users/username/robots.txt // user_agent: a token to be matched against records in the robots.txt. // For example: Googlebot // url: a url to be matched against records in the robots.txt. The URL must be // %-encoded according to RFC3986. // For example: https://example.com/accessible/url.html // Returns: Prints a sentence with verdict about whether 'user_agent' is allowed // to access 'url' based on records in 'local_path_to_robotstxt'. // #include <fstream> #include <iostream> #include "robots.h" bool LoadFile(const std::string& filename, std::string* result) { std::ifstream file(filename, std::ios::in | std::ios::binary | std::ios::ate); if (file.is_open()) { size_t size = file.tellg(); std::vector<char> buffer(size); file.seekg (0, std::ios::beg); file.read(buffer.data(), size); file.close(); if (!file) return false; // file reading error (failbit or badbit). result->assign(buffer.begin(), buffer.end()); return true; } return false; } void ShowHelp(int argc, char** argv) { std::cerr << "Shows whether the given user_agent and URI combination" << " is allowed or disallowed by the given robots.txt file. " << std::endl << std::endl; std::cerr << "Usage: " << std::endl << " " << argv[0] << " <robots.txt filename> <user_agent> <URI>" << std::endl << std::endl; std::cerr << "The URI must be %-encoded according to RFC3986." << std::endl << std::endl; std::cerr << "Example: " << std::endl << " " << argv[0] << " robots.txt FooBot http://example.com/foo" << std::endl; } int main(int argc, char** argv) { std::string filename = argc >= 2 ? argv[1] : ""; if (filename == "-h" || filename == "-help" || filename == "--help") { ShowHelp(argc, argv); return 0; } if (argc != 4) { std::cerr << "Invalid amount of arguments. Showing help." << std::endl << std::endl; ShowHelp(argc, argv); return 1; } std::string robots_content; if (!(LoadFile(filename, &robots_content))) { std::cerr << "failed to read file \"" << filename << "\"" << std::endl; return 1; } std::string user_agent = argv[2]; std::vector<std::string> user_agents(1, user_agent); googlebot::RobotsMatcher matcher; std::string url = argv[3]; bool allowed = matcher.AllowedByRobots(robots_content, &user_agents, url); std::cout << "user-agent '" << user_agent << "' with URI '" << argv[3] << "': " << (allowed ? "ALLOWED" : "DISALLOWED") << std::endl; if (robots_content.empty()) { std::cout << "notice: robots file is empty so all user-agents are allowed" << std::endl; } } <commit_msg>Remove whitespace in method call<commit_after>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ----------------------------------------------------------------------------- // File: robots_main.cc // ----------------------------------------------------------------------------- // // Simple binary to assess whether a URL is accessible to a user-agent according // to records found in a local robots.txt file, based on Google's robots.txt // parsing and matching algorithms. // Usage: // robots_main <local_path_to_robotstxt> <user_agent> <url> // Arguments: // local_path_to_robotstxt: local path to a file containing robots.txt records. // For example: /home/users/username/robots.txt // user_agent: a token to be matched against records in the robots.txt. // For example: Googlebot // url: a url to be matched against records in the robots.txt. The URL must be // %-encoded according to RFC3986. // For example: https://example.com/accessible/url.html // Returns: Prints a sentence with verdict about whether 'user_agent' is allowed // to access 'url' based on records in 'local_path_to_robotstxt'. // #include <fstream> #include <iostream> #include "robots.h" bool LoadFile(const std::string& filename, std::string* result) { std::ifstream file(filename, std::ios::in | std::ios::binary | std::ios::ate); if (file.is_open()) { size_t size = file.tellg(); std::vector<char> buffer(size); file.seekg(0, std::ios::beg); file.read(buffer.data(), size); file.close(); if (!file) return false; // file reading error (failbit or badbit). result->assign(buffer.begin(), buffer.end()); return true; } return false; } void ShowHelp(int argc, char** argv) { std::cerr << "Shows whether the given user_agent and URI combination" << " is allowed or disallowed by the given robots.txt file. " << std::endl << std::endl; std::cerr << "Usage: " << std::endl << " " << argv[0] << " <robots.txt filename> <user_agent> <URI>" << std::endl << std::endl; std::cerr << "The URI must be %-encoded according to RFC3986." << std::endl << std::endl; std::cerr << "Example: " << std::endl << " " << argv[0] << " robots.txt FooBot http://example.com/foo" << std::endl; } int main(int argc, char** argv) { std::string filename = argc >= 2 ? argv[1] : ""; if (filename == "-h" || filename == "-help" || filename == "--help") { ShowHelp(argc, argv); return 0; } if (argc != 4) { std::cerr << "Invalid amount of arguments. Showing help." << std::endl << std::endl; ShowHelp(argc, argv); return 1; } std::string robots_content; if (!(LoadFile(filename, &robots_content))) { std::cerr << "failed to read file \"" << filename << "\"" << std::endl; return 1; } std::string user_agent = argv[2]; std::vector<std::string> user_agents(1, user_agent); googlebot::RobotsMatcher matcher; std::string url = argv[3]; bool allowed = matcher.AllowedByRobots(robots_content, &user_agents, url); std::cout << "user-agent '" << user_agent << "' with URI '" << argv[3] << "': " << (allowed ? "ALLOWED" : "DISALLOWED") << std::endl; if (robots_content.empty()) { std::cout << "notice: robots file is empty so all user-agents are allowed" << std::endl; } } <|endoftext|>
<commit_before>// // Created by michael on 16.02.16. // #include <Story/SimpleStoryTemplate.h> using namespace weave; using namespace std; StoryTemplateResult SimpleStoryTemplate::CreateStory(const EntityMap &requiredEntities, const WeaverGraph &, const WorldModel &worldModel, shared_ptr<RandomStream> randomStream) const { auto entities = getValidEntities(requiredEntities, worldModel, randomStream); if (entities.empty()) { Logger::Fatal("Invalid template call, not all required entities were found!"); } TokenToEntityMap tokenEntityMap; StoryTemplateResult result; for (uint64_t i = 1; i <= GetRequiredEntities().size(); i++) { auto entity = entities[0]; tokenEntityMap[to_string(i)] = {entity->GetId()}; if (conditions.count(StoryCondition::OncePerEntity)) { MetaData markedData; markedData.SetValue(key, 1); result.worldActions.emplace_back(WorldActionType::UPDATE, entity, markedData); } } result.tokenMap = createTokenMapping(tokenEntityMap); result.rawText = rawText; return result; } bool SimpleStoryTemplate::IsValid(const EntityMap &requiredEntities, const WeaverGraph &, const WorldModel &worldModel) const { return getValidEntities(requiredEntities, worldModel, make_shared<RandomStream>()).size() > 0; } vector<shared_ptr<WorldEntity>> SimpleStoryTemplate::getValidEntities(const EntityMap &entityMap, const WorldModel &worldModel, shared_ptr<RandomStream> randomStream) const { vector<shared_ptr<WorldEntity>> result; for (string type : GetRequiredEntities()) { vector<shared_ptr<WorldEntity>> validEntities; auto mapIter = entityMap.find(type); if (mapIter == entityMap.end()) { return validEntities; } for (shared_ptr<WorldEntity> entity : mapIter->second) { ID id = entity->GetId(); MetaData metaData = worldModel.GetMetaData(id); // check the "once per entity" condition if (conditions.count(StoryCondition::OncePerEntity) && metaData.HasValue(key)) { continue; } // check the "without property" condition auto iter = conditions.find(StoryCondition::WithoutProperty); if (iter != conditions.end() && !iter->second.empty() && metaData.HasValue(iter->second[0])) { continue; } // check the "with property" condition iter = conditions.find(StoryCondition::WithProperty); if (iter != conditions.end() && !iter->second.empty() && !metaData.HasValue(iter->second[0])) { continue; } // check the "greater than" condition iter = conditions.find(StoryCondition::GreaterThan); if (iter != conditions.end() && iter->second.size() == 2) { string property = iter->second[0]; int value = atoi(iter->second[1].c_str()); if (!metaData.HasValue(property) || metaData.GetValue(property) <= value) { continue; } } // check the "smaller than" condition iter = conditions.find(StoryCondition::SmallerThan); if (iter != conditions.end() && iter->second.size() == 2) { string property = iter->second[0]; int value = atoi(iter->second[1].c_str()); if (!metaData.HasValue(property) || metaData.GetValue(property) >= value) { continue; } } validEntities.push_back(entity); } if (validEntities.empty()) { return validEntities; } result.push_back(validEntities[randomStream->GetRandomIndex(validEntities.size())]); } return result; } <commit_msg>fixed a bug when a story requires multiple entities<commit_after>// // Created by michael on 16.02.16. // #include <Story/SimpleStoryTemplate.h> using namespace weave; using namespace std; StoryTemplateResult SimpleStoryTemplate::CreateStory(const EntityMap &requiredEntities, const WeaverGraph &, const WorldModel &worldModel, shared_ptr<RandomStream> randomStream) const { auto entities = getValidEntities(requiredEntities, worldModel, randomStream); if (entities.empty()) { Logger::Fatal("Invalid template call, not all required entities were found!"); } TokenToEntityMap tokenEntityMap; StoryTemplateResult result; for (uint64_t i = 1; i <= GetRequiredEntities().size(); i++) { auto entity = entities[i - 1]; tokenEntityMap[to_string(i)] = {entity->GetId()}; if (conditions.count(StoryCondition::OncePerEntity)) { MetaData markedData; markedData.SetValue(key, 1); result.worldActions.emplace_back(WorldActionType::UPDATE, entity, markedData); } } result.tokenMap = createTokenMapping(tokenEntityMap); result.rawText = rawText; return result; } bool SimpleStoryTemplate::IsValid(const EntityMap &requiredEntities, const WeaverGraph &, const WorldModel &worldModel) const { return getValidEntities(requiredEntities, worldModel, make_shared<RandomStream>()).size() > 0; } vector<shared_ptr<WorldEntity>> SimpleStoryTemplate::getValidEntities(const EntityMap &entityMap, const WorldModel &worldModel, shared_ptr<RandomStream> randomStream) const { vector<shared_ptr<WorldEntity>> result; for (string type : GetRequiredEntities()) { vector<shared_ptr<WorldEntity>> validEntities; auto mapIter = entityMap.find(type); if (mapIter == entityMap.end()) { return validEntities; } for (shared_ptr<WorldEntity> entity : mapIter->second) { ID id = entity->GetId(); MetaData metaData = worldModel.GetMetaData(id); // check the "once per entity" condition if (conditions.count(StoryCondition::OncePerEntity) && metaData.HasValue(key)) { continue; } // check the "without property" condition auto iter = conditions.find(StoryCondition::WithoutProperty); if (iter != conditions.end() && !iter->second.empty() && metaData.HasValue(iter->second[0])) { continue; } // check the "with property" condition iter = conditions.find(StoryCondition::WithProperty); if (iter != conditions.end() && !iter->second.empty() && !metaData.HasValue(iter->second[0])) { continue; } // check the "greater than" condition iter = conditions.find(StoryCondition::GreaterThan); if (iter != conditions.end() && iter->second.size() == 2) { string property = iter->second[0]; int value = atoi(iter->second[1].c_str()); if (!metaData.HasValue(property) || metaData.GetValue(property) <= value) { continue; } } // check the "smaller than" condition iter = conditions.find(StoryCondition::SmallerThan); if (iter != conditions.end() && iter->second.size() == 2) { string property = iter->second[0]; int value = atoi(iter->second[1].c_str()); if (!metaData.HasValue(property) || metaData.GetValue(property) >= value) { continue; } } validEntities.push_back(entity); } if (validEntities.empty()) { return validEntities; } result.push_back(validEntities[randomStream->GetRandomIndex(validEntities.size())]); } return result; } <|endoftext|>
<commit_before>#ifndef GUARD_session_hpp #define GUARD_session_hpp #include <sqlite3.h> #include <iostream> namespace phatbooks { class Session { public: /** * Starts a Phatbooks user session. * Initializes SQLite3 (but does not create database * connection). */ Session(); /** * Ends a Phatbooks user session. * Shuts down SQLite3. (It is assumed that there are no * open connections at this point.) */ ~Session(); private: }; inline Session::Session() { std::clog << "Creating session..." << std::endl; sqlite3_initialize(); std::clog << "SQLite3 has been initialized." << std::endl; } inline Session::~Session() { std::clog << "Destroying session..." << std::endl; sqlite3_shutdown(); std::clog << "SQLite3 has been shut down." << std::endl; } } // namespace phatbooks #endif // GUARD_session_hpp <commit_msg>Made Session noncopyable.<commit_after>#ifndef GUARD_session_hpp #define GUARD_session_hpp #include <sqlite3.h> #include <boost/utility.hpp> #include <iostream> namespace phatbooks { class Session { public: /** * Starts a Phatbooks user session. * Initializes SQLite3 (but does not create database * connection). */ Session(); /** * Ends a Phatbooks user session. * Shuts down SQLite3. (It is assumed that there are no * open connections at this point.) */ ~Session(); private: }; inline Session::Session() { std::clog << "Creating session..." << std::endl; sqlite3_initialize(); std::clog << "SQLite3 has been initialized." << std::endl; } inline Session::~Session() { std::clog << "Destroying session..." << std::endl; sqlite3_shutdown(); std::clog << "SQLite3 has been shut down." << std::endl; } } // namespace phatbooks #endif // GUARD_session_hpp <|endoftext|>
<commit_before>#include "raptor_api.h" #include "type/pb_converter.h" #include "boost/date_time/posix_time/posix_time.hpp" //#include "street_network/street_network_api.h" namespace navitia { namespace routing { namespace raptor { std::string iso_string(const nt::Data & d, int date, int hour){ boost::posix_time::ptime date_time(d.meta.production_date.begin() + boost::gregorian::days(date)); date_time += boost::posix_time::seconds(hour); return boost::posix_time::to_iso_string(date_time); } pbnavitia::Response make_pathes(const std::vector<navitia::routing::Path> &paths, const nt::Data & d, streetnetwork::StreetNetwork & worker) { pbnavitia::Response pb_response; pb_response.set_requested_api(pbnavitia::PLANNER); auto temp = worker.get_direct_path(); pbnavitia::Planner * planner = pb_response.mutable_planner(); if(paths.size() > 0 || temp.path_items.size() > 0) { planner->set_response_type(pbnavitia::ITINERARY_FOUND); if(temp.path_items.size() > 0) { pbnavitia::Journey * pb_journey = planner->add_journey(); pb_journey->set_duration(temp.length); fill_road_section(temp, d, pb_journey->add_section(), 1); } for(Path path : paths) { DateTime departure_time = DateTime::inf, arrival_time = DateTime::inf; pbnavitia::Journey * pb_journey = planner->add_journey(); pb_journey->set_nb_transfers(path.nb_changes); pb_journey->set_requested_date_time(boost::posix_time::to_iso_string(path.request_time)); // La marche à pied initiale si on avait donné une coordonnée if(path.items.size() > 0 && path.items.front().stop_points.size() > 0 && path.items.front().stop_points.size() > 0){ const auto temp = worker.get_path(path.items.front().stop_points.front()); if(temp.path_items.size() > 0) { fill_road_section(temp , d, pb_journey->add_section(), 1); departure_time = path.items.front().departure - temp.length/1.38; } } // La partie TC et correspondances for(PathItem & item : path.items){ pbnavitia::Section * pb_section = pb_journey->add_section(); if(item.type == public_transport){ pb_section->set_type(pbnavitia::PUBLIC_TRANSPORT); if( item.vj_idx != type::invalid_idx){ // TODO : réfléchir si ça peut vraiment arriver const type::VehicleJourney & vj = d.pt_data.vehicle_journeys[item.vj_idx]; const type::Route & route = d.pt_data.routes[vj.route_idx]; const type::Line & line = d.pt_data.lines[route.line_idx]; if(line.network_idx != type::invalid_idx) pb_section->set_network(d.pt_data.networks[line.network_idx].name ); else pb_section->set_network(""); if(vj.mode_idx != type::invalid_idx) pb_section->set_mode(d.pt_data.modes[vj.mode_idx].name); pb_section->set_code(line.code); pb_section->set_headsign(vj.name); pb_section->set_direction(route.name); fill_pb_object(line.idx, d, pb_section->mutable_line()); } for(size_t i=0;i<item.stop_points.size();++i){ pbnavitia::StopTime * stop_time = pb_section->add_stop_time(); auto arr_time = item.arrivals[i]; stop_time->set_arrival_date_time(iso_string(d, arr_time.date(), arr_time.hour())); auto dep_time = item.departures[i]; stop_time->set_departure_date_time(iso_string(d, dep_time.date(), dep_time.hour())); fill_pb_object(item.stop_points[i], d, stop_time->mutable_stop_point(), 1); } if(item.stop_points.size() >= 2) { fill_pb_placemark(d.pt_data.stop_points[item.stop_points.front()], d, pb_section->mutable_origin()); fill_pb_placemark(d.pt_data.stop_points[item.stop_points.back()], d, pb_section->mutable_destination()); } } else { pb_section->set_type(pbnavitia::TRANSFER); pb_section->set_duration(item.departure - item.arrival); fill_pb_placemark(d.pt_data.stop_points[item.stop_points.front()], d, pb_section->mutable_origin()); fill_pb_placemark(d.pt_data.stop_points[item.stop_points.back()], d, pb_section->mutable_destination()); } pb_section->set_duration(item.arrival - item.departure); if(departure_time == DateTime::inf) departure_time = item.departure; arrival_time = item.arrival; pb_journey->set_duration(arrival_time - departure_time); } // La marche à pied finale si on avait donné une coordonnée if(path.items.size() > 0 && path.items.back().stop_points.size() > 0 && path.items.back().stop_points.size()>0){ auto temp = worker.get_path(path.items.back().stop_points.back(), true); if(temp.path_items.size() > 0) { fill_road_section(temp, d, pb_journey->add_section(), 1); arrival_time = arrival_time + temp.length/1.38; } } pb_journey->set_departure_date_time(iso_string(d, departure_time.date(), departure_time.hour())); pb_journey->set_arrival_date_time(iso_string(d, arrival_time.date(), arrival_time.hour())); } } else { planner->set_response_type(pbnavitia::NO_SOLUTION); } return pb_response; } std::vector<std::pair<type::idx_t, double> > get_stop_points(const type::EntryPoint &ep, const type::Data & data, streetnetwork::StreetNetwork & worker, bool use_second = false){ std::vector<std::pair<type::idx_t, double> > result; switch(ep.type) { case navitia::type::Type_e::eStopArea: { auto it = data.pt_data.stop_area_map.find(ep.external_code); if(it!= data.pt_data.stop_area_map.end()) { for(auto spidx : data.pt_data.stop_areas[it->second].stop_point_list) { result.push_back(std::make_pair(spidx, 0)); } } } break; case type::Type_e::eStopPoint: { auto it = data.pt_data.stop_point_map.find(ep.external_code); if(it != data.pt_data.stop_point_map.end()){ result.push_back(std::make_pair(data.pt_data.stop_points[it->second].idx, 0)); } } break; // AA gestion des adresses case type::Type_e::eAddress: case type::Type_e::eCoord: { result = worker.find_nearest_stop_points(ep.coordinates, data.pt_data.stop_point_proximity_list, 1000, use_second); } break; default: break; } return result; } pbnavitia::Response make_response(RAPTOR &raptor, const type::EntryPoint &origin, const type::EntryPoint &destination, const std::vector<std::string> &datetimes_str, bool clockwise, std::multimap<std::string, std::string> forbidden, streetnetwork::StreetNetwork & worker) { pbnavitia::Response response; response.set_requested_api(pbnavitia::PLANNER); std::vector<boost::posix_time::ptime> datetimes; for(std::string datetime: datetimes_str){ try { boost::posix_time::ptime ptime; ptime = boost::posix_time::from_iso_string(datetime); if(!raptor.data.meta.production_date.contains(ptime.date())) { response.mutable_planner()->set_response_type(pbnavitia::DATE_OUT_OF_BOUNDS); response.set_info("Example of invalid date: " + datetime); return response; } datetimes.push_back(ptime); } catch(...){ response.set_error("Impossible to parse date " + datetime); return response; } } if(clockwise) std::sort(datetimes.begin(), datetimes.end(), [](boost::posix_time::ptime dt1, boost::posix_time::ptime dt2){return dt1 > dt2;}); else std::sort(datetimes.begin(), datetimes.end()); worker.init(); auto departures = get_stop_points(origin, raptor.data, worker); auto destinations = get_stop_points(destination, raptor.data, worker, true); if(departures.size() == 0 && destinations.size() == 0){ response.mutable_planner()->set_response_type(pbnavitia::NO_ORIGIN_NOR_DESTINATION_POINT); return response; } if(departures.size() == 0){ response.mutable_planner()->set_response_type(pbnavitia::NO_ORIGIN_POINT); return response; } if(destinations.size() == 0){ response.mutable_planner()->set_response_type(pbnavitia::NO_DESTINATION_POINT); return response; } std::vector<Path> result; DateTime borne; if(!clockwise) borne = DateTime::min; else { // std::vector<DateTime> dts; // for(boost::posix_time::ptime datetime : datetimes){ // int day = (datetime.date() - raptor.data.meta.production_date.begin()).days(); // int time = datetime.time_of_day().total_seconds(); // dts.push_back(DateTime(day, time)); // } // return make_pathes(raptor.compute_all(departures, destinations, dts, borne), raptor.data, worker); borne = DateTime::inf; } for(boost::posix_time::ptime datetime : datetimes){ std::vector<Path> tmp; int day = (datetime.date() - raptor.data.meta.production_date.begin()).days(); int time = datetime.time_of_day().total_seconds(); if(clockwise) tmp = raptor.compute_all(departures, destinations, DateTime(day, time), borne, forbidden); else tmp = raptor.compute_reverse_all(departures, destinations, DateTime(day, time), borne, forbidden); // Lorsqu'on demande qu'un seul horaire, on garde tous les résultas if(datetimes.size() == 1){ result = tmp; for(auto & path : result){ path.request_time = datetime; } } else if(tmp.size() > 0) { // Lorsqu'on demande plusieurs horaires, on garde que l'arrivée au plus tôt / départ au plus tard tmp.back().request_time = datetime; result.push_back(tmp.back()); borne = tmp.back().items.back().arrival; } else // Lorsqu'on demande plusieurs horaires, et qu'il n'y a pas de résultat, on retourne un itinéraire vide result.push_back(Path()); } if(clockwise) std::reverse(result.begin(), result.end()); return make_pathes(result, raptor.data, worker); } }}} <commit_msg>raptor api : Le stop_area est affiché dans origin/destination, plus dans chaque stoptime<commit_after>#include "raptor_api.h" #include "type/pb_converter.h" #include "boost/date_time/posix_time/posix_time.hpp" //#include "street_network/street_network_api.h" namespace navitia { namespace routing { namespace raptor { std::string iso_string(const nt::Data & d, int date, int hour){ boost::posix_time::ptime date_time(d.meta.production_date.begin() + boost::gregorian::days(date)); date_time += boost::posix_time::seconds(hour); return boost::posix_time::to_iso_string(date_time); } pbnavitia::Response make_pathes(const std::vector<navitia::routing::Path> &paths, const nt::Data & d, streetnetwork::StreetNetwork & worker) { pbnavitia::Response pb_response; pb_response.set_requested_api(pbnavitia::PLANNER); auto temp = worker.get_direct_path(); pbnavitia::Planner * planner = pb_response.mutable_planner(); if(paths.size() > 0 || temp.path_items.size() > 0) { planner->set_response_type(pbnavitia::ITINERARY_FOUND); if(temp.path_items.size() > 0) { pbnavitia::Journey * pb_journey = planner->add_journey(); pb_journey->set_duration(temp.length); fill_road_section(temp, d, pb_journey->add_section(), 1); } for(Path path : paths) { DateTime departure_time = DateTime::inf, arrival_time = DateTime::inf; pbnavitia::Journey * pb_journey = planner->add_journey(); pb_journey->set_nb_transfers(path.nb_changes); pb_journey->set_requested_date_time(boost::posix_time::to_iso_string(path.request_time)); // La marche à pied initiale si on avait donné une coordonnée if(path.items.size() > 0 && path.items.front().stop_points.size() > 0 && path.items.front().stop_points.size() > 0){ const auto temp = worker.get_path(path.items.front().stop_points.front()); if(temp.path_items.size() > 0) { fill_road_section(temp , d, pb_journey->add_section(), 1); departure_time = path.items.front().departure - temp.length/1.38; } } // La partie TC et correspondances for(PathItem & item : path.items){ pbnavitia::Section * pb_section = pb_journey->add_section(); if(item.type == public_transport){ pb_section->set_type(pbnavitia::PUBLIC_TRANSPORT); if( item.vj_idx != type::invalid_idx){ // TODO : réfléchir si ça peut vraiment arriver const type::VehicleJourney & vj = d.pt_data.vehicle_journeys[item.vj_idx]; const type::Route & route = d.pt_data.routes[vj.route_idx]; const type::Line & line = d.pt_data.lines[route.line_idx]; if(line.network_idx != type::invalid_idx) pb_section->set_network(d.pt_data.networks[line.network_idx].name ); else pb_section->set_network(""); if(vj.mode_idx != type::invalid_idx) pb_section->set_mode(d.pt_data.modes[vj.mode_idx].name); pb_section->set_code(line.code); pb_section->set_headsign(vj.name); pb_section->set_direction(route.name); fill_pb_object(line.idx, d, pb_section->mutable_line()); } for(size_t i=0;i<item.stop_points.size();++i){ pbnavitia::StopTime * stop_time = pb_section->add_stop_time(); auto arr_time = item.arrivals[i]; stop_time->set_arrival_date_time(iso_string(d, arr_time.date(), arr_time.hour())); auto dep_time = item.departures[i]; stop_time->set_departure_date_time(iso_string(d, dep_time.date(), dep_time.hour())); fill_pb_object(item.stop_points[i], d, stop_time->mutable_stop_point(), 0); } if(item.stop_points.size() >= 2) { fill_pb_placemark(d.pt_data.stop_points[item.stop_points.front()], d, pb_section->mutable_origin(), 1); fill_pb_placemark(d.pt_data.stop_points[item.stop_points.back()], d, pb_section->mutable_destination(), 1); } } else { pb_section->set_type(pbnavitia::TRANSFER); pb_section->set_duration(item.departure - item.arrival); fill_pb_placemark(d.pt_data.stop_points[item.stop_points.front()], d, pb_section->mutable_origin(), 1); fill_pb_placemark(d.pt_data.stop_points[item.stop_points.back()], d, pb_section->mutable_destination(), 1); } pb_section->set_duration(item.arrival - item.departure); if(departure_time == DateTime::inf) departure_time = item.departure; arrival_time = item.arrival; pb_journey->set_duration(arrival_time - departure_time); } // La marche à pied finale si on avait donné une coordonnée if(path.items.size() > 0 && path.items.back().stop_points.size() > 0 && path.items.back().stop_points.size()>0){ auto temp = worker.get_path(path.items.back().stop_points.back(), true); if(temp.path_items.size() > 0) { fill_road_section(temp, d, pb_journey->add_section(), 1); arrival_time = arrival_time + temp.length/1.38; } } pb_journey->set_departure_date_time(iso_string(d, departure_time.date(), departure_time.hour())); pb_journey->set_arrival_date_time(iso_string(d, arrival_time.date(), arrival_time.hour())); } } else { planner->set_response_type(pbnavitia::NO_SOLUTION); } return pb_response; } std::vector<std::pair<type::idx_t, double> > get_stop_points(const type::EntryPoint &ep, const type::Data & data, streetnetwork::StreetNetwork & worker, bool use_second = false){ std::vector<std::pair<type::idx_t, double> > result; switch(ep.type) { case navitia::type::Type_e::eStopArea: { auto it = data.pt_data.stop_area_map.find(ep.external_code); if(it!= data.pt_data.stop_area_map.end()) { for(auto spidx : data.pt_data.stop_areas[it->second].stop_point_list) { result.push_back(std::make_pair(spidx, 0)); } } } break; case type::Type_e::eStopPoint: { auto it = data.pt_data.stop_point_map.find(ep.external_code); if(it != data.pt_data.stop_point_map.end()){ result.push_back(std::make_pair(data.pt_data.stop_points[it->second].idx, 0)); } } break; // AA gestion des adresses case type::Type_e::eAddress: case type::Type_e::eCoord: { result = worker.find_nearest_stop_points(ep.coordinates, data.pt_data.stop_point_proximity_list, 1000, use_second); } break; default: break; } return result; } pbnavitia::Response make_response(RAPTOR &raptor, const type::EntryPoint &origin, const type::EntryPoint &destination, const std::vector<std::string> &datetimes_str, bool clockwise, std::multimap<std::string, std::string> forbidden, streetnetwork::StreetNetwork & worker) { pbnavitia::Response response; response.set_requested_api(pbnavitia::PLANNER); std::vector<boost::posix_time::ptime> datetimes; for(std::string datetime: datetimes_str){ try { boost::posix_time::ptime ptime; ptime = boost::posix_time::from_iso_string(datetime); if(!raptor.data.meta.production_date.contains(ptime.date())) { response.mutable_planner()->set_response_type(pbnavitia::DATE_OUT_OF_BOUNDS); response.set_info("Example of invalid date: " + datetime); return response; } datetimes.push_back(ptime); } catch(...){ response.set_error("Impossible to parse date " + datetime); return response; } } if(clockwise) std::sort(datetimes.begin(), datetimes.end(), [](boost::posix_time::ptime dt1, boost::posix_time::ptime dt2){return dt1 > dt2;}); else std::sort(datetimes.begin(), datetimes.end()); worker.init(); auto departures = get_stop_points(origin, raptor.data, worker); auto destinations = get_stop_points(destination, raptor.data, worker, true); if(departures.size() == 0 && destinations.size() == 0){ response.mutable_planner()->set_response_type(pbnavitia::NO_ORIGIN_NOR_DESTINATION_POINT); return response; } if(departures.size() == 0){ response.mutable_planner()->set_response_type(pbnavitia::NO_ORIGIN_POINT); return response; } if(destinations.size() == 0){ response.mutable_planner()->set_response_type(pbnavitia::NO_DESTINATION_POINT); return response; } std::vector<Path> result; DateTime borne; if(!clockwise) borne = DateTime::min; else { // std::vector<DateTime> dts; // for(boost::posix_time::ptime datetime : datetimes){ // int day = (datetime.date() - raptor.data.meta.production_date.begin()).days(); // int time = datetime.time_of_day().total_seconds(); // dts.push_back(DateTime(day, time)); // } // return make_pathes(raptor.compute_all(departures, destinations, dts, borne), raptor.data, worker); borne = DateTime::inf; } for(boost::posix_time::ptime datetime : datetimes){ std::vector<Path> tmp; int day = (datetime.date() - raptor.data.meta.production_date.begin()).days(); int time = datetime.time_of_day().total_seconds(); if(clockwise) tmp = raptor.compute_all(departures, destinations, DateTime(day, time), borne, forbidden); else tmp = raptor.compute_reverse_all(departures, destinations, DateTime(day, time), borne, forbidden); // Lorsqu'on demande qu'un seul horaire, on garde tous les résultas if(datetimes.size() == 1){ result = tmp; for(auto & path : result){ path.request_time = datetime; } } else if(tmp.size() > 0) { // Lorsqu'on demande plusieurs horaires, on garde que l'arrivée au plus tôt / départ au plus tard tmp.back().request_time = datetime; result.push_back(tmp.back()); borne = tmp.back().items.back().arrival; } else // Lorsqu'on demande plusieurs horaires, et qu'il n'y a pas de résultat, on retourne un itinéraire vide result.push_back(Path()); } if(clockwise) std::reverse(result.begin(), result.end()); return make_pathes(result, raptor.data, worker); } }}} <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // SourceManager.cpp // Source file management. // // File is under the MIT license; see LICENSE for details. //------------------------------------------------------------------------------ #include "SourceManager.h" #include <algorithm> #include <fstream> #include "util/HashMap.h" namespace slang { SourceManager::SourceManager() { // add a dummy entry to the start of the directory list so that our file IDs line up FileInfo file; bufferEntries.emplace_back(file); } std::string SourceManager::makeAbsolutePath(StringRef path) const { if (!path) return ""; return Path::makeAbsolute(path).str(); } void SourceManager::addSystemDirectory(StringRef path) { systemDirectories.push_back(Path::makeAbsolute(path)); } void SourceManager::addUserDirectory(StringRef path) { userDirectories.push_back(Path::makeAbsolute(path)); } uint32_t SourceManager::getLineNumber(SourceLocation location) const { SourceLocation fileLocation = getFullyExpandedLoc(location); uint32_t rawLineNumber = getRawLineNumber(fileLocation); if (rawLineNumber == 0) return 0; FileData* fd = getFileData(fileLocation.buffer()); auto lineDirective = fd->getPreviousLineDirective(rawLineNumber); if (!lineDirective) return rawLineNumber; else return lineDirective->lineOfDirective + (rawLineNumber - lineDirective->lineInFile) - 1; } uint32_t SourceManager::getColumnNumber(SourceLocation location) const { FileData* fd = getFileData(location.buffer()); if (!fd) return 0; // walk backward to find start of line uint32_t lineStart = location.offset(); ASSERT(lineStart < fd->mem.count()); while (lineStart > 0 && fd->mem[lineStart - 1] != '\n' && fd->mem[lineStart - 1] != '\r') lineStart--; return location.offset() - lineStart + 1; } StringRef SourceManager::getFileName(SourceLocation location) const { SourceLocation fileLocation = getFullyExpandedLoc(location); // Avoid computing line offsets if we just need a name of `line-less file FileData* fd = getFileData(fileLocation.buffer()); if (!fd) return nullptr; else if (fd->lineDirectives.empty()) return StringRef(fd->name); auto lineDirective = fd->getPreviousLineDirective(getRawLineNumber(fileLocation)); if (!lineDirective) return StringRef(fd->name); else return StringRef(lineDirective->name); } SourceLocation SourceManager::getIncludedFrom(BufferID buffer) const { if (!buffer) return SourceLocation(); ASSERT(buffer.id < bufferEntries.size()); return std::get<FileInfo>(bufferEntries[buffer.id]).includedFrom; } bool SourceManager::isFileLoc(SourceLocation location) const { auto buffer = location.buffer(); if (!buffer) return false; ASSERT(buffer.id < bufferEntries.size()); return std::get_if<FileInfo>(&bufferEntries[buffer.id]) != nullptr; } bool SourceManager::isMacroLoc(SourceLocation location) const { auto buffer = location.buffer(); if (!buffer) return false; ASSERT(buffer.id < bufferEntries.size()); return std::get_if<ExpansionInfo>(&bufferEntries[buffer.id]) != nullptr; } bool SourceManager::isIncludedFileLoc(SourceLocation location) const { return getIncludedFrom(location.buffer()).valid(); } bool SourceManager::isBeforeInCompilationUnit(SourceLocation left, SourceLocation right) const { // Simple check: if they're in the same buffer, just do an easy compare if (left.buffer() == right.buffer()) return left.offset() < right.offset(); // TODO: add a cache for this? auto moveUp = [this](SourceLocation& sl) { if (!isFileLoc(sl)) sl = getExpansionLoc(sl); else { SourceLocation included = getIncludedFrom(sl.buffer()); if (!included) return true; sl = included; } return false; }; // Otherwise we have to build the full include / expansion chain and compare. SmallHashMap<BufferID, uint32_t, 16> leftChain; do { leftChain.emplace(left.buffer(), left.offset()); } while (left.buffer() != right.buffer() && !moveUp(left)); SmallHashMap<BufferID, uint32_t, 16>::iterator it; while ((it = leftChain.find(right.buffer())) == leftChain.end()) { if (moveUp(right)) break; } if (it != leftChain.end()) left = SourceLocation(it->first, it->second); // At this point, we either have a nearest common ancestor, or the two // locations are simply in totally different compilation units. ASSERT(left.buffer() == right.buffer()); return left.offset() < right.offset(); } SourceLocation SourceManager::getExpansionLoc(SourceLocation location) const { auto buffer = location.buffer(); if (!buffer) return SourceLocation(); ASSERT(buffer.id < bufferEntries.size()); return std::get<ExpansionInfo>(bufferEntries[buffer.id]).expansionStart; } SourceRange SourceManager::getExpansionRange(SourceLocation location) const { auto buffer = location.buffer(); if (!buffer) return SourceRange(); ASSERT(buffer.id < bufferEntries.size()); const ExpansionInfo& info = std::get<ExpansionInfo>(bufferEntries[buffer.id]); return SourceRange(info.expansionStart, info.expansionEnd); } SourceLocation SourceManager::getOriginalLoc(SourceLocation location) const { auto buffer = location.buffer(); if (!buffer) return SourceLocation(); ASSERT(buffer.id < bufferEntries.size()); return std::get<ExpansionInfo>(bufferEntries[buffer.id]).originalLoc + location.offset(); } SourceLocation SourceManager::getFullyExpandedLoc(SourceLocation location) const { while (isMacroLoc(location)) location = getExpansionLoc(location); return location; } StringRef SourceManager::getSourceText(BufferID buffer) const { FileData* fd = getFileData(buffer); if (!fd) return nullptr; return StringRef(fd->mem); } SourceLocation SourceManager::createExpansionLoc(SourceLocation originalLoc, SourceLocation expansionStart, SourceLocation expansionEnd) { bufferEntries.emplace_back(ExpansionInfo(originalLoc, expansionStart, expansionEnd)); return SourceLocation(BufferID::get((uint32_t)(bufferEntries.size() - 1)), 0); } SourceBuffer SourceManager::assignText(StringRef text, SourceLocation includedFrom) { // Generate a placeholder name for this "file" return assignText(StringRef("<unnamed_buffer" + std::to_string(unnamedBufferCount++) + ">"), text, includedFrom); } SourceBuffer SourceManager::assignText(StringRef path, StringRef text, SourceLocation includedFrom) { SmallVectorSized<char, 2> buffer; buffer.appendRange(text); if (buffer.empty() || buffer.back() != '\0') buffer.append('\0'); return assignBuffer(path, std::move(buffer), includedFrom); } SourceBuffer SourceManager::appendText(BufferID buffer, StringRef text) { ASSERT(buffer); FileInfo& fi = std::get<FileInfo>(bufferEntries[buffer.id]); SourceLocation includeLoc = SourceLocation(buffer, fi.data->mem.count()); return assignText(text, includeLoc); } SourceBuffer SourceManager::assignBuffer(StringRef path, Vector<char>&& buffer, SourceLocation includedFrom) { Path fullPath = path; std::string canonicalStr = fullPath.str(); auto it = lookupCache.find(canonicalStr); ASSERT(it == lookupCache.end()); return cacheBuffer(std::move(canonicalStr), fullPath, includedFrom, std::move(buffer)); } SourceBuffer SourceManager::readSource(StringRef path) { ASSERT(path); return openCached(path, SourceLocation()); } SourceBuffer SourceManager::readHeader(StringRef path, SourceLocation includedFrom, bool isSystemPath) { // if the header is specified as an absolute path, just do a straight lookup ASSERT(path); Path p = path; if (p.isAbsolute()) return openCached(p, includedFrom); // system path lookups only look in system directories if (isSystemPath) { for (auto& d : systemDirectories) { SourceBuffer result = openCached(d + p, includedFrom); if (result.id) return result; } return SourceBuffer(); } // search relative to the current file FileData* fd = getFileData(includedFrom.buffer()); if (fd && fd->directory) { SourceBuffer result = openCached((*fd->directory) + p, includedFrom); if (result.id) return result; } // search additional include directories for (auto& d : userDirectories) { SourceBuffer result = openCached(d + p, includedFrom); if (result.id) return result; } return SourceBuffer(); } void SourceManager::addLineDirective(SourceLocation location, uint32_t lineNum, StringRef name, uint8_t level) { SourceLocation fileLocation = getFullyExpandedLoc(location); FileData* fd = getFileData(fileLocation.buffer()); if (!fd) return; uint32_t sourceLineNum = getRawLineNumber(fileLocation); fd->lineDirectives.emplace_back(sourceLineNum, lineNum, name, level); } SourceManager::FileData* SourceManager::getFileData(BufferID buffer) const { if (!buffer) return nullptr; ASSERT(buffer.id < bufferEntries.size()); return std::get<FileInfo>(bufferEntries[buffer.id]).data; } SourceBuffer SourceManager::createBufferEntry(FileData* fd, SourceLocation includedFrom) { ASSERT(fd); bufferEntries.emplace_back(FileInfo(fd, includedFrom)); return SourceBuffer { StringRef(fd->mem), BufferID::get((uint32_t)(bufferEntries.size() - 1)) }; } SourceBuffer SourceManager::openCached(const Path& fullPath, SourceLocation includedFrom) { Path absPath; try { absPath = Path::makeAbsolute(fullPath); } catch (std::runtime_error&) { return SourceBuffer(); } // first see if we have this file cached std::string canonicalStr = absPath.str(); auto it = lookupCache.find(canonicalStr); if (it != lookupCache.end()) { FileData* fd = it->second.get(); if (!fd) return SourceBuffer(); return createBufferEntry(fd, includedFrom); } // do the read Vector<char> buffer; if (!readFile(absPath, buffer)) { lookupCache.emplace(std::move(canonicalStr), nullptr); return SourceBuffer(); } return cacheBuffer(std::move(canonicalStr), absPath, includedFrom, std::move(buffer)); } SourceBuffer SourceManager::cacheBuffer(std::string&& canonicalPath, const Path& path, SourceLocation includedFrom, Vector<char>&& buffer) { std::string name = path.filename(); auto fd = std::make_unique<FileData>( &*directories.insert(path.parentPath()).first, name, std::move(buffer) ); FileData* fdPtr = lookupCache.emplace(std::move(canonicalPath), std::move(fd)).first->second.get(); return createBufferEntry(fdPtr, includedFrom); } bool SourceManager::readFile(const Path& path, Vector<char>& buffer) { size_t size; try { size = path.fileSize(); } catch (std::runtime_error&) { return false; } // + 1 for null terminator buffer.extend((uint32_t)size + 1); std::ifstream stream(path.str(), std::ios::binary); stream.read(buffer.begin(), size); // null-terminate the buffer while we're at it buffer.begin()[(uint32_t)size] = '\0'; return stream.good(); } void SourceManager::computeLineOffsets(const Vector<char>& buffer, std::vector<uint32_t>& offsets) { // first line always starts at offset 0 offsets.push_back(0); const char* ptr = buffer.begin(); const char* end = buffer.end(); while (ptr != end) { if (ptr[0] == '\n' || ptr[0] == '\r') { // if we see \r\n or \n\r skip both chars if ((ptr[1] == '\n' || ptr[1] == '\r') && ptr[0] != ptr[1]) ptr++; ptr++; offsets.push_back((uint32_t)(ptr - buffer.begin())); } else { ptr++; } } } const SourceManager::FileData::LineDirectiveInfo* SourceManager::FileData::getPreviousLineDirective(uint32_t rawLineNumber) const { auto it = std::lower_bound(lineDirectives.begin(), lineDirectives.end(), LineDirectiveInfo(rawLineNumber, 0, "", 0), LineDirectiveComparator()); if (it != lineDirectives.begin()) { // lower_bound will give us an iterator to the first directive after the command // let's instead get a pointer to the one right before it if (it == lineDirectives.end()) { // Check to see whether the actual last directive is before the // given line number if (lineDirectives.back().lineInFile >= rawLineNumber) return nullptr; } return &*(it - 1); } else { return nullptr; } } uint32_t SourceManager::getRawLineNumber(SourceLocation location) const { FileData* fd = getFileData(location.buffer()); if (!fd) return 0; // compute line offsets if we haven't already if (fd->lineOffsets.empty()) computeLineOffsets(fd->mem, fd->lineOffsets); // Find the first line offset that is greater than the given location offset. That iterator // then tells us how many lines away from the beginning we are. auto it = std::lower_bound(fd->lineOffsets.begin(), fd->lineOffsets.end(), location.offset()); // We want to ensure the line we return is strictly greater than the given location offset. // So if it is equal, add one to the lower bound we got return (uint32_t)(it - fd->lineOffsets.begin()) + (*it == location.offset()); } } <commit_msg>Fix bug in line number calculation<commit_after>//------------------------------------------------------------------------------ // SourceManager.cpp // Source file management. // // File is under the MIT license; see LICENSE for details. //------------------------------------------------------------------------------ #include "SourceManager.h" #include <algorithm> #include <fstream> #include "util/HashMap.h" namespace slang { SourceManager::SourceManager() { // add a dummy entry to the start of the directory list so that our file IDs line up FileInfo file; bufferEntries.emplace_back(file); } std::string SourceManager::makeAbsolutePath(StringRef path) const { if (!path) return ""; return Path::makeAbsolute(path).str(); } void SourceManager::addSystemDirectory(StringRef path) { systemDirectories.push_back(Path::makeAbsolute(path)); } void SourceManager::addUserDirectory(StringRef path) { userDirectories.push_back(Path::makeAbsolute(path)); } uint32_t SourceManager::getLineNumber(SourceLocation location) const { SourceLocation fileLocation = getFullyExpandedLoc(location); uint32_t rawLineNumber = getRawLineNumber(fileLocation); if (rawLineNumber == 0) return 0; FileData* fd = getFileData(fileLocation.buffer()); auto lineDirective = fd->getPreviousLineDirective(rawLineNumber); if (!lineDirective) return rawLineNumber; else return lineDirective->lineOfDirective + (rawLineNumber - lineDirective->lineInFile) - 1; } uint32_t SourceManager::getColumnNumber(SourceLocation location) const { FileData* fd = getFileData(location.buffer()); if (!fd) return 0; // walk backward to find start of line uint32_t lineStart = location.offset(); ASSERT(lineStart < fd->mem.count()); while (lineStart > 0 && fd->mem[lineStart - 1] != '\n' && fd->mem[lineStart - 1] != '\r') lineStart--; return location.offset() - lineStart + 1; } StringRef SourceManager::getFileName(SourceLocation location) const { SourceLocation fileLocation = getFullyExpandedLoc(location); // Avoid computing line offsets if we just need a name of `line-less file FileData* fd = getFileData(fileLocation.buffer()); if (!fd) return nullptr; else if (fd->lineDirectives.empty()) return StringRef(fd->name); auto lineDirective = fd->getPreviousLineDirective(getRawLineNumber(fileLocation)); if (!lineDirective) return StringRef(fd->name); else return StringRef(lineDirective->name); } SourceLocation SourceManager::getIncludedFrom(BufferID buffer) const { if (!buffer) return SourceLocation(); ASSERT(buffer.id < bufferEntries.size()); return std::get<FileInfo>(bufferEntries[buffer.id]).includedFrom; } bool SourceManager::isFileLoc(SourceLocation location) const { auto buffer = location.buffer(); if (!buffer) return false; ASSERT(buffer.id < bufferEntries.size()); return std::get_if<FileInfo>(&bufferEntries[buffer.id]) != nullptr; } bool SourceManager::isMacroLoc(SourceLocation location) const { auto buffer = location.buffer(); if (!buffer) return false; ASSERT(buffer.id < bufferEntries.size()); return std::get_if<ExpansionInfo>(&bufferEntries[buffer.id]) != nullptr; } bool SourceManager::isIncludedFileLoc(SourceLocation location) const { return getIncludedFrom(location.buffer()).valid(); } bool SourceManager::isBeforeInCompilationUnit(SourceLocation left, SourceLocation right) const { // Simple check: if they're in the same buffer, just do an easy compare if (left.buffer() == right.buffer()) return left.offset() < right.offset(); // TODO: add a cache for this? auto moveUp = [this](SourceLocation& sl) { if (!isFileLoc(sl)) sl = getExpansionLoc(sl); else { SourceLocation included = getIncludedFrom(sl.buffer()); if (!included) return true; sl = included; } return false; }; // Otherwise we have to build the full include / expansion chain and compare. SmallHashMap<BufferID, uint32_t, 16> leftChain; do { leftChain.emplace(left.buffer(), left.offset()); } while (left.buffer() != right.buffer() && !moveUp(left)); SmallHashMap<BufferID, uint32_t, 16>::iterator it; while ((it = leftChain.find(right.buffer())) == leftChain.end()) { if (moveUp(right)) break; } if (it != leftChain.end()) left = SourceLocation(it->first, it->second); // At this point, we either have a nearest common ancestor, or the two // locations are simply in totally different compilation units. ASSERT(left.buffer() == right.buffer()); return left.offset() < right.offset(); } SourceLocation SourceManager::getExpansionLoc(SourceLocation location) const { auto buffer = location.buffer(); if (!buffer) return SourceLocation(); ASSERT(buffer.id < bufferEntries.size()); return std::get<ExpansionInfo>(bufferEntries[buffer.id]).expansionStart; } SourceRange SourceManager::getExpansionRange(SourceLocation location) const { auto buffer = location.buffer(); if (!buffer) return SourceRange(); ASSERT(buffer.id < bufferEntries.size()); const ExpansionInfo& info = std::get<ExpansionInfo>(bufferEntries[buffer.id]); return SourceRange(info.expansionStart, info.expansionEnd); } SourceLocation SourceManager::getOriginalLoc(SourceLocation location) const { auto buffer = location.buffer(); if (!buffer) return SourceLocation(); ASSERT(buffer.id < bufferEntries.size()); return std::get<ExpansionInfo>(bufferEntries[buffer.id]).originalLoc + location.offset(); } SourceLocation SourceManager::getFullyExpandedLoc(SourceLocation location) const { while (isMacroLoc(location)) location = getExpansionLoc(location); return location; } StringRef SourceManager::getSourceText(BufferID buffer) const { FileData* fd = getFileData(buffer); if (!fd) return nullptr; return StringRef(fd->mem); } SourceLocation SourceManager::createExpansionLoc(SourceLocation originalLoc, SourceLocation expansionStart, SourceLocation expansionEnd) { bufferEntries.emplace_back(ExpansionInfo(originalLoc, expansionStart, expansionEnd)); return SourceLocation(BufferID::get((uint32_t)(bufferEntries.size() - 1)), 0); } SourceBuffer SourceManager::assignText(StringRef text, SourceLocation includedFrom) { // Generate a placeholder name for this "file" return assignText(StringRef("<unnamed_buffer" + std::to_string(unnamedBufferCount++) + ">"), text, includedFrom); } SourceBuffer SourceManager::assignText(StringRef path, StringRef text, SourceLocation includedFrom) { SmallVectorSized<char, 2> buffer; buffer.appendRange(text); if (buffer.empty() || buffer.back() != '\0') buffer.append('\0'); return assignBuffer(path, std::move(buffer), includedFrom); } SourceBuffer SourceManager::appendText(BufferID buffer, StringRef text) { ASSERT(buffer); FileInfo& fi = std::get<FileInfo>(bufferEntries[buffer.id]); SourceLocation includeLoc = SourceLocation(buffer, fi.data->mem.count()); return assignText(text, includeLoc); } SourceBuffer SourceManager::assignBuffer(StringRef path, Vector<char>&& buffer, SourceLocation includedFrom) { Path fullPath = path; std::string canonicalStr = fullPath.str(); auto it = lookupCache.find(canonicalStr); ASSERT(it == lookupCache.end()); return cacheBuffer(std::move(canonicalStr), fullPath, includedFrom, std::move(buffer)); } SourceBuffer SourceManager::readSource(StringRef path) { ASSERT(path); return openCached(path, SourceLocation()); } SourceBuffer SourceManager::readHeader(StringRef path, SourceLocation includedFrom, bool isSystemPath) { // if the header is specified as an absolute path, just do a straight lookup ASSERT(path); Path p = path; if (p.isAbsolute()) return openCached(p, includedFrom); // system path lookups only look in system directories if (isSystemPath) { for (auto& d : systemDirectories) { SourceBuffer result = openCached(d + p, includedFrom); if (result.id) return result; } return SourceBuffer(); } // search relative to the current file FileData* fd = getFileData(includedFrom.buffer()); if (fd && fd->directory) { SourceBuffer result = openCached((*fd->directory) + p, includedFrom); if (result.id) return result; } // search additional include directories for (auto& d : userDirectories) { SourceBuffer result = openCached(d + p, includedFrom); if (result.id) return result; } return SourceBuffer(); } void SourceManager::addLineDirective(SourceLocation location, uint32_t lineNum, StringRef name, uint8_t level) { SourceLocation fileLocation = getFullyExpandedLoc(location); FileData* fd = getFileData(fileLocation.buffer()); if (!fd) return; uint32_t sourceLineNum = getRawLineNumber(fileLocation); fd->lineDirectives.emplace_back(sourceLineNum, lineNum, name, level); } SourceManager::FileData* SourceManager::getFileData(BufferID buffer) const { if (!buffer) return nullptr; ASSERT(buffer.id < bufferEntries.size()); return std::get<FileInfo>(bufferEntries[buffer.id]).data; } SourceBuffer SourceManager::createBufferEntry(FileData* fd, SourceLocation includedFrom) { ASSERT(fd); bufferEntries.emplace_back(FileInfo(fd, includedFrom)); return SourceBuffer { StringRef(fd->mem), BufferID::get((uint32_t)(bufferEntries.size() - 1)) }; } SourceBuffer SourceManager::openCached(const Path& fullPath, SourceLocation includedFrom) { Path absPath; try { absPath = Path::makeAbsolute(fullPath); } catch (std::runtime_error&) { return SourceBuffer(); } // first see if we have this file cached std::string canonicalStr = absPath.str(); auto it = lookupCache.find(canonicalStr); if (it != lookupCache.end()) { FileData* fd = it->second.get(); if (!fd) return SourceBuffer(); return createBufferEntry(fd, includedFrom); } // do the read Vector<char> buffer; if (!readFile(absPath, buffer)) { lookupCache.emplace(std::move(canonicalStr), nullptr); return SourceBuffer(); } return cacheBuffer(std::move(canonicalStr), absPath, includedFrom, std::move(buffer)); } SourceBuffer SourceManager::cacheBuffer(std::string&& canonicalPath, const Path& path, SourceLocation includedFrom, Vector<char>&& buffer) { std::string name = path.filename(); auto fd = std::make_unique<FileData>( &*directories.insert(path.parentPath()).first, name, std::move(buffer) ); FileData* fdPtr = lookupCache.emplace(std::move(canonicalPath), std::move(fd)).first->second.get(); return createBufferEntry(fdPtr, includedFrom); } bool SourceManager::readFile(const Path& path, Vector<char>& buffer) { size_t size; try { size = path.fileSize(); } catch (std::runtime_error&) { return false; } // + 1 for null terminator buffer.extend((uint32_t)size + 1); std::ifstream stream(path.str(), std::ios::binary); stream.read(buffer.begin(), size); // null-terminate the buffer while we're at it buffer.begin()[(uint32_t)size] = '\0'; return stream.good(); } void SourceManager::computeLineOffsets(const Vector<char>& buffer, std::vector<uint32_t>& offsets) { // first line always starts at offset 0 offsets.push_back(0); const char* ptr = buffer.begin(); const char* end = buffer.end(); while (ptr != end) { if (ptr[0] == '\n' || ptr[0] == '\r') { // if we see \r\n or \n\r skip both chars if ((ptr[1] == '\n' || ptr[1] == '\r') && ptr[0] != ptr[1]) ptr++; ptr++; offsets.push_back((uint32_t)(ptr - buffer.begin())); } else { ptr++; } } } const SourceManager::FileData::LineDirectiveInfo* SourceManager::FileData::getPreviousLineDirective(uint32_t rawLineNumber) const { auto it = std::lower_bound(lineDirectives.begin(), lineDirectives.end(), LineDirectiveInfo(rawLineNumber, 0, "", 0), LineDirectiveComparator()); if (it != lineDirectives.begin()) { // lower_bound will give us an iterator to the first directive after the command // let's instead get a pointer to the one right before it if (it == lineDirectives.end()) { // Check to see whether the actual last directive is before the // given line number if (lineDirectives.back().lineInFile >= rawLineNumber) return nullptr; } return &*(it - 1); } else { return nullptr; } } uint32_t SourceManager::getRawLineNumber(SourceLocation location) const { FileData* fd = getFileData(location.buffer()); if (!fd) return 0; // compute line offsets if we haven't already if (fd->lineOffsets.empty()) computeLineOffsets(fd->mem, fd->lineOffsets); // Find the first line offset that is greater than the given location offset. That iterator // then tells us how many lines away from the beginning we are. auto it = std::lower_bound(fd->lineOffsets.begin(), fd->lineOffsets.end(), location.offset()); // We want to ensure the line we return is strictly greater than the given location offset. // So if it is equal, add one to the lower bound we got uint32_t line = uint32_t(it - fd->lineOffsets.begin()); if (it != fd->lineOffsets.end() && *it == location.offset()) line++; return line; } } <|endoftext|>
<commit_before>//============================================================================= // // Adventure Game Studio (AGS) // // Copyright (C) 1999-2011 Chris Jones and 2011-20xx others // The full list of copyright holders can be found in the Copyright.txt // file, which is part of this source code distribution. // // The AGS source code is provided under the Artistic License 2.0. // A copy of this license can be found in the file License.txt and at // http://www.opensource.org/licenses/artistic-license-2.0.php // //============================================================================= // // C-Script run-time interpreter (c) 2001 Chris Jones // // You must DISABLE OPTIMIZATIONS AND REGISTER VARIABLES in your compiler // when compiling this, or strange results can happen. // // There is a problem with importing functions on 16-bit compilers: the // script system assumes that all parameters are passed as 4 bytes, which // ints are not on 16-bit systems. Be sure to define all parameters as longs, // or join the 21st century and switch to DJGPP or Visual C++. // //============================================================================= #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include "script/script_runtime.h" #include "script/script_common.h" #include "script/cc_error.h" #include "script/cc_options.h" #include "ac/dynobj/cc_dynamicarray.h" #include "ac/dynobj/managedobjectpool.h" #include "script/systemimports.h" #include "ac/statobj/staticobject.h" extern ccInstance *current_instance; // in script/cc_instance bool ccAddExternalStaticFunction(const char *name, ScriptAPIFunction *pfn) { return simp.add(name, RuntimeScriptValue().SetStaticFunction(pfn), NULL) == 0; } bool ccAddExternalPluginFunction(const char *name, void *pfn) { return simp.add(name, RuntimeScriptValue().SetPluginFunction(pfn), NULL) == 0; } bool ccAddExternalStaticObject(const char *name, void *ptr, ICCStaticObject *manager) { return simp.add(name, RuntimeScriptValue().SetStaticObject(ptr, manager), NULL) == 0; } bool ccAddExternalStaticArray(const char *name, void *ptr, StaticArray *array_mgr) { return simp.add(name, RuntimeScriptValue().SetStaticArray(ptr, array_mgr), NULL) == 0; } bool ccAddExternalDynamicObject(const char *name, void *ptr, ICCDynamicObject *manager) { return simp.add(name, RuntimeScriptValue().SetDynamicObject(ptr, manager), NULL) == 0; } bool ccAddExternalObjectFunction(const char *name, ScriptAPIObjectFunction *pfn) { return simp.add(name, RuntimeScriptValue().SetObjectFunction(pfn), NULL) == 0; } bool ccAddExternalScriptSymbol(const char *name, const RuntimeScriptValue &prval, ccInstance *inst) { return simp.add(name, prval, inst) == 0; } void ccRemoveExternalSymbol(const char *namof) { simp.remove(namof); } void ccRemoveAllSymbols() { simp.clear(); } ccInstance *loadedInstances[MAX_LOADED_INSTANCES] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; void nullfree(void *data) { if (data != NULL) free(data); } void *ccGetSymbolAddress(char *namof) { const ScriptImport *import = simp.getByName(namof); if (import) { return import->Value.Ptr; } return NULL; } bool ccAddExternalFunctionForPlugin(const char *name, void *pfn) { return simp_for_plugin.add(name, RuntimeScriptValue().SetPluginFunction(pfn), NULL) == 0; } void *ccGetSymbolAddressForPlugin(char *namof) { const ScriptImport *import = simp_for_plugin.getByName(namof); if (import) { return import->Value.Ptr; } return NULL; } new_line_hook_type new_line_hook = NULL; char ccRunnerCopyright[] = "ScriptExecuter32 v" SCOM_VERSIONSTR " (c) 2001 Chris Jones"; int maxWhileLoops = 0; // If a while loop does this many iterations without the // NofityScriptAlive function getting called, the script // aborts. Set to 0 to disable. void ccSetScriptAliveTimer (int numloop) { maxWhileLoops = numloop; } void ccNotifyScriptStillAlive () { if (current_instance != NULL) current_instance->flags |= INSTF_RUNNING; } void ccSetDebugHook(new_line_hook_type jibble) { new_line_hook = jibble; } int call_function(intptr_t addr, const RuntimeScriptValue *object, int numparm, const RuntimeScriptValue *parms) { if (!addr) { cc_error("null function pointer in call_function"); return -1; } if (numparm > 0 && !parms) { cc_error("invalid parameters array in call_function"); return -1; } intptr_t parm_value[9]; if (object) { parm_value[0] = (intptr_t)object->GetPtrWithOffset(); numparm++; } for (int ival = object ? 1 : 0, iparm = 0; ival < numparm; ++ival, ++iparm) { switch (parms[iparm].Type) { case kScValInteger: case kScValFloat: // AGS passes floats, copying their values into long variable case kScValPluginArg: parm_value[ival] = (intptr_t)parms[iparm].IValue; break; break; default: parm_value[ival] = (intptr_t)parms[iparm].GetPtrWithOffset(); break; } } // // AN IMPORTANT NOTE ON PARAM TYPE // of 2012-11-10 // //// NOTE of 2012-12-20: //// Everything said below is applicable only for calling //// exported plugin functions. // // Here we are sending parameters of type intptr_t to registered // function of unknown kind. Intptr_t is 32-bit for x32 build and // 64-bit for x64 build. // The exported functions usually have two types of parameters: // pointer and 'int' (32-bit). For x32 build those two have the // same size, but for x64 build first has 64-bit size while the // second remains 32-bit. // In formal case that would cause 'overflow' - function will // receive more data than needed (written to stack), with some // values shifted further by 32 bits. // // Upon testing, however, it was revealed that AMD64 processor, // the only platform we support x64 Linux AGS build on right now, // treats all the function parameters pushed to stack as 64-bit // values (few first parameters are sent via registers, and hence // are least concern anyway). Therefore, no 'overflow' occurs, // and 64-bit values are being effectively truncated to 32-bit // integers in the callee. // // Since this is still quite unreliable, this should be // reimplemented when there's enough free time available for // developers both for coding & testing. // // Most basic idea is to pass array of RuntimeScriptValue // objects (that hold type description) and get same RSV as a // return result. Keep in mind, though, that this solution will // require fixing ALL exported functions, so a good amount of // time and energy should be allocated for this task. // switch (numparm) { case 0: { int (*fparam) (); fparam = (int (*)())addr; return fparam(); } case 1: { int (*fparam) (intptr_t); fparam = (int (*)(intptr_t))addr; return fparam(parm_value[0]); } case 2: { int (*fparam) (intptr_t, intptr_t); fparam = (int (*)(intptr_t, intptr_t))addr; return fparam(parm_value[0], parm_value[1]); } case 3: { int (*fparam) (intptr_t, intptr_t, intptr_t); fparam = (int (*)(intptr_t, intptr_t, intptr_t))addr; return fparam(parm_value[0], parm_value[1], parm_value[2]); } case 4: { int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t); fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t))addr; return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3]); } case 5: { int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t); fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr; return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4]); } case 6: { int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t); fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr; return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5]); } case 7: { int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t); fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr; return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6]); } case 8: { int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t); fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr; return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6], parm_value[7]); } case 9: { int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t); fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr; return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6], parm_value[7], parm_value[8]); } } cc_error("too many arguments in call to function"); return -1; } <commit_msg>Engine: Fixed non-function symbols not being exported to plugins.<commit_after>//============================================================================= // // Adventure Game Studio (AGS) // // Copyright (C) 1999-2011 Chris Jones and 2011-20xx others // The full list of copyright holders can be found in the Copyright.txt // file, which is part of this source code distribution. // // The AGS source code is provided under the Artistic License 2.0. // A copy of this license can be found in the file License.txt and at // http://www.opensource.org/licenses/artistic-license-2.0.php // //============================================================================= // // C-Script run-time interpreter (c) 2001 Chris Jones // // You must DISABLE OPTIMIZATIONS AND REGISTER VARIABLES in your compiler // when compiling this, or strange results can happen. // // There is a problem with importing functions on 16-bit compilers: the // script system assumes that all parameters are passed as 4 bytes, which // ints are not on 16-bit systems. Be sure to define all parameters as longs, // or join the 21st century and switch to DJGPP or Visual C++. // //============================================================================= #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include "script/script_runtime.h" #include "script/script_common.h" #include "script/cc_error.h" #include "script/cc_options.h" #include "ac/dynobj/cc_dynamicarray.h" #include "ac/dynobj/managedobjectpool.h" #include "script/systemimports.h" #include "ac/statobj/staticobject.h" extern ccInstance *current_instance; // in script/cc_instance bool ccAddExternalStaticFunction(const char *name, ScriptAPIFunction *pfn) { return simp.add(name, RuntimeScriptValue().SetStaticFunction(pfn), NULL) == 0; } bool ccAddExternalPluginFunction(const char *name, void *pfn) { return simp.add(name, RuntimeScriptValue().SetPluginFunction(pfn), NULL) == 0; } bool ccAddExternalStaticObject(const char *name, void *ptr, ICCStaticObject *manager) { return simp.add(name, RuntimeScriptValue().SetStaticObject(ptr, manager), NULL) == 0; } bool ccAddExternalStaticArray(const char *name, void *ptr, StaticArray *array_mgr) { return simp.add(name, RuntimeScriptValue().SetStaticArray(ptr, array_mgr), NULL) == 0; } bool ccAddExternalDynamicObject(const char *name, void *ptr, ICCDynamicObject *manager) { return simp.add(name, RuntimeScriptValue().SetDynamicObject(ptr, manager), NULL) == 0; } bool ccAddExternalObjectFunction(const char *name, ScriptAPIObjectFunction *pfn) { return simp.add(name, RuntimeScriptValue().SetObjectFunction(pfn), NULL) == 0; } bool ccAddExternalScriptSymbol(const char *name, const RuntimeScriptValue &prval, ccInstance *inst) { return simp.add(name, prval, inst) == 0; } void ccRemoveExternalSymbol(const char *namof) { simp.remove(namof); } void ccRemoveAllSymbols() { simp.clear(); } ccInstance *loadedInstances[MAX_LOADED_INSTANCES] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; void nullfree(void *data) { if (data != NULL) free(data); } void *ccGetSymbolAddress(char *namof) { const ScriptImport *import = simp.getByName(namof); if (import) { return import->Value.Ptr; } return NULL; } bool ccAddExternalFunctionForPlugin(const char *name, void *pfn) { return simp_for_plugin.add(name, RuntimeScriptValue().SetPluginFunction(pfn), NULL) == 0; } void *ccGetSymbolAddressForPlugin(char *namof) { const ScriptImport *import = simp_for_plugin.getByName(namof); if (import) { return import->Value.Ptr; } else { // Also search the internal symbol table for non-function symbols import = simp.getByName(namof); if (import) { return import->Value.Ptr; } } return NULL; } new_line_hook_type new_line_hook = NULL; char ccRunnerCopyright[] = "ScriptExecuter32 v" SCOM_VERSIONSTR " (c) 2001 Chris Jones"; int maxWhileLoops = 0; // If a while loop does this many iterations without the // NofityScriptAlive function getting called, the script // aborts. Set to 0 to disable. void ccSetScriptAliveTimer (int numloop) { maxWhileLoops = numloop; } void ccNotifyScriptStillAlive () { if (current_instance != NULL) current_instance->flags |= INSTF_RUNNING; } void ccSetDebugHook(new_line_hook_type jibble) { new_line_hook = jibble; } int call_function(intptr_t addr, const RuntimeScriptValue *object, int numparm, const RuntimeScriptValue *parms) { if (!addr) { cc_error("null function pointer in call_function"); return -1; } if (numparm > 0 && !parms) { cc_error("invalid parameters array in call_function"); return -1; } intptr_t parm_value[9]; if (object) { parm_value[0] = (intptr_t)object->GetPtrWithOffset(); numparm++; } for (int ival = object ? 1 : 0, iparm = 0; ival < numparm; ++ival, ++iparm) { switch (parms[iparm].Type) { case kScValInteger: case kScValFloat: // AGS passes floats, copying their values into long variable case kScValPluginArg: parm_value[ival] = (intptr_t)parms[iparm].IValue; break; break; default: parm_value[ival] = (intptr_t)parms[iparm].GetPtrWithOffset(); break; } } // // AN IMPORTANT NOTE ON PARAM TYPE // of 2012-11-10 // //// NOTE of 2012-12-20: //// Everything said below is applicable only for calling //// exported plugin functions. // // Here we are sending parameters of type intptr_t to registered // function of unknown kind. Intptr_t is 32-bit for x32 build and // 64-bit for x64 build. // The exported functions usually have two types of parameters: // pointer and 'int' (32-bit). For x32 build those two have the // same size, but for x64 build first has 64-bit size while the // second remains 32-bit. // In formal case that would cause 'overflow' - function will // receive more data than needed (written to stack), with some // values shifted further by 32 bits. // // Upon testing, however, it was revealed that AMD64 processor, // the only platform we support x64 Linux AGS build on right now, // treats all the function parameters pushed to stack as 64-bit // values (few first parameters are sent via registers, and hence // are least concern anyway). Therefore, no 'overflow' occurs, // and 64-bit values are being effectively truncated to 32-bit // integers in the callee. // // Since this is still quite unreliable, this should be // reimplemented when there's enough free time available for // developers both for coding & testing. // // Most basic idea is to pass array of RuntimeScriptValue // objects (that hold type description) and get same RSV as a // return result. Keep in mind, though, that this solution will // require fixing ALL exported functions, so a good amount of // time and energy should be allocated for this task. // switch (numparm) { case 0: { int (*fparam) (); fparam = (int (*)())addr; return fparam(); } case 1: { int (*fparam) (intptr_t); fparam = (int (*)(intptr_t))addr; return fparam(parm_value[0]); } case 2: { int (*fparam) (intptr_t, intptr_t); fparam = (int (*)(intptr_t, intptr_t))addr; return fparam(parm_value[0], parm_value[1]); } case 3: { int (*fparam) (intptr_t, intptr_t, intptr_t); fparam = (int (*)(intptr_t, intptr_t, intptr_t))addr; return fparam(parm_value[0], parm_value[1], parm_value[2]); } case 4: { int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t); fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t))addr; return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3]); } case 5: { int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t); fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr; return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4]); } case 6: { int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t); fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr; return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5]); } case 7: { int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t); fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr; return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6]); } case 8: { int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t); fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr; return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6], parm_value[7]); } case 9: { int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t); fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr; return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6], parm_value[7], parm_value[8]); } } cc_error("too many arguments in call to function"); return -1; } <|endoftext|>
<commit_before>#include <Internal/CharacterControlManagerImpl.hpp> #include <Internal/PhysicsModuleImplementation.hpp> #include <cstdint> namespace DoremiEngine { namespace Physics { CharacterControlManagerImpl::CharacterControlManagerImpl(InternalPhysicsUtils& p_utils) : m_utils(p_utils) { m_manager = PxCreateControllerManager(*m_utils.m_worldScene); } CharacterControlManagerImpl::~CharacterControlManagerImpl() {} int CharacterControlManagerImpl::AddController(int p_id, int p_matID, XMFLOAT3 p_position, XMFLOAT2 p_dimensions) { // Set start attributes of the controller PxCapsuleControllerDesc desc; desc.setToDefault(); desc.position = PxExtendedVec3(p_position.x, p_position.y, p_position.z); desc.height = p_dimensions.x; desc.radius = p_dimensions.y; desc.material = m_utils.m_physicsMaterialManager->GetMaterial(p_matID); // DANGER! Assumes it already has material if(desc.material == NULL) { throw std::runtime_error("No physics material exists with that ID"); } desc.stepOffset = 0.1; desc.reportCallback = m_controllerCallback; desc.behaviorCallback = this; // Hard coded up vector desc.upDirection = PxVec3(0, 1, 0); m_controllers[p_id] = m_manager->createController(desc); m_IDsByControllers[m_controllers[p_id]] = p_id; SetCallback(p_id, (1 << 0), (1 << 0)); // Redundant return? return p_id; } int CharacterControlManagerImpl::MoveController(int p_id, XMFLOAT3 p_discplacement, float p_dt) { /* Some variable that apperas to define when the controller stops moving Tweak as necessary. Possibly could be moved to some other place.*/ float m_minDistTraveled = 0; // EMPTY FILTERS! PxControllerFilters filters; // Check if controller exists if(m_controllers.find(p_id) == m_controllers.end()) { // Controller did not exist throw std::runtime_error("No controller exists with id: " + p_id); } m_controllers[p_id]->move(PxVec3(p_discplacement.x, p_discplacement.y, p_discplacement.z), 0, p_dt, filters); // Redundant return? return p_id; } XMFLOAT3 CharacterControlManagerImpl::GetPosition(int p_id) { // Check if controller exists if(m_controllers.find(p_id) == m_controllers.end()) { // Controller did not exist throw std::runtime_error("No controller exists with id: " + p_id); } PxExtendedVec3 p = m_controllers[p_id]->getPosition(); return XMFLOAT3(p.x, p.y, p.z); } XMFLOAT4 CharacterControlManagerImpl::GetOrientation(int p_id) { // Check if controller exists if(m_controllers.find(p_id) == m_controllers.end()) { // Controller did not exist throw std::runtime_error("No controller exists with id: " + p_id); } PxQuat q = m_controllers[p_id]->getActor()->getGlobalPose().q; return XMFLOAT4(q.x, q.y, q.z, q.w); } void CharacterControlManagerImpl::SetCallback(int p_bodyID, int p_filterGroup, int p_filterMask) { // Check if controller exists if(m_controllers.find(p_bodyID) == m_controllers.end()) { // Controller did not exist throw std::runtime_error("No controller exists with id: " + p_bodyID); } PxFilterData filterData; filterData.word0 = p_filterGroup; // Own ID filterData.word1 = p_filterMask; // ID mask to filter pairs that trigger contact callback PxRigidActor* actor = m_controllers[p_bodyID]->getActor(); uint32_t numShapes = actor->getNbShapes(); // Magic allocation of memory (i think) PxShape** shapes = (PxShape**)m_utils.m_allocator.allocate(sizeof(PxShape*) * numShapes, 0, __FILE__, __LINE__); actor->getShapes(shapes, numShapes); for(uint32_t i = 0; i < numShapes; i++) { PxShape* shape = shapes[i]; shape->setSimulationFilterData(filterData); } if(shapes) { m_utils.m_allocator.deallocate(shapes); shapes = NULL; } } void CharacterControlManagerImpl::SetCallbackClass(PxUserControllerHitReport* p_callback) { m_controllerCallback = p_callback; } unordered_map<PxController*, int> CharacterControlManagerImpl::GetIdsByControllers() { return m_IDsByControllers; } PxControllerBehaviorFlags CharacterControlManagerImpl::getBehaviorFlags(const PxShape& shape, const PxActor& actor) { return PxControllerBehaviorFlag::eCCT_CAN_RIDE_ON_OBJECT; } PxControllerBehaviorFlags CharacterControlManagerImpl::getBehaviorFlags(const PxController& controller) { return PxControllerBehaviorFlags(0); } PxControllerBehaviorFlags CharacterControlManagerImpl::getBehaviorFlags(const PxObstacle& obstacle) { return PxControllerBehaviorFlags(0); } } }<commit_msg>PhysicsModule: fixed exception throwing<commit_after>#include <Internal/CharacterControlManagerImpl.hpp> #include <Internal/PhysicsModuleImplementation.hpp> #include <cstdint> namespace DoremiEngine { namespace Physics { CharacterControlManagerImpl::CharacterControlManagerImpl(InternalPhysicsUtils& p_utils) : m_utils(p_utils) { m_manager = PxCreateControllerManager(*m_utils.m_worldScene); } CharacterControlManagerImpl::~CharacterControlManagerImpl() {} int CharacterControlManagerImpl::AddController(int p_id, int p_matID, XMFLOAT3 p_position, XMFLOAT2 p_dimensions) { // Set start attributes of the controller PxCapsuleControllerDesc desc; desc.setToDefault(); desc.position = PxExtendedVec3(p_position.x, p_position.y, p_position.z); desc.height = p_dimensions.x; desc.radius = p_dimensions.y; desc.material = m_utils.m_physicsMaterialManager->GetMaterial(p_matID); // DANGER! Assumes it already has material if(desc.material == NULL) { throw std::runtime_error("No physics material exists with that ID"); } desc.stepOffset = 0.1; desc.reportCallback = m_controllerCallback; desc.behaviorCallback = this; // Hard coded up vector desc.upDirection = PxVec3(0, 1, 0); m_controllers[p_id] = m_manager->createController(desc); m_IDsByControllers[m_controllers[p_id]] = p_id; SetCallback(p_id, (1 << 0), (1 << 0)); // Redundant return? return p_id; } int CharacterControlManagerImpl::MoveController(int p_id, XMFLOAT3 p_discplacement, float p_dt) { /* Some variable that apperas to define when the controller stops moving Tweak as necessary. Possibly could be moved to some other place.*/ float m_minDistTraveled = 0; // EMPTY FILTERS! PxControllerFilters filters; // Check if controller exists if(m_controllers.find(p_id) == m_controllers.end()) { // Controller did not exist throw std::runtime_error("No controller exists with id: " + to_string(p_id)); } m_controllers[p_id]->move(PxVec3(p_discplacement.x, p_discplacement.y, p_discplacement.z), 0, p_dt, filters); // Redundant return? return p_id; } XMFLOAT3 CharacterControlManagerImpl::GetPosition(int p_id) { // Check if controller exists if(m_controllers.find(p_id) == m_controllers.end()) { // Controller did not exist throw std::runtime_error("No controller exists with id: " + to_string(p_id)); } PxExtendedVec3 p = m_controllers[p_id]->getPosition(); return XMFLOAT3(p.x, p.y, p.z); } XMFLOAT4 CharacterControlManagerImpl::GetOrientation(int p_id) { // Check if controller exists if(m_controllers.find(p_id) == m_controllers.end()) { // Controller did not exist throw std::runtime_error("No controller exists with id: " + to_string(p_id)); } PxQuat q = m_controllers[p_id]->getActor()->getGlobalPose().q; return XMFLOAT4(q.x, q.y, q.z, q.w); } void CharacterControlManagerImpl::SetCallback(int p_bodyID, int p_filterGroup, int p_filterMask) { // Check if controller exists if(m_controllers.find(p_bodyID) == m_controllers.end()) { // Controller did not exist throw std::runtime_error("No controller exists with id: " + to_string(p_bodyID)); } PxFilterData filterData; filterData.word0 = p_filterGroup; // Own ID filterData.word1 = p_filterMask; // ID mask to filter pairs that trigger contact callback PxRigidActor* actor = m_controllers[p_bodyID]->getActor(); uint32_t numShapes = actor->getNbShapes(); // Magic allocation of memory (i think) PxShape** shapes = (PxShape**)m_utils.m_allocator.allocate(sizeof(PxShape*) * numShapes, 0, __FILE__, __LINE__); actor->getShapes(shapes, numShapes); for(uint32_t i = 0; i < numShapes; i++) { PxShape* shape = shapes[i]; shape->setSimulationFilterData(filterData); } if(shapes) { m_utils.m_allocator.deallocate(shapes); shapes = NULL; } } void CharacterControlManagerImpl::SetCallbackClass(PxUserControllerHitReport* p_callback) { m_controllerCallback = p_callback; } unordered_map<PxController*, int> CharacterControlManagerImpl::GetIdsByControllers() { return m_IDsByControllers; } PxControllerBehaviorFlags CharacterControlManagerImpl::getBehaviorFlags(const PxShape& shape, const PxActor& actor) { return PxControllerBehaviorFlag::eCCT_CAN_RIDE_ON_OBJECT; } PxControllerBehaviorFlags CharacterControlManagerImpl::getBehaviorFlags(const PxController& controller) { return PxControllerBehaviorFlags(0); } PxControllerBehaviorFlags CharacterControlManagerImpl::getBehaviorFlags(const PxObstacle& obstacle) { return PxControllerBehaviorFlags(0); } } }<|endoftext|>
<commit_before>/* * coords_view.cpp * PHD Guiding * * Created by Oleg Kutkov * Copyright (c) 2017 Crimean Astrophysical observatory * All rights reserved. * * This source code is distributed under the following "BSD" license * 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 Bret McKee, Dad Dog Development Ltd, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * */ #include "phd.h" #include "coords_view.h" BEGIN_EVENT_TABLE(CoordsView, wxWindow) EVT_PAINT(CoordsView::OnPaint) END_EVENT_TABLE() CoordsView::CoordsView(wxWindow *parent): wxWindow(parent,wxID_ANY,wxDefaultPosition,wxDefaultSize, wxFULL_REPAINT_ON_RESIZE, "Scope position") { SetBackgroundStyle(wxBG_STYLE_PAINT); this->visible = false; } CoordsView::~CoordsView() { } void CoordsView::UpdateData(double ha, double ra, double dec, double ra_sp, double dec_sp) { curr_ha = ha; curr_ra = ra; curr_dec = dec; curr_ra_sp = ra_sp; curr_dec_sp = dec_sp; if (this->visible) { Refresh(); } } void CoordsView::SetState(bool is_active) { this->visible = is_active; if (is_active) Refresh(); } inline double frac(const double& x) { return x - floor(x); } inline void degree_to_coord(const double deg, int &h, int &m, int &s) { h = deg / 15; m = abs((int)(frac(deg / 15) * 60)); s = abs((int)(frac(frac(deg / 15) * 60) * 60)); } void CoordsView::OnPaint(wxPaintEvent& WXUNUSED(evt)) { wxAutoBufferedPaintDC dc(this); dc.SetBackground(wxColour(0,0,0)); dc.Clear(); if (!pFrame || !pFrame->pGuider || pFrame->pGuider->GetState() == STATE_UNINITIALIZED) return; #if defined (__APPLE__) const wxFont& smallFont = *wxSMALL_FONT; #else const wxFont& smallFont = *wxSWISS_FONT; #endif const int ysize = this->GetSize().GetY(); wxFont largeFont = smallFont.Scaled(1.25); dc.SetFont(largeFont); dc.SetTextForeground(*wxWHITE); dc.DrawText("t: ", 10, 5); dc.DrawText(wxString::Format(wxT("%3.2f"), curr_ha), 55, 5); dc.DrawText("RA: ", 10, 30); int ra_h, ra_m, ra_s; degree_to_coord(curr_ra, ra_h, ra_m, ra_s); dc.DrawText(wxString::Format(wxT("%02i h %02i m %02i s"), ra_h, ra_m, ra_s), 55, 30); dc.DrawText("DEC: ", 10, 55); int dec_h, dec_m, dec_s; degree_to_coord(curr_dec, dec_h, dec_m, dec_s); dc.DrawText(wxString::Format(wxT("%02i h %02i m %02i s"), dec_h, dec_m, dec_s), 55, 55); dc.DrawText("RA SPEED: ", 10, 85); dc.DrawText(wxString::Format(wxT("%.2f arcsec/sec"), curr_ra_sp), 105, 85); dc.DrawText("DEC SPEED: ", 10, 115); dc.DrawText(wxString::Format(wxT("%.2f arcsec/sec"), curr_dec_sp), 105, 115); } <commit_msg>text position changed<commit_after>/* * coords_view.cpp * PHD Guiding * * Created by Oleg Kutkov * Copyright (c) 2017 Crimean Astrophysical observatory * All rights reserved. * * This source code is distributed under the following "BSD" license * 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 Bret McKee, Dad Dog Development Ltd, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * */ #include "phd.h" #include "coords_view.h" BEGIN_EVENT_TABLE(CoordsView, wxWindow) EVT_PAINT(CoordsView::OnPaint) END_EVENT_TABLE() CoordsView::CoordsView(wxWindow *parent): wxWindow(parent,wxID_ANY,wxDefaultPosition,wxDefaultSize, wxFULL_REPAINT_ON_RESIZE, "Scope position") { SetBackgroundStyle(wxBG_STYLE_PAINT); this->visible = false; } CoordsView::~CoordsView() { } void CoordsView::UpdateData(double ha, double ra, double dec, double ra_sp, double dec_sp) { curr_ha = ha; curr_ra = ra; curr_dec = dec; curr_ra_sp = ra_sp; curr_dec_sp = dec_sp; if (this->visible) { Refresh(); } } void CoordsView::SetState(bool is_active) { this->visible = is_active; if (is_active) Refresh(); } inline double frac(const double& x) { return x - floor(x); } inline void degree_to_coord(const double deg, int &h, int &m, int &s) { h = deg / 15; m = abs((int)(frac(deg / 15) * 60)); s = abs((int)(frac(frac(deg / 15) * 60) * 60)); } void CoordsView::OnPaint(wxPaintEvent& WXUNUSED(evt)) { wxAutoBufferedPaintDC dc(this); dc.SetBackground(wxColour(0,0,0)); dc.Clear(); if (!pFrame || !pFrame->pGuider || pFrame->pGuider->GetState() == STATE_UNINITIALIZED) return; #if defined (__APPLE__) const wxFont& smallFont = *wxSMALL_FONT; #else const wxFont& smallFont = *wxSWISS_FONT; #endif const int ysize = this->GetSize().GetY(); wxFont largeFont = smallFont.Scaled(1.25); dc.SetFont(largeFont); dc.SetTextForeground(*wxWHITE); dc.DrawText("t: ", 10, 5); dc.DrawText(wxString::Format(wxT("%3.2f"), curr_ha), 55, 5); dc.DrawText("RA: ", 10, 30); int ra_h, ra_m, ra_s; degree_to_coord(curr_ra, ra_h, ra_m, ra_s); dc.DrawText(wxString::Format(wxT("%02i h %02i m %02i s"), ra_h, ra_m, ra_s), 55, 30); dc.DrawText("DEC: ", 10, 55); int dec_h, dec_m, dec_s; degree_to_coord(curr_dec, dec_h, dec_m, dec_s); dc.DrawText(wxString::Format(wxT("%02i h %02i m %02i s"), dec_h, dec_m, dec_s), 55, 55); dc.DrawText("RA SPEED: ", 10, 85); dc.DrawText(wxString::Format(wxT("%.2f arcsec/sec"), curr_ra_sp), 120, 85); dc.DrawText("DEC SPEED: ", 10, 115); dc.DrawText(wxString::Format(wxT("%.2f arcsec/sec"), curr_dec_sp), 120, 115); } <|endoftext|>
<commit_before>#ifdef WIN32 #include <windows.h> #define CURL_STATICLIB // this has to match the way the curl library was built. #else #include <stdlib.h> #endif #include <curl/curl.h> #include <string.h> #include "safe_fopen.h" struct Downloaded_Data { char* text; int size; }; static size_t WriteCallback(char *contents, size_t size, size_t nmemb, void *userdata) { Downloaded_Data *downloaded_data = (Downloaded_Data*)userdata; size_t data_size = size * nmemb; if(downloaded_data->text) { free(downloaded_data->text); downloaded_data->text = NULL; } if(size == 0) return 0; downloaded_data->text = (char*)malloc(data_size + 1); if(!downloaded_data->text) return 0; downloaded_data->size = data_size; memcpy(downloaded_data->text, contents, data_size); downloaded_data->text[data_size] = 0; return data_size; } void print_help() { printf("This utility accepts arguments in the following format:\n"); printf("config_fetch http://url.to.config.file [path_to_cache_file]\n"); printf("config_fetch -help"); } bool print_cached_file(const char *cached_path) { FILE *fp; int character; fp = safe_fopen_no_create_follow(cached_path, "rb"); if(!fp) { printf("Error: Failed to open cache file for reading.\n"); return false; } while((character = getc(fp)) != EOF) { putchar(character); } fclose(fp); return true; } int main(int argc, char **argv) { CURL *handle = NULL; int rval = -1; const char *cache_path; Downloaded_Data downloaded_data; FILE *fp = NULL; long http_code; int cb = 0; downloaded_data.text = NULL; downloaded_data.size = 0; if(argc < 2 || argc > 3) { print_help(); return -1; } if(strncmp(argv[1], "-h", 2) == 0) { print_help(); return 0; } if(argc == 3) cache_path = argv[2]; else cache_path = "config_cache.local"; #ifndef WIN32 curl_global_init(CURL_GLOBAL_NOTHING); #endif handle = curl_easy_init(); if(!handle) { fprintf(stderr, "Error attempting to initialize CURL library.\n"); return -1; } curl_easy_setopt(handle, CURLOPT_URL, argv[1]); curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(handle, CURLOPT_WRITEDATA, &downloaded_data); curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, -1); rval = curl_easy_perform(handle); if(rval || !downloaded_data.text) { print_cached_file(cache_path); goto Cleanup; } rval = curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &http_code); if(rval) { print_cached_file(cache_path); goto Cleanup; } if(http_code != 200) { print_cached_file(cache_path); goto Cleanup; } cb = fwrite(downloaded_data.text, 1, downloaded_data.size, stdout); if (cb != downloaded_data.size) { fprintf(stderr, "error: could not write entire config to stdout\n"); } fp = safe_fcreate_replace_if_exists(cache_path, "wb"); if(!fp) goto Cleanup; cb = fwrite(downloaded_data.text, 1, downloaded_data.size, fp); if (cb != downloaded_data.size) { fprintf(stderr, "error: could not write entire config to cache file!\n"); } fclose(fp); Cleanup: if(downloaded_data.text) free(downloaded_data.text); curl_easy_cleanup(handle); curl_global_cleanup(); return rval; // 0 on success } <commit_msg>fix config_fetch so that doesn't just write the last buffer to disk/stdout #4018 ===VersionHistory:None== bug never shipped<commit_after>#ifdef WIN32 #include <windows.h> #define CURL_STATICLIB // this has to match the way the curl library was built. #else #include <stdlib.h> #endif #include <curl/curl.h> #include <string.h> #include <string> #include "safe_fopen.h" static size_t WriteCallback(char *contents, size_t size, size_t nmemb, void *userdata) { std::string * ptext = (std::string *)userdata; size_t data_size = size * nmemb; ptext->append(contents, size * nmemb); return data_size; } void print_help() { printf("This utility accepts arguments in the following format:\n"); printf("config_fetch http://url.to.config.file [path_to_cache_file]\n"); printf("config_fetch -help"); } bool print_cached_file(const char *cached_path) { FILE *fp; int character; fp = safe_fopen_no_create_follow(cached_path, "rb"); if(!fp) { printf("Error: Failed to open cache file for reading.\n"); return false; } while((character = getc(fp)) != EOF) { putchar(character); } fclose(fp); return true; } int main(int argc, char **argv) { CURL *handle = NULL; int rval = -1; const char *cache_path; std::string downloaded_data; FILE *fp = NULL; long http_code; int cb = 0; if(argc < 2 || argc > 3) { print_help(); return -1; } if(strncmp(argv[1], "-h", 2) == 0) { print_help(); return 0; } if(argc == 3) cache_path = argv[2]; else cache_path = "config_cache.local"; #ifndef WIN32 curl_global_init(CURL_GLOBAL_NOTHING); #endif handle = curl_easy_init(); if(!handle) { fprintf(stderr, "Error attempting to initialize CURL library.\n"); return -1; } curl_easy_setopt(handle, CURLOPT_URL, argv[1]); curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(handle, CURLOPT_WRITEDATA, &downloaded_data); curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, -1); rval = curl_easy_perform(handle); if(rval || downloaded_data.empty()) { print_cached_file(cache_path); goto Cleanup; } rval = curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &http_code); if(rval) { print_cached_file(cache_path); goto Cleanup; } if(http_code != 200) { print_cached_file(cache_path); goto Cleanup; } cb = fwrite(downloaded_data.c_str(), 1, downloaded_data.size(), stdout); if (cb != (int)downloaded_data.size()) { fprintf(stderr, "error: could not write entire config to stdout\n"); } fp = safe_fcreate_replace_if_exists(cache_path, "wb"); if(!fp) goto Cleanup; cb = fwrite(downloaded_data.c_str(), 1, downloaded_data.size(), fp); if (cb != (int)downloaded_data.size()) { fprintf(stderr, "error: could not write entire config to cache file!\n"); } fclose(fp); Cleanup: // if(downloaded_data.text) free(downloaded_data.text); curl_easy_cleanup(handle); curl_global_cleanup(); return rval; // 0 on success } <|endoftext|>
<commit_before>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2012, 2017 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/cameras/Camera_Spherical.hpp" #include "openMVG/features/feature.hpp" #include "openMVG/features/sift/SIFT_Anatomy_Image_Describer.hpp" #include "openMVG/features/svg_features.hpp" #include "openMVG/image/image_io.hpp" #include "openMVG/image/image_concat.hpp" #include "openMVG/matching/regions_matcher.hpp" #include "openMVG/matching/svg_matches.hpp" #include "openMVG/multiview/conditioning.hpp" #include "openMVG/multiview/essential.hpp" #include "openMVG/multiview/triangulation.hpp" #include "openMVG/multiview/solver_essential_spherical.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansac.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansacKernelAdaptator.hpp" #include "openMVG/sfm/pipelines/sfm_robust_model_estimation.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_BA_ceres.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <iostream> #include <string> using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::image; using namespace openMVG::matching; using namespace openMVG::robust; using namespace openMVG::sfm; using namespace std; int main(int argc, char **argv) { CmdLine cmd; string jpg_filenameL, jpg_filenameR; cmd.add( make_option('a', jpg_filenameL, "input_a") ); cmd.add( make_option('b', jpg_filenameR, "input_b") ); std::cout << "Compute the relative pose between two spherical image." << "\nUse an Acontrario robust estimation based on angular errors." << std::endl; try { if (argc == 1) { const std::string sInputDir = std::string(THIS_SOURCE_DIR); jpg_filenameL = sInputDir + "/SponzaLion000.jpg"; jpg_filenameR = sInputDir + "/SponzaLion001.jpg"; } else { cmd.process(argc, argv); } } catch (const std::string& s) { std::cout << "Invalid usage of arguments -a IMGA -b IMGB" << std::endl; return EXIT_FAILURE; } Image<unsigned char> imageL, imageR; ReadImage(jpg_filenameL.c_str(), &imageL); ReadImage(jpg_filenameR.c_str(), &imageR); // Setup 2 camera intrinsics cameras::Intrinsic_Spherical cameraL(imageL.Width(), imageL.Height()), cameraR(imageR.Width(), imageR.Height()); //-- // Detect regions thanks to an image_describer //-- using namespace openMVG::features; std::unique_ptr<Image_describer> image_describer (new SIFT_Anatomy_Image_describer(SIFT_Anatomy_Image_describer::Params(-1))); std::map<IndexT, std::unique_ptr<features::Regions> > regions_perImage; image_describer->Describe(imageL, regions_perImage[0]); image_describer->Describe(imageR, regions_perImage[1]); const SIFT_Regions *regionsL = dynamic_cast<const SIFT_Regions*>(regions_perImage.at(0).get()), *regionsR = dynamic_cast<const SIFT_Regions*>(regions_perImage.at(1).get()); const PointFeatures featsL = regions_perImage.at(0)->GetRegionsPositions(), featsR = regions_perImage.at(1)->GetRegionsPositions(); std::cout << "Left image SIFT count: " << featsL.size() << std::endl << "Right image SIFT count: "<< featsR.size() << std::endl; // Show both images side by side { Image<unsigned char> concat; ConcatH(imageL, imageR, concat); string out_filename = "01_concat.jpg"; WriteImage(out_filename.c_str(), concat); } //- Draw features on the two image (side by side) { Features2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->GetRegionsPositions(), "02_features.svg" ); } std::vector<IndMatch> vec_PutativeMatches; //-- Perform matching -> find Nearest neighbor, filtered with Distance ratio { // Find corresponding points matching::DistanceRatioMatch( 0.8, matching::ANN_L2, *regions_perImage.at(0).get(), *regions_perImage.at(1).get(), vec_PutativeMatches); IndMatchDecorator<float> matchDeduplicator(vec_PutativeMatches, featsL, featsR); matchDeduplicator.getDeduplicated(vec_PutativeMatches); // Draw correspondences after Nearest Neighbor ratio filter const bool bVertical = true; Matches2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->GetRegionsPositions(), vec_PutativeMatches, "03_Matches.svg", bVertical ); } // Essential geometry filtering of putative matches { //A. get back interest point and send it to the robust estimation framework Mat xL(2, vec_PutativeMatches.size()), xR(2, vec_PutativeMatches.size()); for (size_t k = 0; k < vec_PutativeMatches.size(); ++k) { const PointFeature & imaL = featsL[vec_PutativeMatches[k].i_]; const PointFeature & imaR = featsR[vec_PutativeMatches[k].j_]; xL.col(k) = imaL.coords().cast<double>(); xR.col(k) = imaR.coords().cast<double>(); } //-- Convert planar to spherical coordinates Mat xL_spherical(3,vec_PutativeMatches.size()), xR_spherical(3,vec_PutativeMatches.size()); for (size_t iCol = 0; iCol < vec_PutativeMatches.size(); ++iCol) { xL_spherical.col(iCol) = cameraL(xL.col(iCol)); xR_spherical.col(iCol) = cameraR(xR.col(iCol)); } //-- Essential matrix robust estimation from spherical bearing vectors { std::vector<uint32_t> vec_inliers; // Define the AContrario angular error adaptor using KernelType = openMVG::robust::ACKernelAdaptor_AngularRadianError< // Use the 8 point solver in order to estimate E openMVG::spherical_cam::EightPointRelativePoseSolver, openMVG::spherical_cam::AngularError, Mat3>; KernelType kernel(xL_spherical, xR_spherical); // Robust estimation of the Essential matrix and it's precision Mat3 E; const double precision = std::numeric_limits<double>::infinity(); const std::pair<double,double> ACRansacOut = ACRANSAC(kernel, vec_inliers, 1024, &E, precision, true); const double & threshold = ACRansacOut.first; std::cout << "\n Angular threshold found: " << R2D(threshold) << "(Degree)"<<std::endl; std::cout << "\n #Putatives/#inliers : " << xL_spherical.cols() << "/" << vec_inliers.size() << "\n" << std::endl; const bool bVertical = true; InlierMatches2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->GetRegionsPositions(), vec_PutativeMatches, vec_inliers, "04_inliers.svg", bVertical ); if (vec_inliers.size() > 60) // 60 is used to filter solution with few common geometric matches (unstable solution) { // Decompose the essential matrix and keep the best solution (if any) Mat3 R; Vec3 t; std::vector<uint32_t> inliers_indexes; std::vector<Vec3> inliers_X; if (openMVG::sfm::estimate_Rt_fromE(xL_spherical, xR_spherical, E, vec_inliers, &R, &t, &inliers_indexes, &inliers_X)) { // Lets make a BA on the scene to check if it relative pose and structure can be refined // Setup a SfM scene with two view corresponding the pictures SfM_Data tiny_scene; tiny_scene.views[0].reset(new View("", 0, 0, 0, imageL.Width(), imageL.Height())); tiny_scene.views[1].reset(new View("", 1, 0, 1, imageR.Width(), imageR.Height())); // Setup shared intrinsics camera data tiny_scene.intrinsics[0].reset(new Intrinsic_Spherical(imageR.Width(), imageR.Height())); // Setup poses camera data const Pose3 pose0 = tiny_scene.poses[tiny_scene.views[0]->id_pose] = Pose3(Mat3::Identity(), Vec3::Zero()); const Pose3 pose1 = tiny_scene.poses[tiny_scene.views[1]->id_pose] = Pose3(R, - R.transpose() * t); // Add a new landmark (3D point with its image observations) for (int i = 0; i < inliers_indexes.size(); ++i) { Landmark landmark; landmark.X = inliers_X[i]; landmark.obs[tiny_scene.views[0]->id_view] = Observation(xL.col(inliers_indexes[i]), 0); landmark.obs[tiny_scene.views[1]->id_view] = Observation(xR.col(inliers_indexes[i]), 0); tiny_scene.structure.insert(std::make_pair(tiny_scene.structure.size(), landmark)); } Save(tiny_scene, "EssentialGeometry_start.ply", ESfM_Data(ALL)); std::vector<double> residuals; // Perform Bundle Adjustment of the scene Bundle_Adjustment_Ceres bundle_adjustment_obj; if (bundle_adjustment_obj.Adjust(tiny_scene, Optimize_Options( Intrinsic_Parameter_Type::NONE, Extrinsic_Parameter_Type::ADJUST_ALL, Structure_Parameter_Type::ADJUST_ALL))) { // Compute reprojection error const Pose3 pose0 = tiny_scene.poses[tiny_scene.views[0]->id_pose]; const Pose3 pose1 = tiny_scene.poses[tiny_scene.views[1]->id_pose]; for (Landmarks::const_iterator iter = tiny_scene.GetLandmarks().begin(); iter != tiny_scene.GetLandmarks().end(); ++iter) { const IndexT trackId = iter->first; const Landmark & landmark = iter->second; const Observations & obs = landmark.obs; Observations::const_iterator iterObs_xI = obs.find(tiny_scene.views[0]->id_view); Observations::const_iterator iterObs_xJ = obs.find(tiny_scene.views[1]->id_view); const Observation & ob_x0 = iterObs_xI->second; const Observation & ob_x1 = iterObs_xJ->second; const Vec2 residual_I = cameraL.residual(pose0, landmark.X, ob_x0.x); const Vec2 residual_J = cameraR.residual(pose1, landmark.X, ob_x1.x); residuals.push_back(residual_I.norm()); residuals.push_back(residual_J.norm()); } std::cout << "Residual statistics (pixels):" << std::endl; minMaxMeanMedian<double>( residuals.begin(), residuals.end()); Save(tiny_scene, "EssentialGeometry_refined.ply", ESfM_Data(ALL)); } } } } } return EXIT_SUCCESS; } <commit_msg>Enhance reproducibility.<commit_after>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2012, 2017 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/cameras/Camera_Spherical.hpp" #include "openMVG/features/feature.hpp" #include "openMVG/features/sift/SIFT_Anatomy_Image_Describer.hpp" #include "openMVG/features/svg_features.hpp" #include "openMVG/image/image_io.hpp" #include "openMVG/image/image_concat.hpp" #include "openMVG/matching/regions_matcher.hpp" #include "openMVG/matching/svg_matches.hpp" #include "openMVG/multiview/conditioning.hpp" #include "openMVG/multiview/essential.hpp" #include "openMVG/multiview/triangulation.hpp" #include "openMVG/multiview/solver_essential_spherical.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansac.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansacKernelAdaptator.hpp" #include "openMVG/sfm/pipelines/sfm_robust_model_estimation.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_BA_ceres.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <iostream> #include <string> using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::image; using namespace openMVG::matching; using namespace openMVG::robust; using namespace openMVG::sfm; using namespace std; int main(int argc, char **argv) { CmdLine cmd; string jpg_filenameL, jpg_filenameR; cmd.add( make_option('a', jpg_filenameL, "input_a") ); cmd.add( make_option('b', jpg_filenameR, "input_b") ); std::cout << "Compute the relative pose between two spherical image." << "\nUse an Acontrario robust estimation based on angular errors." << std::endl; try { if (argc == 1) { const std::string sInputDir = std::string(THIS_SOURCE_DIR); jpg_filenameL = sInputDir + "/SponzaLion000.jpg"; jpg_filenameR = sInputDir + "/SponzaLion001.jpg"; } else { cmd.process(argc, argv); } } catch (const std::string& s) { std::cout << "Invalid usage of arguments -a IMGA -b IMGB" << std::endl; return EXIT_FAILURE; } Image<unsigned char> imageL, imageR; ReadImage(jpg_filenameL.c_str(), &imageL); ReadImage(jpg_filenameR.c_str(), &imageR); // Setup 2 camera intrinsics cameras::Intrinsic_Spherical cameraL(imageL.Width(), imageL.Height()), cameraR(imageR.Width(), imageR.Height()); //-- // Detect regions thanks to an image_describer //-- using namespace openMVG::features; std::unique_ptr<Image_describer> image_describer (new SIFT_Anatomy_Image_describer(SIFT_Anatomy_Image_describer::Params(-1))); std::map<IndexT, std::unique_ptr<features::Regions> > regions_perImage; image_describer->Describe(imageL, regions_perImage[0]); image_describer->Describe(imageR, regions_perImage[1]); const SIFT_Regions *regionsL = dynamic_cast<const SIFT_Regions*>(regions_perImage.at(0).get()), *regionsR = dynamic_cast<const SIFT_Regions*>(regions_perImage.at(1).get()); const PointFeatures featsL = regions_perImage.at(0)->GetRegionsPositions(), featsR = regions_perImage.at(1)->GetRegionsPositions(); std::cout << "Left image SIFT count: " << featsL.size() << std::endl << "Right image SIFT count: "<< featsR.size() << std::endl; // Show both images side by side { Image<unsigned char> concat; ConcatH(imageL, imageR, concat); string out_filename = "01_concat.jpg"; WriteImage(out_filename.c_str(), concat); } //- Draw features on the two image (side by side) { Features2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->GetRegionsPositions(), "02_features.svg" ); } std::vector<IndMatch> vec_PutativeMatches; //-- Perform matching -> find Nearest neighbor, filtered with Distance ratio { // Find corresponding points matching::DistanceRatioMatch( 0.8, matching::BRUTE_FORCE_L2, *regions_perImage.at(0).get(), *regions_perImage.at(1).get(), vec_PutativeMatches); IndMatchDecorator<float> matchDeduplicator(vec_PutativeMatches, featsL, featsR); matchDeduplicator.getDeduplicated(vec_PutativeMatches); // Draw correspondences after Nearest Neighbor ratio filter const bool bVertical = true; Matches2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->GetRegionsPositions(), vec_PutativeMatches, "03_Matches.svg", bVertical ); } // Essential geometry filtering of putative matches { //A. get back interest point and send it to the robust estimation framework Mat xL(2, vec_PutativeMatches.size()), xR(2, vec_PutativeMatches.size()); for (size_t k = 0; k < vec_PutativeMatches.size(); ++k) { const PointFeature & imaL = featsL[vec_PutativeMatches[k].i_]; const PointFeature & imaR = featsR[vec_PutativeMatches[k].j_]; xL.col(k) = imaL.coords().cast<double>(); xR.col(k) = imaR.coords().cast<double>(); } //-- Convert planar to spherical coordinates Mat xL_spherical(3,vec_PutativeMatches.size()), xR_spherical(3,vec_PutativeMatches.size()); for (size_t iCol = 0; iCol < vec_PutativeMatches.size(); ++iCol) { xL_spherical.col(iCol) = cameraL(xL.col(iCol)); xR_spherical.col(iCol) = cameraR(xR.col(iCol)); } //-- Essential matrix robust estimation from spherical bearing vectors { std::vector<uint32_t> vec_inliers; // Define the AContrario angular error adaptor using KernelType = openMVG::robust::ACKernelAdaptor_AngularRadianError< // Use the 8 point solver in order to estimate E openMVG::spherical_cam::EightPointRelativePoseSolver, openMVG::spherical_cam::AngularError, Mat3>; KernelType kernel(xL_spherical, xR_spherical); // Robust estimation of the Essential matrix and it's precision Mat3 E; const double precision = std::numeric_limits<double>::infinity(); const std::pair<double,double> ACRansacOut = ACRANSAC(kernel, vec_inliers, 1024, &E, precision, true); const double & threshold = ACRansacOut.first; std::cout << "\n Angular threshold found: " << R2D(threshold) << "(Degree)"<<std::endl; std::cout << "\n #Putatives/#inliers : " << xL_spherical.cols() << "/" << vec_inliers.size() << "\n" << std::endl; const bool bVertical = true; InlierMatches2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->GetRegionsPositions(), vec_PutativeMatches, vec_inliers, "04_inliers.svg", bVertical ); if (vec_inliers.size() > 60) // 60 is used to filter solution with few common geometric matches (unstable solution) { // Decompose the essential matrix and keep the best solution (if any) Mat3 R; Vec3 t; std::vector<uint32_t> inliers_indexes; std::vector<Vec3> inliers_X; if (openMVG::sfm::estimate_Rt_fromE(xL_spherical, xR_spherical, E, vec_inliers, &R, &t, &inliers_indexes, &inliers_X)) { // Lets make a BA on the scene to check if it relative pose and structure can be refined // Setup a SfM scene with two view corresponding the pictures SfM_Data tiny_scene; tiny_scene.views[0].reset(new View("", 0, 0, 0, imageL.Width(), imageL.Height())); tiny_scene.views[1].reset(new View("", 1, 0, 1, imageR.Width(), imageR.Height())); // Setup shared intrinsics camera data tiny_scene.intrinsics[0].reset(new Intrinsic_Spherical(imageR.Width(), imageR.Height())); // Setup poses camera data const Pose3 pose0 = tiny_scene.poses[tiny_scene.views[0]->id_pose] = Pose3(Mat3::Identity(), Vec3::Zero()); const Pose3 pose1 = tiny_scene.poses[tiny_scene.views[1]->id_pose] = Pose3(R, - R.transpose() * t); // Add a new landmark (3D point with its image observations) for (int i = 0; i < inliers_indexes.size(); ++i) { Landmark landmark; landmark.X = inliers_X[i]; landmark.obs[tiny_scene.views[0]->id_view] = Observation(xL.col(inliers_indexes[i]), 0); landmark.obs[tiny_scene.views[1]->id_view] = Observation(xR.col(inliers_indexes[i]), 0); tiny_scene.structure.insert(std::make_pair(tiny_scene.structure.size(), landmark)); } Save(tiny_scene, "EssentialGeometry_start.ply", ESfM_Data(ALL)); std::vector<double> residuals; // Perform Bundle Adjustment of the scene Bundle_Adjustment_Ceres bundle_adjustment_obj; if (bundle_adjustment_obj.Adjust(tiny_scene, Optimize_Options( Intrinsic_Parameter_Type::NONE, Extrinsic_Parameter_Type::ADJUST_ALL, Structure_Parameter_Type::ADJUST_ALL))) { // Compute reprojection error const Pose3 pose0 = tiny_scene.poses[tiny_scene.views[0]->id_pose]; const Pose3 pose1 = tiny_scene.poses[tiny_scene.views[1]->id_pose]; for (Landmarks::const_iterator iter = tiny_scene.GetLandmarks().begin(); iter != tiny_scene.GetLandmarks().end(); ++iter) { const IndexT trackId = iter->first; const Landmark & landmark = iter->second; const Observations & obs = landmark.obs; Observations::const_iterator iterObs_xI = obs.find(tiny_scene.views[0]->id_view); Observations::const_iterator iterObs_xJ = obs.find(tiny_scene.views[1]->id_view); const Observation & ob_x0 = iterObs_xI->second; const Observation & ob_x1 = iterObs_xJ->second; const Vec2 residual_I = cameraL.residual(pose0, landmark.X, ob_x0.x); const Vec2 residual_J = cameraR.residual(pose1, landmark.X, ob_x1.x); residuals.push_back(residual_I.norm()); residuals.push_back(residual_J.norm()); } std::cout << "Residual statistics (pixels):" << std::endl; minMaxMeanMedian<double>( residuals.begin(), residuals.end()); Save(tiny_scene, "EssentialGeometry_refined.ply", ESfM_Data(ALL)); } } } } } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved */ #include "../StroikaPreComp.h" #include "../../Foundation/Characters/String_Constant.h" #include "../../Foundation/Characters/ToString.h" #include "../../Foundation/Execution/Exceptions.h" #include "../../Foundation/IO/Network/HTTP/ClientErrorException.h" #include "../../Foundation/IO/Network/HTTP/Headers.h" #include "Router.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Memory; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::WebServer; using IO::Network::HTTP::ClientErrorException; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** ************************* WebServer::Router::Rep_ ****************************** ******************************************************************************** */ struct Router::Rep_ : Interceptor::_IRep { Rep_ (const Sequence<Route>& routes) : fRoutes_ (routes) { } virtual void HandleFault ([[maybe_unused]] Message* m, [[maybe_unused]] const exception_ptr& e) noexcept override { } virtual void HandleMessage (Message* m) override { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx{L"Router::Rep_::HandleMessage", L"(...method=%s,url=%s)", m->GetRequestHTTPMethod ().c_str (), Characters::ToString (m->GetRequestURL ()).c_str ()}; #endif Sequence<String> matches; optional<RequestHandler> handler = Lookup_ (*m->PeekRequest (), &matches); if (handler) { (*handler) (m, matches); } else { if (optional<Set<String>> o = GetAllowedMethodsForRequest_ (*m->PeekRequest ())) { // From 10.4.6 405 Method Not Allowed // The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. // The response MUST include an Allow header containing a list of valid methods for the requested resource. Assert (not o->empty ()); StringBuilder res; o->Apply ([&res] (const String& i) { if (not res.empty ()) { res += L", "; } res += i; }); m->PeekResponse ()->AddHeader (IO::Network::HTTP::HeaderName::kAllow, res.str ()); Execution::Throw (ClientErrorException (IO::Network::HTTP::StatusCodes::kMethodNotAllowed)); } else { DbgTrace (L"Router 404: (...url=%s)", Characters::ToString (m->GetRequestURL ()).c_str ()); Execution::Throw (ClientErrorException (IO::Network::HTTP::StatusCodes::kNotFound)); } } } optional<RequestHandler> Lookup_ (const Request& request, Sequence<String>* matches) const { String method = request.GetHTTPMethod (); URI url = request.GetURL (); String hostRelPath; try { hostRelPath = url.GetAbsPath<String> ().SubString (1); // According to https://tools.ietf.org/html/rfc2616#section-5.1.2 - the URI must be abs_path } catch (...) { Execution::Throw (ClientErrorException (IO::Network::HTTP::StatusCodes::kBadRequest, L"request URI requires an absolute path"sv)); } // We interpret routes as matching against a relative path from the root for (Route r : fRoutes_) { if (r.fVerbMatch_ and not method.Match (*r.fVerbMatch_)) { continue; } if (matches == nullptr) { if (r.fPathMatch_ and not hostRelPath.Match (*r.fPathMatch_)) { continue; } } else { if (r.fPathMatch_ and not hostRelPath.Match (*r.fPathMatch_, matches)) { continue; } } if (r.fRequestMatch_ and not(*r.fRequestMatch_) (request)) { continue; } return r.fHandler_; } return nullopt; } optional<Set<String>> GetAllowedMethodsForRequest_ (const Request& request) const { URI url = request.GetURL (); String hostRelPath = url.GetPath (); static const Set<String> kMethods2Try_{L"GET"sv, L"PUT"sv, L"OPTIONS"sv, L"DELETE"sv, L"POST"sv}; Set<String> methods; for (String method : kMethods2Try_) { for (Route r : fRoutes_) { if (r.fVerbMatch_ and not method.Match (*r.fVerbMatch_)) { continue; } if (r.fPathMatch_ and not hostRelPath.Match (*r.fPathMatch_)) { continue; } if (r.fRequestMatch_ and not(*r.fRequestMatch_) (request)) { continue; } methods.Add (method); } } return methods.empty () ? optional<Set<String>>{} : optional<Set<String>>{methods}; } const Sequence<Route> fRoutes_; // no need for synchronization cuz constant - just set on construction }; /* ******************************************************************************** *************************** WebServer::Router ********************************** ******************************************************************************** */ Router::Router (const Sequence<Route>& routes) : inherited (make_shared<Rep_> (routes)) { } optional<RequestHandler> Router::Lookup (const Request& request) const { return _GetRep<Rep_> ().Lookup_ (request, nullptr); } <commit_msg>minor cleanups to WebServer Router code, and fixed one regression - due to GetPath/GetAbsPath change - / in name - with getting allowed methods for path<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved */ #include "../StroikaPreComp.h" #include "../../Foundation/Characters/String_Constant.h" #include "../../Foundation/Characters/ToString.h" #include "../../Foundation/Execution/Exceptions.h" #include "../../Foundation/IO/Network/HTTP/ClientErrorException.h" #include "../../Foundation/IO/Network/HTTP/Headers.h" #include "../../Foundation/IO/Network/HTTP/Methods.h" #include "Router.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Memory; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::WebServer; using HTTP::ClientErrorException; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** ************************* WebServer::Router::Rep_ ****************************** ******************************************************************************** */ struct Router::Rep_ : Interceptor::_IRep { Rep_ (const Sequence<Route>& routes) : fRoutes_ (routes) { } virtual void HandleFault ([[maybe_unused]] Message* m, [[maybe_unused]] const exception_ptr& e) noexcept override { } virtual void HandleMessage (Message* m) override { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx{L"Router::Rep_::HandleMessage", L"(...method=%s,url=%s)", m->GetRequestHTTPMethod ().c_str (), Characters::ToString (m->GetRequestURL ()).c_str ()}; #endif Sequence<String> matches; optional<RequestHandler> handler = Lookup_ (*m->PeekRequest (), &matches); if (handler) { (*handler) (m, matches); } else { if (optional<Set<String>> o = GetAllowedMethodsForRequest_ (*m->PeekRequest ())) { // From 10.4.6 405 Method Not Allowed // The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. // The response MUST include an Allow header containing a list of valid methods for the requested resource. Assert (not o->empty ()); StringBuilder res; o->Apply ([&res] (const String& i) { if (not res.empty ()) { res += L", "; } res += i; }); m->PeekResponse ()->AddHeader (HTTP::HeaderName::kAllow, res.str ()); Execution::Throw (ClientErrorException (HTTP::StatusCodes::kMethodNotAllowed)); } else { DbgTrace (L"Router 404: (...url=%s)", Characters::ToString (m->GetRequestURL ()).c_str ()); Execution::Throw (ClientErrorException (HTTP::StatusCodes::kNotFound)); } } } optional<RequestHandler> Lookup_ (const Request& request, Sequence<String>* matches) const { String method = request.GetHTTPMethod (); URI url = request.GetURL (); String hostRelPath; try { hostRelPath = url.GetAbsPath<String> ().SubString (1); // According to https://tools.ietf.org/html/rfc2616#section-5.1.2 - the URI must be abs_path } catch (...) { Execution::Throw (ClientErrorException (HTTP::StatusCodes::kBadRequest, L"request URI requires an absolute path"sv)); } // We interpret routes as matching against a relative path from the root for (Route r : fRoutes_) { if (r.fVerbMatch_ and not method.Match (*r.fVerbMatch_)) { continue; } if (matches == nullptr) { if (r.fPathMatch_ and not hostRelPath.Match (*r.fPathMatch_)) { continue; } } else { if (r.fPathMatch_ and not hostRelPath.Match (*r.fPathMatch_, matches)) { continue; } } if (r.fRequestMatch_ and not(*r.fRequestMatch_) (request)) { continue; } return r.fHandler_; } return nullopt; } optional<Set<String>> GetAllowedMethodsForRequest_ (const Request& request) const { URI url = request.GetURL (); String hostRelPath; try { hostRelPath = url.GetAbsPath<String> ().SubString (1); // According to https://tools.ietf.org/html/rfc2616#section-5.1.2 - the URI must be abs_path } catch (...) { return nullopt; } static const Set<String> kMethods2Try_{HTTP::Methods::kGet, HTTP::Methods::kPut, HTTP::Methods::kOptions, HTTP::Methods::kDelete, HTTP::Methods::kPost}; Set<String> methods; for (String method : kMethods2Try_) { for (Route r : fRoutes_) { if (r.fVerbMatch_ and not method.Match (*r.fVerbMatch_)) { continue; } if (r.fPathMatch_ and not hostRelPath.Match (*r.fPathMatch_)) { continue; } if (r.fRequestMatch_ and not(*r.fRequestMatch_) (request)) { continue; } methods.Add (method); } } return methods.empty () ? nullopt : optional<Set<String>>{methods}; } const Sequence<Route> fRoutes_; // no need for synchronization cuz constant - just set on construction }; /* ******************************************************************************** *************************** WebServer::Router ********************************** ******************************************************************************** */ Router::Router (const Sequence<Route>& routes) : inherited (make_shared<Rep_> (routes)) { } optional<RequestHandler> Router::Lookup (const Request& request) const { return _GetRep<Rep_> ().Lookup_ (request, nullptr); } <|endoftext|>
<commit_before>#include "gum/Statistics.h" #include "gum/StatFPS.h" #include "gum/StatTag.h" #include "gum/GUM_GTxt.h" #include "gum/SymbolPool.h" #include "gum/Image.h" #include <logger.h> #include <glp_loop.h> #include <ps_3d.h> #include <sprite2/pre_defined.h> #include S2_MAT_HEADER #include <sprite2/StatDrawCall.h> #include <sprite2/StatPingPong.h> #include <sprite2/StatTopNodes.h> #include <sprite2/StatSymDraw.h> #include <sprite2/StatSymCount.h> #include <sprite2/StatSprCount.h> #include <sprite2/S2_Sprite.h> #include <sprite2/S2_Actor.h> #include <shaderlab/ShaderMgr.h> #include <shaderlab/Statistics.h> #include <shaderlab/StatDrawCall.h> #include <string> #include <time.h> namespace gum { SINGLETON_DEFINITION(Statistics); static const float FPS_SMOOTHING = 0.99f; Statistics::Statistics() : m_flags(0) , m_tpf(0) , m_tpf_smooth(0) , m_no_stat_begin(0) , m_no_stat_tot(0) , m_opt_enable(false) { memset(&m_mem, 0, sizeof(m_mem)); } void Statistics::EnableGraph(bool enable) { if (enable) { m_flags |= FLAG_PRINT_GRAPH; } else { m_flags &= ~FLAG_PRINT_GRAPH; } } void Statistics::EnableConsole(bool enable) { if (enable) { m_flags |= FLAG_PRINT_CONSOLE; } else { m_flags &= ~FLAG_PRINT_CONSOLE; } } void Statistics::EnableFile(bool enable) { if (enable == IsFileEnable()) { return; } if (enable) { m_flags |= FLAG_PRINT_FILE; #ifdef __ANDROID__ m_fout.open("/sdcard/lr_stat.bin", std::ofstream::out | std::ofstream::binary); #else m_fout.open("lr_stat.bin", std::ofstream::out | std::ofstream::binary); #endif // __ANDROID__ } else { m_flags &= ~FLAG_PRINT_FILE; m_fout.close(); } } bool Statistics::IsGraphEnable() const { return (m_flags & FLAG_PRINT_GRAPH) != 0; } bool Statistics::IsConsoleEnable() const { return (m_flags & FLAG_PRINT_CONSOLE) != 0; } bool Statistics::IsFileEnable() const { return (m_flags & FLAG_PRINT_FILE) != 0; } void Statistics::Update() { if (m_flags == 0) { return; } m_tpf = glp_get_dt(); m_tpf_smooth = (m_tpf_smooth * FPS_SMOOTHING) + m_tpf * (1.0f - FPS_SMOOTHING); } void Statistics::Print() { StatTag::Instance()->PrintScreen(); if (m_flags == 0) { return; } if (m_flags & FLAG_PRINT_GRAPH) { PrintScreen(); } if (m_flags & FLAG_PRINT_CONSOLE) { PrintConsole(); } if (m_flags & FLAG_PRINT_FILE) { PrintFile(); } } void Statistics::Reset() { if (m_flags == 0) { return; } m_tpf = 0; sl::Statistics::Instance()->Reset(); sl::StatDrawCall::Instance()->Reset(); s2::StatDrawCall::Instance()->Reset(); s2::StatPingPong::Instance()->Reset(); s2::StatTopNodes::Instance()->Reset(); s2::StatSymDraw::Instance()->Reset(); } void Statistics::Flush() { StatTag::Instance()->Flush(); } void Statistics::NoStatBegin() { m_no_stat_begin = glp_get_time(); } void Statistics::NoStatEnd() { m_no_stat_tot = (glp_get_time() - m_no_stat_begin); } void Statistics::OptEnable(bool enable) { m_opt_enable = enable; } void Statistics::SetMem(float tot, float lua) { m_mem.tot = tot; m_mem.lua = lua; } void Statistics::PrintScreen() const { sl::ShaderMgr* mgr = sl::ShaderMgr::Instance(); mgr->SetShader(sl::SPRITE2); static char buf[512]; const int w = 960; const int top = 280; S2_MAT mt; mt.Translate(0, top); sprintf(buf, "OPT: %s, emitter: %d", m_opt_enable ? "open" : "closed", p3d_emitter_count()); GTxt::Instance()->Draw(mt, buf, w); mt.Translate(0, -30); sprintf(buf, "FPS: %.1f, ms: %.1f, ex:%.1f", 1000.0f / m_tpf, m_tpf_smooth, m_no_stat_tot / 1000.0f); GTxt::Instance()->Draw(mt, buf, w); mt.Translate(0, -30); sprintf(buf, "MEM: tot %.1f, tex %.1f, lua %.1f", m_mem.tot, m_mem.tex, m_mem.lua); GTxt::Instance()->Draw(mt, buf, w); static std::string buf_str; buf_str.reserve(512); mt.Translate(0, -30); sl::Statistics::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); mt.Translate(0, -30); s2::StatDrawCall::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); mt.Translate(0, -40); s2::StatPingPong::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); mt.Translate(0, -50); sprintf(buf, "COUNT: sym %d, spr %d, actor %d, img %d", SymbolPool::Instance()->Count(), s2::Sprite::GetAllSprCount(), s2::Actor::GetAllActorCount(), ImageMgr::Instance()->Count()); GTxt::Instance()->Draw(mt, buf, w); mt.Translate(0, -30); s2::StatSymCount::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); mt.Translate(0, -30); s2::StatSprCount::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); mt.Translate(450, -100); s2::StatTopNodes::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); // mt.Translate(450, 180); // s2::StatSymbol::Instance()->Print(buf_str); // GTxt::Instance()->Draw(mt, buf_str, w); // buf_str.clear(); // mt.Translate(0, -230); // sl::StatDrawCall::Instance()->Print(buf_str); // GTxt::Instance()->Draw(mt, buf_str, w); // buf_str.clear(); mgr->FlushShader(); } void Statistics::PrintConsole() const { static const int PRINT_COUNT = 30; static int count = 0; ++count; if (count == PRINT_COUNT) { count = 0; sl::Statistics* stat = sl::Statistics::Instance(); int dc = stat->GetDrawCall(); int count = stat->GetVertices(); float fps_curr = StatFPS::Instance()->GetFPSCurr(); float curr_cost = 0; if (fps_curr != 0) { curr_cost = 1000.0f / fps_curr; } LOGI("fps %.1f, cost %.1f, dc %d, vertices %d, cost avg %.1f\n", 1000.0f / m_tpf_smooth, m_tpf_smooth, dc, count, curr_cost); } } void Statistics::PrintFile() const { sl::Statistics* sl_stat = sl::Statistics::Instance(); static char buf[512]; sprintf(buf, "timestamp %lu, cost %.1f, vertices %d, dc %d\n", time(NULL), m_tpf_smooth, sl_stat->GetVertices(), sl_stat->GetDrawCall()); m_fout << buf; // static std::string buf_str; // buf_str.reserve(1024); // s2::StatTopNodes::Instance()->Print(buf_str); // m_fout << buf_str; static const int FLUSH_COUNT = 100; static int count = 0; ++count; if (count == FLUSH_COUNT) { count = 0; m_fout.flush(); } } }<commit_msg>[FIXED] stat reset<commit_after>#include "gum/Statistics.h" #include "gum/StatFPS.h" #include "gum/StatTag.h" #include "gum/GUM_GTxt.h" #include "gum/SymbolPool.h" #include "gum/Image.h" #include <logger.h> #include <glp_loop.h> #include <ps_3d.h> #include <sprite2/pre_defined.h> #include S2_MAT_HEADER #include <sprite2/StatDrawCall.h> #include <sprite2/StatPingPong.h> #include <sprite2/StatTopNodes.h> #include <sprite2/StatSymDraw.h> #include <sprite2/StatSymCount.h> #include <sprite2/StatSprCount.h> #include <sprite2/S2_Sprite.h> #include <sprite2/S2_Actor.h> #include <shaderlab/ShaderMgr.h> #include <shaderlab/Statistics.h> #include <shaderlab/StatDrawCall.h> #include <string> #include <time.h> namespace gum { SINGLETON_DEFINITION(Statistics); static const float FPS_SMOOTHING = 0.99f; Statistics::Statistics() : m_flags(0) , m_tpf(0) , m_tpf_smooth(0) , m_no_stat_begin(0) , m_no_stat_tot(0) , m_opt_enable(false) { memset(&m_mem, 0, sizeof(m_mem)); } void Statistics::EnableGraph(bool enable) { if (enable) { m_flags |= FLAG_PRINT_GRAPH; } else { m_flags &= ~FLAG_PRINT_GRAPH; } } void Statistics::EnableConsole(bool enable) { if (enable) { m_flags |= FLAG_PRINT_CONSOLE; } else { m_flags &= ~FLAG_PRINT_CONSOLE; } } void Statistics::EnableFile(bool enable) { if (enable == IsFileEnable()) { return; } if (enable) { m_flags |= FLAG_PRINT_FILE; #ifdef __ANDROID__ m_fout.open("/sdcard/lr_stat.bin", std::ofstream::out | std::ofstream::binary); #else m_fout.open("lr_stat.bin", std::ofstream::out | std::ofstream::binary); #endif // __ANDROID__ } else { m_flags &= ~FLAG_PRINT_FILE; m_fout.close(); } } bool Statistics::IsGraphEnable() const { return (m_flags & FLAG_PRINT_GRAPH) != 0; } bool Statistics::IsConsoleEnable() const { return (m_flags & FLAG_PRINT_CONSOLE) != 0; } bool Statistics::IsFileEnable() const { return (m_flags & FLAG_PRINT_FILE) != 0; } void Statistics::Update() { if (m_flags == 0) { return; } m_tpf = glp_get_dt(); m_tpf_smooth = (m_tpf_smooth * FPS_SMOOTHING) + m_tpf * (1.0f - FPS_SMOOTHING); } void Statistics::Print() { StatTag::Instance()->PrintScreen(); if (m_flags == 0) { return; } if (m_flags & FLAG_PRINT_GRAPH) { PrintScreen(); } if (m_flags & FLAG_PRINT_CONSOLE) { PrintConsole(); } if (m_flags & FLAG_PRINT_FILE) { PrintFile(); } } void Statistics::Reset() { m_tpf = 0; sl::Statistics::Instance()->Reset(); sl::StatDrawCall::Instance()->Reset(); s2::StatDrawCall::Instance()->Reset(); s2::StatPingPong::Instance()->Reset(); s2::StatTopNodes::Instance()->Reset(); s2::StatSymDraw::Instance()->Reset(); } void Statistics::Flush() { StatTag::Instance()->Flush(); } void Statistics::NoStatBegin() { m_no_stat_begin = glp_get_time(); } void Statistics::NoStatEnd() { m_no_stat_tot = (glp_get_time() - m_no_stat_begin); } void Statistics::OptEnable(bool enable) { m_opt_enable = enable; } void Statistics::SetMem(float tot, float lua) { m_mem.tot = tot; m_mem.lua = lua; } void Statistics::PrintScreen() const { sl::ShaderMgr* mgr = sl::ShaderMgr::Instance(); mgr->SetShader(sl::SPRITE2); static char buf[512]; const int w = 960; const int top = 280; S2_MAT mt; mt.Translate(0, top); sprintf(buf, "OPT: %s, emitter: %d", m_opt_enable ? "open" : "closed", p3d_emitter_count()); GTxt::Instance()->Draw(mt, buf, w); mt.Translate(0, -30); sprintf(buf, "FPS: %.1f, ms: %.1f, ex:%.1f", 1000.0f / m_tpf, m_tpf_smooth, m_no_stat_tot / 1000.0f); GTxt::Instance()->Draw(mt, buf, w); mt.Translate(0, -30); sprintf(buf, "MEM: tot %.1f, tex %.1f, lua %.1f", m_mem.tot, m_mem.tex, m_mem.lua); GTxt::Instance()->Draw(mt, buf, w); static std::string buf_str; buf_str.reserve(512); mt.Translate(0, -30); sl::Statistics::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); mt.Translate(0, -30); s2::StatDrawCall::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); mt.Translate(0, -40); s2::StatPingPong::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); mt.Translate(0, -50); sprintf(buf, "COUNT: sym %d, spr %d, actor %d, img %d", SymbolPool::Instance()->Count(), s2::Sprite::GetAllSprCount(), s2::Actor::GetAllActorCount(), ImageMgr::Instance()->Count()); GTxt::Instance()->Draw(mt, buf, w); mt.Translate(0, -30); s2::StatSymCount::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); mt.Translate(0, -30); s2::StatSprCount::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); mt.Translate(450, -100); s2::StatTopNodes::Instance()->Print(buf_str); GTxt::Instance()->Draw(mt, buf_str, w); buf_str.clear(); // mt.Translate(450, 180); // s2::StatSymbol::Instance()->Print(buf_str); // GTxt::Instance()->Draw(mt, buf_str, w); // buf_str.clear(); // mt.Translate(0, -230); // sl::StatDrawCall::Instance()->Print(buf_str); // GTxt::Instance()->Draw(mt, buf_str, w); // buf_str.clear(); mgr->FlushShader(); } void Statistics::PrintConsole() const { static const int PRINT_COUNT = 30; static int count = 0; ++count; if (count == PRINT_COUNT) { count = 0; sl::Statistics* stat = sl::Statistics::Instance(); int dc = stat->GetDrawCall(); int count = stat->GetVertices(); float fps_curr = StatFPS::Instance()->GetFPSCurr(); float curr_cost = 0; if (fps_curr != 0) { curr_cost = 1000.0f / fps_curr; } LOGI("fps %.1f, cost %.1f, dc %d, vertices %d, cost avg %.1f\n", 1000.0f / m_tpf_smooth, m_tpf_smooth, dc, count, curr_cost); } } void Statistics::PrintFile() const { sl::Statistics* sl_stat = sl::Statistics::Instance(); static char buf[512]; sprintf(buf, "timestamp %lu, cost %.1f, vertices %d, dc %d\n", time(NULL), m_tpf_smooth, sl_stat->GetVertices(), sl_stat->GetDrawCall()); m_fout << buf; // static std::string buf_str; // buf_str.reserve(1024); // s2::StatTopNodes::Instance()->Print(buf_str); // m_fout << buf_str; static const int FLUSH_COUNT = 100; static int count = 0; ++count; if (count == FLUSH_COUNT) { count = 0; m_fout.flush(); } } }<|endoftext|>
<commit_before>#include <sstream> #include <sys/time.h> #include "marshal.h" using namespace std; namespace rpc { #ifdef PKT_SAMPLING int _pkt_sample_in[PKT_SAMPLE_SIZE]; int _pkt_sample_out[PKT_SAMPLE_SIZE]; void _pkt_sampling_report() { static size_t ratelimit_counter = 0; static int last_report_tm = 0; if (ratelimit_counter++ % 1024 == 0) { struct timeval now; gettimeofday(&now, NULL); if (now.tv_sec - last_report_tm >= 1) { { ostringstream ostr; for (int i = 0; i < PKT_SAMPLE_SIZE; i++) { ostr << " " << _pkt_sample_in[i]; } Log::info("PKT_SAMPLE_IN: %s", ostr.str().c_str()); } { ostringstream ostr; for (int i = 0; i < PKT_SAMPLE_SIZE; i++) { ostr << " " << _pkt_sample_out[i]; } Log::info("PKT_SAMPLE_OUT:%s", ostr.str().c_str()); } last_report_tm = now.tv_sec; } } } #endif // PKT_SAMPLING /** * 8kb minimum chunk size. * NOTE: this value directly affects how many read/write syscall will be issued. */ const int Chunk::min_size = 8192; Marshal1::Bookmark* Marshal1::set_bookmark(int size) { verify(write_counter_ == 0); // invariant: head of chunk list is not fully read (otherwise it's a waste of memory) assert(chunk_.empty() || !chunk_.front()->fully_read()); Bookmark* bmark = new Bookmark(); bmark->size_ = size; bmark->ptr_ = new char*[bmark->size_]; for (int i = 0; i < bmark->size_; i++) { if (chunk_.empty() || chunk_.back()->fully_written()) { chunk_.push_back(new Chunk); } bmark->ptr_[i] = chunk_.back()->set_bookmark(); } return bmark; } void Marshal1::write_bookmark(Bookmark* bmark, const void* ptr) { char* pc = (char *) ptr; verify(bmark != NULL && bmark->ptr_ != NULL && bmark->size_ >= 0); for (int i = 0; i < bmark->size_; i++) { *(bmark->ptr_[i]) = pc[i]; } } int Marshal1::write(const void* p, int n) { assert(chunk_.empty() || !chunk_.front()->fully_read()); if (chunk_.empty() || chunk_.back()->fully_written()) { chunk_.push_back(new Chunk(p, n)); } else { int n_write = chunk_.back()->write(p, n); // otherwise the above fully_written() will return true assert(n_write > 0); if (n_write < n) { const char* pc = (const char *) p; chunk_.push_back(new Chunk(pc + n_write, n - n_write)); } } write_counter_ += n; return n; } int Marshal1::read(void* p, int n) { assert(chunk_.empty() || !chunk_.front()->fully_read()); char* pc = (char *) p; int n_read = 0; while (!chunk_.empty() && n_read < n) { int r = chunk_.front()->read(pc + n_read, n - n_read); if (chunk_.front()->fully_read()) { // remove fully read chunks, avoid unnecessary mem usage delete chunk_.front(); chunk_.pop_front(); } if (r == 0) { // currently there's no content for us to read, so stop. break; } n_read += r; } verify(n_read <= n); assert(chunk_.empty() || !chunk_.front()->fully_read()); return n_read; } int Marshal1::peek(void* p, int n) const { assert(chunk_.empty() || !chunk_.front()->fully_read()); char* pc = (char *) p; int n_peek = 0; for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) { int r = (*it)->peek(pc + n_peek, n - n_peek); if (r == 0) { // no more data to peek, so stop break; } n_peek += r; if (n_peek == n) { // read enough data, so stop break; } } assert(n_peek <= n); assert(chunk_.empty() || !chunk_.front()->fully_read()); return n_peek; } int Marshal1::write_to_fd(int fd, const io_ratelimit& rate) { assert(chunk_.empty() || !chunk_.front()->fully_read()); if (rate.min_size > 0 || rate.interval > 0) { // rpc batching, check if should wait till next batch bool should_wait = true; if (rate.min_size > 0 && content_size_gt(rate.min_size)) { should_wait = false; } if (rate.interval > 0) { struct timeval tm; gettimeofday(&tm, NULL); double now = tm.tv_sec + tm.tv_usec / 1000.0 / 1000.0; if (should_wait && now - last_write_fd_tm_ > rate.interval) { should_wait = false; } if (should_wait == false) { last_write_fd_tm_ = now; } } if (should_wait) { return 0; } } int n_write = 0; while (!chunk_.empty()) { int r = chunk_.front()->write_to_fd(fd); if (chunk_.front()->fully_read()) { // remove useless chunks when they are fully read delete chunk_.front(); chunk_.pop_front(); } if (r <= 0) { break; } n_write += r; } assert(chunk_.empty() || !chunk_.front()->fully_read()); return n_write; } int Marshal1::read_from_marshal(Marshal1& m, int n /* =? */) { assert(chunk_.empty() || !chunk_.front()->fully_read()); assert(m.chunk_.empty() || !m.chunk_.front()->fully_read()); int n_read = 0; while (n_read < n) { if (m.chunk_.empty()) { // nothing more to read break; } if (chunk_.empty() || chunk_.back()->fully_written()) { int head_size = m.chunk_.front()->content_size(); if (head_size < n - n_read) { // speed up: directly transfer chunk pointer, avoid memory copying chunk_.push_back(m.chunk_.front()); m.chunk_.pop_front(); n_read += head_size; // skip read_from_chunk operations continue; } else { chunk_.push_back(new Chunk); } } int r = chunk_.back()->read_from_chunk(*m.chunk_.front(), n - n_read); if (m.chunk_.front()->fully_read()) { // remove useless chunks when they are fully read delete m.chunk_.front(); m.chunk_.pop_front(); } if (r == 0) { // no more data to read break; } n_read += r; } assert(chunk_.empty() || !chunk_.front()->fully_read()); assert(m.chunk_.empty() || !m.chunk_.front()->fully_read()); return n_read; } int Marshal1::read_from_fd(int fd) { assert(chunk_.empty() || !chunk_.front()->fully_read()); int n_read = 0; for (;;) { if (chunk_.empty() || chunk_.back()->fully_written()) { chunk_.push_back(new Chunk); } int r = chunk_.back()->read_from_fd(fd); if (r <= 0) { break; } n_read += r; } assert(chunk_.empty() || !chunk_.front()->fully_read()); return n_read; } bool Marshal1::content_size_gt(int size) const { int size_visited = 0; for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) { size_visited += (*it)->content_size(); if (size_visited > size) { return true; } } return size_visited > size; } size_t Marshal1::content_size() const { size_t size = 0; for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) { size += (*it)->content_size(); } return size; } } <commit_msg>FastMarshal::content_size and ~FastMarshal<commit_after>#include <sstream> #include <sys/time.h> #include "marshal.h" using namespace std; namespace rpc { #ifdef PKT_SAMPLING int _pkt_sample_in[PKT_SAMPLE_SIZE]; int _pkt_sample_out[PKT_SAMPLE_SIZE]; void _pkt_sampling_report() { static size_t ratelimit_counter = 0; static int last_report_tm = 0; if (ratelimit_counter++ % 1024 == 0) { struct timeval now; gettimeofday(&now, NULL); if (now.tv_sec - last_report_tm >= 1) { { ostringstream ostr; for (int i = 0; i < PKT_SAMPLE_SIZE; i++) { ostr << " " << _pkt_sample_in[i]; } Log::info("PKT_SAMPLE_IN: %s", ostr.str().c_str()); } { ostringstream ostr; for (int i = 0; i < PKT_SAMPLE_SIZE; i++) { ostr << " " << _pkt_sample_out[i]; } Log::info("PKT_SAMPLE_OUT:%s", ostr.str().c_str()); } last_report_tm = now.tv_sec; } } } #endif // PKT_SAMPLING FastMarshal::~FastMarshal() { chunk* chnk = head_; while (chnk != nullptr) { chunk* next = chnk->next; delete chnk; chnk = next; } } bool FastMarshal::content_size_gt(size_t n) const { assert(tail_ == nullptr || tail_->next == nullptr); size_t sz = 0; chunk* chnk = head_; while (chnk != nullptr) { sz += chnk->content_size(); if (sz > n) { return true; } chnk = chnk->next; } return sz > n; } size_t FastMarshal::content_size() const { assert(tail_ == nullptr || tail_->next == nullptr); size_t sz = 0; chunk* chnk = head_; while (chnk != nullptr) { sz += chnk->content_size(); chnk = chnk->next; } return sz; } /** * 8kb minimum chunk size. * NOTE: this value directly affects how many read/write syscall will be issued. */ const int Chunk::min_size = 8192; Marshal1::Bookmark* Marshal1::set_bookmark(int size) { verify(write_counter_ == 0); // invariant: head of chunk list is not fully read (otherwise it's a waste of memory) assert(chunk_.empty() || !chunk_.front()->fully_read()); Bookmark* bmark = new Bookmark(); bmark->size_ = size; bmark->ptr_ = new char*[bmark->size_]; for (int i = 0; i < bmark->size_; i++) { if (chunk_.empty() || chunk_.back()->fully_written()) { chunk_.push_back(new Chunk); } bmark->ptr_[i] = chunk_.back()->set_bookmark(); } return bmark; } void Marshal1::write_bookmark(Bookmark* bmark, const void* ptr) { char* pc = (char *) ptr; verify(bmark != NULL && bmark->ptr_ != NULL && bmark->size_ >= 0); for (int i = 0; i < bmark->size_; i++) { *(bmark->ptr_[i]) = pc[i]; } } int Marshal1::write(const void* p, int n) { assert(chunk_.empty() || !chunk_.front()->fully_read()); if (chunk_.empty() || chunk_.back()->fully_written()) { chunk_.push_back(new Chunk(p, n)); } else { int n_write = chunk_.back()->write(p, n); // otherwise the above fully_written() will return true assert(n_write > 0); if (n_write < n) { const char* pc = (const char *) p; chunk_.push_back(new Chunk(pc + n_write, n - n_write)); } } write_counter_ += n; return n; } int Marshal1::read(void* p, int n) { assert(chunk_.empty() || !chunk_.front()->fully_read()); char* pc = (char *) p; int n_read = 0; while (!chunk_.empty() && n_read < n) { int r = chunk_.front()->read(pc + n_read, n - n_read); if (chunk_.front()->fully_read()) { // remove fully read chunks, avoid unnecessary mem usage delete chunk_.front(); chunk_.pop_front(); } if (r == 0) { // currently there's no content for us to read, so stop. break; } n_read += r; } verify(n_read <= n); assert(chunk_.empty() || !chunk_.front()->fully_read()); return n_read; } int Marshal1::peek(void* p, int n) const { assert(chunk_.empty() || !chunk_.front()->fully_read()); char* pc = (char *) p; int n_peek = 0; for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) { int r = (*it)->peek(pc + n_peek, n - n_peek); if (r == 0) { // no more data to peek, so stop break; } n_peek += r; if (n_peek == n) { // read enough data, so stop break; } } assert(n_peek <= n); assert(chunk_.empty() || !chunk_.front()->fully_read()); return n_peek; } int Marshal1::write_to_fd(int fd, const io_ratelimit& rate) { assert(chunk_.empty() || !chunk_.front()->fully_read()); if (rate.min_size > 0 || rate.interval > 0) { // rpc batching, check if should wait till next batch bool should_wait = true; if (rate.min_size > 0 && content_size_gt(rate.min_size)) { should_wait = false; } if (rate.interval > 0) { struct timeval tm; gettimeofday(&tm, NULL); double now = tm.tv_sec + tm.tv_usec / 1000.0 / 1000.0; if (should_wait && now - last_write_fd_tm_ > rate.interval) { should_wait = false; } if (should_wait == false) { last_write_fd_tm_ = now; } } if (should_wait) { return 0; } } int n_write = 0; while (!chunk_.empty()) { int r = chunk_.front()->write_to_fd(fd); if (chunk_.front()->fully_read()) { // remove useless chunks when they are fully read delete chunk_.front(); chunk_.pop_front(); } if (r <= 0) { break; } n_write += r; } assert(chunk_.empty() || !chunk_.front()->fully_read()); return n_write; } int Marshal1::read_from_marshal(Marshal1& m, int n /* =? */) { assert(chunk_.empty() || !chunk_.front()->fully_read()); assert(m.chunk_.empty() || !m.chunk_.front()->fully_read()); int n_read = 0; while (n_read < n) { if (m.chunk_.empty()) { // nothing more to read break; } if (chunk_.empty() || chunk_.back()->fully_written()) { int head_size = m.chunk_.front()->content_size(); if (head_size < n - n_read) { // speed up: directly transfer chunk pointer, avoid memory copying chunk_.push_back(m.chunk_.front()); m.chunk_.pop_front(); n_read += head_size; // skip read_from_chunk operations continue; } else { chunk_.push_back(new Chunk); } } int r = chunk_.back()->read_from_chunk(*m.chunk_.front(), n - n_read); if (m.chunk_.front()->fully_read()) { // remove useless chunks when they are fully read delete m.chunk_.front(); m.chunk_.pop_front(); } if (r == 0) { // no more data to read break; } n_read += r; } assert(chunk_.empty() || !chunk_.front()->fully_read()); assert(m.chunk_.empty() || !m.chunk_.front()->fully_read()); return n_read; } int Marshal1::read_from_fd(int fd) { assert(chunk_.empty() || !chunk_.front()->fully_read()); int n_read = 0; for (;;) { if (chunk_.empty() || chunk_.back()->fully_written()) { chunk_.push_back(new Chunk); } int r = chunk_.back()->read_from_fd(fd); if (r <= 0) { break; } n_read += r; } assert(chunk_.empty() || !chunk_.front()->fully_read()); return n_read; } bool Marshal1::content_size_gt(int size) const { int size_visited = 0; for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) { size_visited += (*it)->content_size(); if (size_visited > size) { return true; } } return size_visited > size; } size_t Marshal1::content_size() const { size_t size = 0; for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) { size += (*it)->content_size(); } return size; } } <|endoftext|>
<commit_before>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE JPetParamBankTest #include <boost/test/unit_test.hpp> #define private public #include "../../JPetParamBank/JPetParamBank.h" #include <TFile.h> BOOST_AUTO_TEST_SUITE(ParamBankTS) BOOST_AUTO_TEST_CASE(DefaultConstructorTest) { JPetParamBank bank; BOOST_REQUIRE(bank.getScintillatorsSize() == 0); BOOST_REQUIRE(bank.getPMsSize() == 0); BOOST_REQUIRE(bank.getPMCalibsSize() == 0); BOOST_REQUIRE(bank.getFEBsSize() == 0); BOOST_REQUIRE(bank.getTRBsSize() == 0); BOOST_REQUIRE(bank.getTOMBChannelsSize() == 0); BOOST_REQUIRE(bank.getScintillators().GetEntries() == 0); BOOST_REQUIRE(bank.getPMs().GetEntries() == 0); BOOST_REQUIRE(bank.getPMCalibs().GetEntries() == 0); BOOST_REQUIRE(bank.getFEBs().GetEntries() == 0); BOOST_REQUIRE(bank.getTRBs().GetEntries() == 0); BOOST_REQUIRE(bank.getTOMBChannels().GetEntries() == 0); } BOOST_AUTO_TEST_CASE(AddingDummyElementsTest) { JPetParamBank bank; JPetScin scint(111, 8.f, 2.f, 4.f, 8.f); JPetPM pm(JPetPM::SideB, 222, 32, 64, std::make_pair(16.f, 32.f)); JPetPMCalib pmCalib(256, "JPetPMCalibTest", 2.f, 4.f, 8.f, 16.f, 32.f, 128, 512); JPetFEB feb(1, true, "testStatus", "descr", 1, 1); JPetTRB trb(333, 64, 128); JPetTOMBChannel TOMBChannel(32u); float epsilon = 0.0001f; bank.addScintillator(scint); bank.addPM(pm); bank.addPMCalib(pmCalib); bank.addFEB(feb); bank.addTRB(trb); bank.addTOMBChannel(TOMBChannel); BOOST_REQUIRE(bank.getScintillatorsSize() == 1); BOOST_REQUIRE(bank.getPMsSize() == 1); BOOST_REQUIRE(bank.getPMCalibsSize() == 1); BOOST_REQUIRE(bank.getFEBsSize() == 1); BOOST_REQUIRE(bank.getTRBsSize() == 1); BOOST_REQUIRE(bank.getTOMBChannelsSize() == 1); BOOST_REQUIRE(bank.getScintillators().GetEntries() == 1); BOOST_REQUIRE(bank.getPMs().GetEntries() == 1); BOOST_REQUIRE(bank.getPMCalibs().GetEntries() == 1); BOOST_REQUIRE(bank.getFEBs().GetEntries() == 1); BOOST_REQUIRE(bank.getTRBs().GetEntries() == 1); BOOST_REQUIRE(bank.getTOMBChannels().GetEntries() == 1); BOOST_REQUIRE(bank.getScintillator(0).getID() == 111); BOOST_CHECK_CLOSE(bank.getScintillator(0).getAttenLen(), 8.f, epsilon); struct JPetScin::ScinDimensions scin_dimensions(2.f, 4.f, 8.f); scin_dimensions = bank.getScintillator(0).getScinSize(); BOOST_CHECK_CLOSE(scin_dimensions.fLength, 2.f, epsilon); BOOST_CHECK_CLOSE(scin_dimensions.fHeight, 4.f, epsilon); BOOST_CHECK_CLOSE(scin_dimensions.fWidth, 8.f, epsilon); BOOST_REQUIRE(bank.getPM(0).getSide() == JPetPM::SideB); BOOST_REQUIRE(bank.getPM(0).getID() == 222); BOOST_REQUIRE(bank.getPM(0).getHVset() == 32); BOOST_REQUIRE(bank.getPM(0).getHVopt() == 64); BOOST_CHECK_CLOSE(bank.getPM(0).getHVgain(JPetPM::kFirst), 16.f, epsilon); BOOST_CHECK_CLOSE(bank.getPM(0).getHVgain(JPetPM::kSecond), 32.f, epsilon); std::pair<float, float> HVgain = bank.getPM(0).getHVgain(); BOOST_CHECK_CLOSE(HVgain.first, 16.f, epsilon); BOOST_CHECK_CLOSE(HVgain.second, 32.f, epsilon); BOOST_REQUIRE(bank.getPMCalib(0).GetId() == 256); BOOST_REQUIRE(bank.getPMCalib(0).GetNamePM() == "JPetPMCalibTest"); BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetOpthv(), 2.f, epsilon); BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetC2e_1(), 4.f, epsilon); BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetC2e_2(), 8.f, epsilon); BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetGainalpha(), 16.f, epsilon); BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetGainbeta(), 32.f, epsilon); BOOST_REQUIRE(bank.getPMCalib(0).GetPMCalibAssignment().id == 128); BOOST_REQUIRE(bank.getPMCalib(0).GetPMCalibAssignment().photomultiplier_id == 512); BOOST_REQUIRE(bank.getFEB(0).getID() == 1); BOOST_REQUIRE(bank.getFEB(0).isActive() == true); BOOST_REQUIRE(bank.getFEB(0).status() == "testStatus"); BOOST_REQUIRE(bank.getFEB(0).description() == "descr"); BOOST_REQUIRE(bank.getFEB(0).version() == 1); BOOST_REQUIRE(bank.getTRB(0).getID() == 333); BOOST_REQUIRE(bank.getTRB(0).getType() == 64); BOOST_REQUIRE(bank.getTRB(0).getChannel() == 128); BOOST_REQUIRE(bank.getTOMBChannel(0).getChannel() == 32u); } BOOST_AUTO_TEST_CASE(clearAllContainersTest) { JPetParamBank bank; JPetScin scint(111, 8.f, 2.f, 4.f, 8.f); JPetPM pm(JPetPM::SideB, 222, 32, 64, std::make_pair(16.f, 32.f)); JPetPMCalib pmCalib(256, "JPetPMCalibTest", 2.f, 4.f, 8.f, 16.f, 32.f, 128, 512); JPetFEB feb(1, true, "testStatus", "descr", 1, 1); JPetTRB trb(333, 64, 128); JPetTOMBChannel TOMBChannel(32u); bank.addScintillator(scint); bank.addPM(pm); bank.addPMCalib(pmCalib); bank.addFEB(feb); bank.addTRB(trb); bank.addTOMBChannel(TOMBChannel); BOOST_REQUIRE(bank.getScintillatorsSize() == 1); BOOST_REQUIRE(bank.getPMsSize() == 1); BOOST_REQUIRE(bank.getPMCalibsSize() == 1); BOOST_REQUIRE(bank.getFEBsSize() == 1); BOOST_REQUIRE(bank.getTRBsSize() == 1); BOOST_REQUIRE(bank.getTOMBChannelsSize() == 1); bank.clear(); BOOST_REQUIRE(bank.getScintillatorsSize() == 0); BOOST_REQUIRE(bank.getPMsSize() == 0); BOOST_REQUIRE(bank.getPMCalibsSize() == 0); BOOST_REQUIRE(bank.getFEBsSize() == 0); BOOST_REQUIRE(bank.getTRBsSize() == 0); BOOST_REQUIRE(bank.getTOMBChannelsSize() == 0); } BOOST_AUTO_TEST_CASE(getSizeTest) { JPetParamBank bank; JPetScin scint(111, 8.f, 2.f, 4.f, 8.f); JPetPM pm(JPetPM::SideB, 222, 32, 64, std::make_pair(16.f, 32.f)); JPetPMCalib pmCalib(256, "JPetPMCalibTest", 2.f, 4.f, 8.f, 16.f, 32.f, 128, 512); JPetFEB feb(1, true, "testStatus", "descr", 1, 1); JPetTRB trb(333, 64, 128); JPetTOMBChannel TOMBChannel(32u); bank.addScintillator(scint); bank.addPM(pm); bank.addPMCalib(pmCalib); bank.addFEB(feb); bank.addTRB(trb); bank.addTOMBChannel(TOMBChannel); BOOST_REQUIRE(bank.getSize(JPetParamBank::kScintillator) == 1); BOOST_REQUIRE(bank.getSize(JPetParamBank::kPM) == 1); BOOST_REQUIRE(bank.getSize(JPetParamBank::kPMCalib) == 1); BOOST_REQUIRE(bank.getSize(JPetParamBank::kFEB) == 1); BOOST_REQUIRE(bank.getSize(JPetParamBank::kTRB) == 1); BOOST_REQUIRE(bank.getSize(JPetParamBank::kTOMBChannel) == 1); } BOOST_AUTO_TEST_CASE( saving_reading_file ) { JPetParamBank bank; JPetScin scint1(1, 0, 0, 0, 0); JPetScin scint2(2, 0, 0, 0, 0); JPetPM pm1; JPetPM pm2; JPetPM pm3; JPetPM pm4; pm1.setID(1); pm2.setID(2); pm3.setID(3); pm4.setID(4); JPetPMCalib pmCalib(256, "JPetPMCalibTest", 2.f, 4.f, 8.f, 16.f, 32.f, 128, 512); pm1.setTRefScin(scint1); pm2.setTRefScin(scint1); pm3.setTRefScin(scint2); pm4.setTRefScin(scint2); JPetFEB feb(1, true, "testStatus", "descr", 1, 1); JPetTRB trb; bank.addPM(pm1); bank.addPM(pm2); bank.addPM(pm3); bank.addPM(pm4); bank.addPMCalib(pmCalib); bank.addScintillator(scint1); bank.addScintillator(scint2); bank.addTRB(trb); bank.addFEB(feb); for (int i = 0; i < 100; i++) { JPetTOMBChannel channel(i); bank.addTOMBChannel(channel); } BOOST_REQUIRE(bank.getPMCalibsSize() == 1); TFile file("test.root", "UPDATE"); file.cd(); file.WriteObject(&bank, "ParamBank"); file.Close(); bank.clear(); TFile file2("test.root", "READ"); JPetParamBank* pBank = static_cast<JPetParamBank*>(file2.Get("ParamBank")); JPetParamBank& bank2 = *pBank; BOOST_REQUIRE(bank2.getScintillatorsSize() == 2); BOOST_REQUIRE(bank2.getPMsSize() == 4); BOOST_REQUIRE(bank2.getPMCalibsSize() == 0); // TODO ERROR - should be 1 BOOST_REQUIRE(bank2.getFEBsSize() == 1); BOOST_REQUIRE(bank2.getTRBsSize() == 1); BOOST_REQUIRE(bank2.getScintillators().GetEntries() == 2); BOOST_REQUIRE(bank2.getPMs().GetEntries() == 4); BOOST_REQUIRE(bank2.getPMCalibs().GetEntries() == 0); // TODO ERROR - should be 1 BOOST_REQUIRE(bank2.getFEBs().GetEntries() == 1); BOOST_REQUIRE(bank2.getTRBs().GetEntries() == 1); // BOOST_REQUIRE(bank2.getPMCalib(0).GetId() == 256); // TODO ERROR BOOST_REQUIRE(bank2.getFEB(0).getID() == 1); BOOST_REQUIRE(bank2.getFEB(0).isActive()); BOOST_REQUIRE(bank2.getFEB(0).status() == "testStatus"); BOOST_REQUIRE(bank2.getFEB(0).description() == "descr"); BOOST_REQUIRE(bank2.getFEB(0).version() == 1); BOOST_REQUIRE(bank2.getPM(0).getScin().getID() == 1); BOOST_REQUIRE(bank2.getPM(1).getScin().getID() == 1); BOOST_REQUIRE(bank2.getPM(2).getScin().getID() == 2); BOOST_REQUIRE(bank2.getPM(3).getScin().getID() == 2); BOOST_REQUIRE(bank2.getScintillator(0).getID() == 1); BOOST_REQUIRE(bank2.getScintillator(1).getID() == 2); file2.Close(); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>fixed JPetParamBankTests<commit_after>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE JPetParamBankTest #include <boost/test/unit_test.hpp> #define private public #include "../../JPetParamBank/JPetParamBank.h" #include <TFile.h> BOOST_AUTO_TEST_SUITE(ParamBankTS) BOOST_AUTO_TEST_CASE(DefaultConstructorTest) { JPetParamBank bank; BOOST_REQUIRE(bank.getScintillatorsSize() == 0); BOOST_REQUIRE(bank.getPMsSize() == 0); BOOST_REQUIRE(bank.getPMCalibsSize() == 0); BOOST_REQUIRE(bank.getFEBsSize() == 0); BOOST_REQUIRE(bank.getTRBsSize() == 0); BOOST_REQUIRE(bank.getTOMBChannelsSize() == 0); BOOST_REQUIRE(bank.getScintillators().GetEntries() == 0); BOOST_REQUIRE(bank.getPMs().GetEntries() == 0); BOOST_REQUIRE(bank.getPMCalibs().GetEntries() == 0); BOOST_REQUIRE(bank.getFEBs().GetEntries() == 0); BOOST_REQUIRE(bank.getTRBs().GetEntries() == 0); BOOST_REQUIRE(bank.getTOMBChannels().GetEntries() == 0); } BOOST_AUTO_TEST_CASE(AddingDummyElementsTest) { JPetParamBank bank; JPetScin scint(111, 8.f, 2.f, 4.f, 8.f); JPetPM pm(JPetPM::SideB, 222, 32, 64, std::make_pair(16.f, 32.f)); JPetPMCalib pmCalib(256, "JPetPMCalibTest", 2.f, 4.f, 8.f, 16.f, 32.f, 128, 512); JPetFEB feb(1, true, "testStatus", "descr", 1, 1); JPetTRB trb(333, 64, 128); JPetTOMBChannel TOMBChannel(32u); float epsilon = 0.0001f; bank.addScintillator(scint); bank.addPM(pm); bank.addPMCalib(pmCalib); bank.addFEB(feb); bank.addTRB(trb); bank.addTOMBChannel(TOMBChannel); BOOST_REQUIRE(bank.getScintillatorsSize() == 1); BOOST_REQUIRE(bank.getPMsSize() == 1); BOOST_REQUIRE(bank.getPMCalibsSize() == 1); BOOST_REQUIRE(bank.getFEBsSize() == 1); BOOST_REQUIRE(bank.getTRBsSize() == 1); BOOST_REQUIRE(bank.getTOMBChannelsSize() == 1); BOOST_REQUIRE(bank.getScintillators().GetEntries() == 1); BOOST_REQUIRE(bank.getPMs().GetEntries() == 1); BOOST_REQUIRE(bank.getPMCalibs().GetEntries() == 1); BOOST_REQUIRE(bank.getFEBs().GetEntries() == 1); BOOST_REQUIRE(bank.getTRBs().GetEntries() == 1); BOOST_REQUIRE(bank.getTOMBChannels().GetEntries() == 1); BOOST_REQUIRE(bank.getScintillator(0).getID() == 111); BOOST_CHECK_CLOSE(bank.getScintillator(0).getAttenLen(), 8.f, epsilon); struct JPetScin::ScinDimensions scin_dimensions(2.f, 4.f, 8.f); scin_dimensions = bank.getScintillator(0).getScinSize(); BOOST_CHECK_CLOSE(scin_dimensions.fLength, 2.f, epsilon); BOOST_CHECK_CLOSE(scin_dimensions.fHeight, 4.f, epsilon); BOOST_CHECK_CLOSE(scin_dimensions.fWidth, 8.f, epsilon); BOOST_REQUIRE(bank.getPM(0).getSide() == JPetPM::SideB); BOOST_REQUIRE(bank.getPM(0).getID() == 222); BOOST_REQUIRE(bank.getPM(0).getHVset() == 32); BOOST_REQUIRE(bank.getPM(0).getHVopt() == 64); BOOST_CHECK_CLOSE(bank.getPM(0).getHVgain(JPetPM::kFirst), 16.f, epsilon); BOOST_CHECK_CLOSE(bank.getPM(0).getHVgain(JPetPM::kSecond), 32.f, epsilon); std::pair<float, float> HVgain = bank.getPM(0).getHVgain(); BOOST_CHECK_CLOSE(HVgain.first, 16.f, epsilon); BOOST_CHECK_CLOSE(HVgain.second, 32.f, epsilon); BOOST_REQUIRE(bank.getPMCalib(0).GetId() == 256); BOOST_REQUIRE(bank.getPMCalib(0).GetNamePM() == "JPetPMCalibTest"); BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetOpthv(), 2.f, epsilon); BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetC2e_1(), 4.f, epsilon); BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetC2e_2(), 8.f, epsilon); BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetGainalpha(), 16.f, epsilon); BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetGainbeta(), 32.f, epsilon); BOOST_REQUIRE(bank.getPMCalib(0).GetPMCalibAssignment().id == 128); BOOST_REQUIRE(bank.getPMCalib(0).GetPMCalibAssignment().photomultiplier_id == 512); BOOST_REQUIRE(bank.getFEB(0).getID() == 1); BOOST_REQUIRE(bank.getFEB(0).isActive() == true); BOOST_REQUIRE(bank.getFEB(0).status() == "testStatus"); BOOST_REQUIRE(bank.getFEB(0).description() == "descr"); BOOST_REQUIRE(bank.getFEB(0).version() == 1); BOOST_REQUIRE(bank.getTRB(0).getID() == 333); BOOST_REQUIRE(bank.getTRB(0).getType() == 64); BOOST_REQUIRE(bank.getTRB(0).getChannel() == 128); BOOST_REQUIRE(bank.getTOMBChannel(0).getChannel() == 32u); } BOOST_AUTO_TEST_CASE(clearAllContainersTest) { JPetParamBank bank; JPetScin scint(111, 8.f, 2.f, 4.f, 8.f); JPetPM pm(JPetPM::SideB, 222, 32, 64, std::make_pair(16.f, 32.f)); JPetPMCalib pmCalib(256, "JPetPMCalibTest", 2.f, 4.f, 8.f, 16.f, 32.f, 128, 512); JPetFEB feb(1, true, "testStatus", "descr", 1, 1); JPetTRB trb(333, 64, 128); JPetTOMBChannel TOMBChannel(32u); bank.addScintillator(scint); bank.addPM(pm); bank.addPMCalib(pmCalib); bank.addFEB(feb); bank.addTRB(trb); bank.addTOMBChannel(TOMBChannel); BOOST_REQUIRE(bank.getScintillatorsSize() == 1); BOOST_REQUIRE(bank.getPMsSize() == 1); BOOST_REQUIRE(bank.getPMCalibsSize() == 1); BOOST_REQUIRE(bank.getFEBsSize() == 1); BOOST_REQUIRE(bank.getTRBsSize() == 1); BOOST_REQUIRE(bank.getTOMBChannelsSize() == 1); bank.clear(); BOOST_REQUIRE(bank.getScintillatorsSize() == 0); BOOST_REQUIRE(bank.getPMsSize() == 0); BOOST_REQUIRE(bank.getPMCalibsSize() == 0); BOOST_REQUIRE(bank.getFEBsSize() == 0); BOOST_REQUIRE(bank.getTRBsSize() == 0); BOOST_REQUIRE(bank.getTOMBChannelsSize() == 0); } BOOST_AUTO_TEST_CASE(getSizeTest) { JPetParamBank bank; JPetScin scint(111, 8.f, 2.f, 4.f, 8.f); JPetPM pm(JPetPM::SideB, 222, 32, 64, std::make_pair(16.f, 32.f)); JPetPMCalib pmCalib(256, "JPetPMCalibTest", 2.f, 4.f, 8.f, 16.f, 32.f, 128, 512); JPetFEB feb(1, true, "testStatus", "descr", 1, 1); JPetTRB trb(333, 64, 128); JPetTOMBChannel TOMBChannel(32u); bank.addScintillator(scint); bank.addPM(pm); bank.addPMCalib(pmCalib); bank.addFEB(feb); bank.addTRB(trb); bank.addTOMBChannel(TOMBChannel); BOOST_REQUIRE(bank.getSize(JPetParamBank::kScintillator) == 1); BOOST_REQUIRE(bank.getSize(JPetParamBank::kPM) == 1); BOOST_REQUIRE(bank.getSize(JPetParamBank::kPMCalib) == 1); BOOST_REQUIRE(bank.getSize(JPetParamBank::kFEB) == 1); BOOST_REQUIRE(bank.getSize(JPetParamBank::kTRB) == 1); BOOST_REQUIRE(bank.getSize(JPetParamBank::kTOMBChannel) == 1); } BOOST_AUTO_TEST_CASE( saving_reading_file ) { JPetParamBank bank; JPetScin scint1(1, 0, 0, 0, 0); JPetScin scint2(2, 0, 0, 0, 0); JPetPM pm1; JPetPM pm2; JPetPM pm3; JPetPM pm4; pm1.setID(1); pm2.setID(2); pm3.setID(3); pm4.setID(4); JPetPMCalib pmCalib(256, "JPetPMCalibTest", 2.f, 4.f, 8.f, 16.f, 32.f, 128, 512); pm1.setScin(scint1); pm2.setScin(scint1); pm3.setScin(scint2); pm4.setScin(scint2); JPetFEB feb(1, true, "testStatus", "descr", 1, 1); JPetTRB trb; bank.addPM(pm1); bank.addPM(pm2); bank.addPM(pm3); bank.addPM(pm4); bank.addPMCalib(pmCalib); bank.addScintillator(scint1); bank.addScintillator(scint2); bank.addTRB(trb); bank.addFEB(feb); for (int i = 0; i < 100; i++) { JPetTOMBChannel channel(i); bank.addTOMBChannel(channel); } BOOST_REQUIRE(bank.getPMCalibsSize() == 1); TFile file("test.root", "UPDATE"); file.cd(); file.WriteObject(&bank, "ParamBank"); file.Close(); bank.clear(); TFile file2("test.root", "READ"); JPetParamBank* pBank = static_cast<JPetParamBank*>(file2.Get("ParamBank")); JPetParamBank& bank2 = *pBank; BOOST_REQUIRE(bank2.getScintillatorsSize() == 2); BOOST_REQUIRE(bank2.getPMsSize() == 4); BOOST_REQUIRE(bank2.getPMCalibsSize() == 0); // TODO ERROR - should be 1 BOOST_REQUIRE(bank2.getFEBsSize() == 1); BOOST_REQUIRE(bank2.getTRBsSize() == 1); BOOST_REQUIRE(bank2.getScintillators().GetEntries() == 2); BOOST_REQUIRE(bank2.getPMs().GetEntries() == 4); BOOST_REQUIRE(bank2.getPMCalibs().GetEntries() == 0); // TODO ERROR - should be 1 BOOST_REQUIRE(bank2.getFEBs().GetEntries() == 1); BOOST_REQUIRE(bank2.getTRBs().GetEntries() == 1); // BOOST_REQUIRE(bank2.getPMCalib(0).GetId() == 256); // TODO ERROR BOOST_REQUIRE(bank2.getFEB(0).getID() == 1); BOOST_REQUIRE(bank2.getFEB(0).isActive()); BOOST_REQUIRE(bank2.getFEB(0).status() == "testStatus"); BOOST_REQUIRE(bank2.getFEB(0).description() == "descr"); BOOST_REQUIRE(bank2.getFEB(0).version() == 1); BOOST_REQUIRE(bank2.getPM(0).getScin().getID() == 1); BOOST_REQUIRE(bank2.getPM(1).getScin().getID() == 1); BOOST_REQUIRE(bank2.getPM(2).getScin().getID() == 2); BOOST_REQUIRE(bank2.getPM(3).getScin().getID() == 2); BOOST_REQUIRE(bank2.getScintillator(0).getID() == 1); BOOST_REQUIRE(bank2.getScintillator(1).getID() == 2); file2.Close(); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <ncurses.h> #include <csignal> #include <cstdlib> #include "signals.hh" extern "C" { static void myexit(int i) { endwin(); SIG_DFL(i); } } namespace vick { void setup_signal_handling() { signal(SIGABRT, myexit); signal(SIGFPE, myexit); signal(SIGILL, myexit); signal(SIGINT, myexit); signal(SIGSEGV, myexit); signal(SIGTERM, myexit); } } <commit_msg>Use `*.h` headers rather than `c*`<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <ncurses.h> #include <signal.h> #include <stdlib.h> #include "signals.hh" extern "C" { static void myexit(int i) { endwin(); SIG_DFL(i); } } namespace vick { void setup_signal_handling() { signal(SIGABRT, myexit); signal(SIGFPE, myexit); signal(SIGILL, myexit); signal(SIGINT, myexit); signal(SIGSEGV, myexit); signal(SIGTERM, myexit); } } <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief RX65N ダイレクト・デジタル・シンセサイザ @n マイコン内臓12ビットD/A変換を使って、波形を生成するガジェット @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2019 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #define CASH_KFONT #include "common/renesas.hpp" #include "common/cmt_io.hpp" #include "common/fixed_fifo.hpp" #include "common/sci_io.hpp" #include "common/sci_i2c_io.hpp" #include "common/format.hpp" #include "common/command.hpp" #include "common/spi_io2.hpp" #include "ff13c/mmc_io.hpp" #include "common/tpu_io.hpp" #include "common/qspi_io.hpp" #include "graphics/font8x16.hpp" #include "graphics/graphics.hpp" #include "graphics/filer.hpp" #include "graphics/kfont.hpp" #include "graphics/font.hpp" #include "chip/FT5206.hpp" namespace { typedef device::PORT<device::PORT7, device::bitpos::B0> LED; typedef device::system_io<12000000> SYSTEM_IO; typedef device::cmt_io<device::CMT0, utils::null_task> CMT; CMT cmt_; typedef utils::fixed_fifo<char, 512> RECV_BUFF; typedef utils::fixed_fifo<char, 1024> SEND_BUFF; typedef device::sci_io<device::SCI9, RECV_BUFF, SEND_BUFF> SCI; SCI sci_; // カード電源制御は使わないので、「device::NULL_PORT」を指定する。 // typedef device::PORT<device::PORT6, device::bitpos::B4> SDC_POWER; typedef device::NULL_PORT SDC_POWER; #ifdef SDHI_IF // RX65N Envision Kit の SDHI ポートは、候補3になっている typedef fatfs::sdhi_io<device::SDHI, SDC_POWER, device::port_map::option::THIRD> SDHI; SDHI sdh_; #else // Soft SDC 用 SPI 定義(SPI) typedef device::PORT<device::PORT2, device::bitpos::B2> MISO; // DAT0 typedef device::PORT<device::PORT2, device::bitpos::B0> MOSI; // CMD typedef device::PORT<device::PORT2, device::bitpos::B1> SPCK; // CLK typedef device::spi_io2<MISO, MOSI, SPCK> SPI; ///< Soft SPI 定義 SPI spi_; typedef device::PORT<device::PORT1, device::bitpos::B7> SDC_SELECT; // DAT3 カード選択信号 typedef device::PORT<device::PORT2, device::bitpos::B5> SDC_DETECT; // CD カード検出 typedef fatfs::mmc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> MMC; // ハードウェアー定義 MMC sdh_(spi_, 20000000); #endif typedef device::PORT<device::PORT6, device::bitpos::B3> LCD_DISP; typedef device::PORT<device::PORT6, device::bitpos::B6> LCD_LIGHT; static const int16_t LCD_X = 480; static const int16_t LCD_Y = 272; static void* LCD_ORG = reinterpret_cast<void*>(0x00000100); static const auto PIXT = graphics::pixel::TYPE::RGB565; typedef device::glcdc_io<device::GLCDC, LCD_X, LCD_Y, PIXT> GLCDC_IO; GLCDC_IO glcdc_io_(nullptr, LCD_ORG); typedef graphics::font8x16 AFONT; AFONT afont_; #ifdef CASH_KFONT typedef graphics::kfont<16, 16, 64> KFONT; #else typedef graphics::kfont<16, 16> KFONT; #endif KFONT kfont_; typedef graphics::font<AFONT, KFONT> FONT; FONT font_(afont_, kfont_); // typedef device::drw2d_mgr<GLCDC_IO, FONT> RENDER; typedef graphics::render<GLCDC_IO, FONT> RENDER; RENDER render_(glcdc_io_, font_); // FT5206, SCI6 簡易 I2C 定義 typedef device::PORT<device::PORT0, device::bitpos::B7> FT5206_RESET; typedef utils::fixed_fifo<uint8_t, 64> RB6; typedef utils::fixed_fifo<uint8_t, 64> SB6; typedef device::sci_i2c_io<device::SCI6, RB6, SB6, device::port_map::option::FIRST_I2C> FT5206_I2C; FT5206_I2C ft5206_i2c_; typedef chip::FT5206<FT5206_I2C> FT5206; FT5206 ft5206_(ft5206_i2c_); utils::command<256> cmd_; void update_led_() { static uint8_t n = 0; ++n; if(n >= 30) { n = 0; } if(n < 10) { LED::P = 0; } else { LED::P = 1; } } void command_() { if(!cmd_.service()) { return; } uint8_t cmdn = cmd_.get_words(); if(cmdn >= 1) { bool f = false; if(cmd_.cmp_word(0, "dir")) { // dir [xxx] if(sdh_.get_mount()) { if(cmdn >= 2) { char tmp[128]; cmd_.get_word(1, tmp, sizeof(tmp)); utils::file_io::dir(tmp); } else { utils::file_io::dir(""); } } f = true; } else if(cmd_.cmp_word(0, "cd")) { // cd [xxx] if(sdh_.get_mount()) { if(cmdn >= 2) { char tmp[128]; cmd_.get_word(1, tmp, sizeof(tmp)); utils::file_io::cd(tmp); } else { utils::file_io::cd("/"); } } f = true; } else if(cmd_.cmp_word(0, "pwd")) { // pwd char tmp[FF_MAX_LFN + 1]; if(!utils::file_io::pwd(tmp, sizeof(tmp))) { utils::format("%s\n") % tmp; } f = true; } else if(cmd_.cmp_word(0, "help")) { utils::format(" dir [path]\n"); utils::format(" cd [path]\n"); utils::format(" pwd\n"); f = true; } if(!f) { char tmp[128]; if(cmd_.get_word(0, tmp, sizeof(tmp))) { utils::format("Command error: '%s'\n") % tmp; } } } } } extern "C" { void sci_putch(char ch) { sci_.putch(ch); } void sci_puts(const char* str) { sci_.puts(str); } char sci_getch(void) { return sci_.getch(); } uint16_t sci_length() { return sci_.recv_length(); } DSTATUS disk_initialize(BYTE drv) { return sdh_.disk_initialize(drv); } DSTATUS disk_status(BYTE drv) { return sdh_.disk_status(drv); } DRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) { return sdh_.disk_read(drv, buff, sector, count); } DRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) { return sdh_.disk_write(drv, buff, sector, count); } DRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) { return sdh_.disk_ioctl(drv, ctrl, buff); } DWORD get_fattime(void) { time_t t = 0; /// rtc_.get_time(t); return utils::str::get_fattime(t); } } int main(int argc, char** argv); int main(int argc, char** argv) { SYSTEM_IO::setup_system_clock(); { // SCI 設定 static const uint8_t sci_level = 2; sci_.start(115200, sci_level); } { // SD カード・クラスの初期化 sdh_.start(); } utils::format("RTK5RX65N Start for Direct Digital Synthsyzer\n"); cmd_.set_prompt("# "); { // GLCDC の初期化 LCD_DISP::DIR = 1; LCD_LIGHT::DIR = 1; LCD_DISP::P = 0; // DISP Disable LCD_LIGHT::P = 0; // BackLight Disable (No PWM) if(glcdc_io_.start()) { utils::format("Start GLCDC\n"); LCD_DISP::P = 1; // DISP Enable LCD_LIGHT::P = 1; // BackLight Enable (No PWM) if(!glcdc_io_.control(GLCDC_IO::CONTROL_CMD::START_DISPLAY)) { utils::format("GLCDC ctrl fail...\n"); } } else { utils::format("GLCDC Fail\n"); } } { // FT5206 touch screen controller FT5206::reset<FT5206_RESET>(); uint8_t intr_lvl = 1; if(!ft5206_i2c_.start(FT5206_I2C::SPEED::STANDARD, intr_lvl)) { utils::format("FT5206 I2C Start Fail...\n"); } if(!ft5206_.start()) { utils::format("FT5206 Start Fail...\n"); } } LED::DIR = 1; // タッチパネルの安定待ち while(1) { render_.sync_frame(); ft5206_.update(); sdh_.service(); command_(); update_led_(); } } <commit_msg>Update: clean up shell class<commit_after>//=====================================================================// /*! @file @brief RX65N ダイレクト・デジタル・シンセサイザ @n マイコン内臓12ビットD/A変換を使って、波形を生成するガジェット @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2019 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #define CASH_KFONT #include "common/renesas.hpp" #include "common/cmt_io.hpp" #include "common/fixed_fifo.hpp" #include "common/sci_io.hpp" #include "common/sci_i2c_io.hpp" #include "common/format.hpp" #include "common/command.hpp" #include "common/shell.hpp" #include "common/spi_io2.hpp" #include "common/tpu_io.hpp" #include "common/qspi_io.hpp" #include "graphics/font8x16.hpp" #include "graphics/graphics.hpp" #include "graphics/filer.hpp" #include "graphics/kfont.hpp" #include "graphics/font.hpp" #include "chip/FT5206.hpp" namespace { typedef device::PORT<device::PORT7, device::bitpos::B0> LED; typedef device::system_io<12000000> SYSTEM_IO; typedef device::cmt_io<device::CMT0, utils::null_task> CMT; CMT cmt_; typedef utils::fixed_fifo<char, 512> RECV_BUFF; typedef utils::fixed_fifo<char, 1024> SEND_BUFF; typedef device::sci_io<device::SCI9, RECV_BUFF, SEND_BUFF> SCI; SCI sci_; // カード電源制御は使わないので、「device::NULL_PORT」を指定する。 // typedef device::PORT<device::PORT6, device::bitpos::B4> SDC_POWER; typedef device::NULL_PORT SDC_POWER; #ifdef SDHI_IF // RX65N Envision Kit の SDHI ポートは、候補3になっている typedef fatfs::sdhi_io<device::SDHI, SDC_POWER, device::port_map::option::THIRD> SDHI; SDHI sdh_; #else // Soft SDC 用 SPI 定義(SPI) typedef device::PORT<device::PORT2, device::bitpos::B2> MISO; // DAT0 typedef device::PORT<device::PORT2, device::bitpos::B0> MOSI; // CMD typedef device::PORT<device::PORT2, device::bitpos::B1> SPCK; // CLK typedef device::spi_io2<MISO, MOSI, SPCK> SPI; ///< Soft SPI 定義 SPI spi_; typedef device::PORT<device::PORT1, device::bitpos::B7> SDC_SELECT; // DAT3 カード選択信号 typedef device::PORT<device::PORT2, device::bitpos::B5> SDC_DETECT; // CD カード検出 typedef fatfs::mmc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> MMC; // ハードウェアー定義 MMC sdh_(spi_, 20000000); #endif typedef device::PORT<device::PORT6, device::bitpos::B3> LCD_DISP; typedef device::PORT<device::PORT6, device::bitpos::B6> LCD_LIGHT; static const int16_t LCD_X = 480; static const int16_t LCD_Y = 272; static void* LCD_ORG = reinterpret_cast<void*>(0x00000100); static const auto PIXT = graphics::pixel::TYPE::RGB565; typedef device::glcdc_io<device::GLCDC, LCD_X, LCD_Y, PIXT> GLCDC_IO; GLCDC_IO glcdc_io_(nullptr, LCD_ORG); typedef graphics::font8x16 AFONT; AFONT afont_; #ifdef CASH_KFONT typedef graphics::kfont<16, 16, 64> KFONT; #else typedef graphics::kfont<16, 16> KFONT; #endif KFONT kfont_; typedef graphics::font<AFONT, KFONT> FONT; FONT font_(afont_, kfont_); // typedef device::drw2d_mgr<GLCDC_IO, FONT> RENDER; typedef graphics::render<GLCDC_IO, FONT> RENDER; RENDER render_(glcdc_io_, font_); // FT5206, SCI6 簡易 I2C 定義 typedef device::PORT<device::PORT0, device::bitpos::B7> FT5206_RESET; typedef utils::fixed_fifo<uint8_t, 64> RB6; typedef utils::fixed_fifo<uint8_t, 64> SB6; typedef device::sci_i2c_io<device::SCI6, RB6, SB6, device::port_map::option::FIRST_I2C> FT5206_I2C; FT5206_I2C ft5206_i2c_; typedef chip::FT5206<FT5206_I2C> FT5206; FT5206 ft5206_(ft5206_i2c_); typedef utils::command<256> CMD; CMD cmd_; typedef utils::shell<CMD> SHELL; SHELL shell_(cmd_); void update_led_() { static uint8_t n = 0; ++n; if(n >= 30) { n = 0; } if(n < 10) { LED::P = 0; } else { LED::P = 1; } } void command_() { if(!cmd_.service()) { return; } if(shell_.analize()) { return; } if(cmd_.cmp_word(0, "help")) { shell_.help(); } else { utils::format("Command error: '%s'\n") % cmd_.get_command(); } } } extern "C" { void sci_putch(char ch) { sci_.putch(ch); } void sci_puts(const char* str) { sci_.puts(str); } char sci_getch(void) { return sci_.getch(); } uint16_t sci_length() { return sci_.recv_length(); } DSTATUS disk_initialize(BYTE drv) { return sdh_.disk_initialize(drv); } DSTATUS disk_status(BYTE drv) { return sdh_.disk_status(drv); } DRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) { return sdh_.disk_read(drv, buff, sector, count); } DRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) { return sdh_.disk_write(drv, buff, sector, count); } DRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) { return sdh_.disk_ioctl(drv, ctrl, buff); } DWORD get_fattime(void) { time_t t = 0; /// rtc_.get_time(t); return utils::str::get_fattime(t); } } int main(int argc, char** argv); int main(int argc, char** argv) { SYSTEM_IO::setup_system_clock(); { // SCI 設定 static const uint8_t sci_level = 2; sci_.start(115200, sci_level); } { // SD カード・クラスの初期化 sdh_.start(); } utils::format("RTK5RX65N Start for Direct Digital Synthsyzer\n"); cmd_.set_prompt("# "); { // GLCDC の初期化 LCD_DISP::DIR = 1; LCD_LIGHT::DIR = 1; LCD_DISP::P = 0; // DISP Disable LCD_LIGHT::P = 0; // BackLight Disable (No PWM) if(glcdc_io_.start()) { utils::format("Start GLCDC\n"); LCD_DISP::P = 1; // DISP Enable LCD_LIGHT::P = 1; // BackLight Enable (No PWM) if(!glcdc_io_.control(GLCDC_IO::CONTROL_CMD::START_DISPLAY)) { utils::format("GLCDC ctrl fail...\n"); } } else { utils::format("GLCDC Fail\n"); } } { // FT5206 touch screen controller FT5206::reset<FT5206_RESET>(); uint8_t intr_lvl = 1; if(!ft5206_i2c_.start(FT5206_I2C::SPEED::STANDARD, intr_lvl)) { utils::format("FT5206 I2C Start Fail...\n"); } if(!ft5206_.start()) { utils::format("FT5206 Start Fail...\n"); } } LED::DIR = 1; // タッチパネルの安定待ち while(1) { render_.sync_frame(); ft5206_.update(); sdh_.service(); command_(); update_led_(); } } <|endoftext|>
<commit_before>#include "RenderCameraSystem.hpp" #include <Components/CameraComponent.hpp> #include <Components/SpotLight.hh> #include <Components/DirectionalLightComponent.hh> #include <Components/Light.hh> #include <Core/Engine.hh> #include <Core/AScene.hh> #include <glm/gtc/matrix_transform.hpp> #include <BFC/BFCLinkTracker.hpp> #include <BFC/BFCBlockManagerFactory.hpp> #include <BFC/BFCCullableObject.hpp> #include <Graphic/DRBCameraDrawableList.hpp> #include <Graphic/BFCCullableTypes.hpp> #include <Threads/ThreadManager.hpp> #include <Threads/RenderThread.hpp> #include <Threads/MainThread.hpp> #include <Threads/Commands/ToRenderCommands.hpp> #include "Utils/Frustum.hh" namespace AGE { RenderCameraSystem::RenderCameraSystem(AScene *scene) : System(std::move(scene)), _cameras(std::move(scene)), _spotLights(std::move(scene)), _directionnalLights(std::move(scene)), _pointLights(std::move(scene)) { _name = "Camera system"; } bool RenderCameraSystem::initialize() { _cameras.requireComponent<CameraComponent>(); _spotLights.requireComponent<SpotLightComponent>(); _directionnalLights.requireComponent<DirectionalLightComponent>(); _pointLights.requireComponent<PointLightComponent>(); return (true); } void RenderCameraSystem::updateBegin(float time) { } void RenderCameraSystem::mainUpdate(float time) { _scene->getBfcLinkTracker()->reset(); // check if the render thread does not already have stuff to draw if (GetMainThread()->isRenderFrame() == false) { return; } std::list<std::shared_ptr<DRBSpotLightDrawableList>> spotLightList; std::list<std::shared_ptr<DRBData>> pointLightList; for (auto spotEntity : _spotLights.getCollection()) { auto spot = spotEntity->getComponent<SpotLightComponent>(); auto spotDrawableList = std::make_shared<DRBSpotLightDrawableList>(); spotDrawableList->spotLight = spot->getCullableHandle().getPtr()->getDatas(); // WARNINNNNNNNNNNNG // Le calcul n'est pas bon !!!! // Paul, fais le STP, merci Frustum spotlightFrustum; spotlightFrustum.setMatrix(glm::perspective(spot->getCutOff() / 2.0f, spot->getExponent(), 0.1f, 1000.0f)* glm::inverse(spotEntity->getLink().getGlobalTransform())); glm::vec4 a = spotEntity->getLink().getGlobalTransform() * glm::vec4(-1, -1, 0, 1); glm::vec4 b = spotEntity->getLink().getGlobalTransform() * glm::vec4(-1, 1, 0, 1); glm::vec4 c = spotEntity->getLink().getGlobalTransform() * glm::vec4(1, 1, 0, 1); glm::vec4 d = spotEntity->getLink().getGlobalTransform() * glm::vec4(1, -1, 0, 1); AGE::GetRenderThread()->getQueue()->emplaceCommand<Commands::ToRender::Draw3DQuad>(glm::vec3(a), glm::vec3(b), glm::vec3(c), glm::vec3(d)); _scene->getBfcBlockManagerFactory()->cullOnChannel(BFCCullableType::CullableMesh, spotDrawableList->meshs, spotlightFrustum); spotLightList.push_back(spotDrawableList); } for (auto pointLightEntity : _pointLights.getCollection()) { auto point = pointLightEntity->getComponent<PointLightComponent>(); pointLightList.push_back(point->getCullableHandle().getPtr()->getDatas()); } for (auto cameraEntity : _cameras.getCollection()) { Frustum cameraFrustum; auto camera = cameraEntity->getComponent<CameraComponent>(); auto cameraList = std::make_shared<DRBCameraDrawableList>(); cameraList->cameraInfos.data = camera->getData(); cameraList->cameraInfos.view = glm::inverse(cameraEntity->getLink().getGlobalTransform()); cameraFrustum.setMatrix(camera->getProjection() * cameraList->cameraInfos.view); _scene->getBfcBlockManagerFactory()->cullOnChannel(BFCCullableType::CullableMesh, cameraList->meshs, cameraFrustum); _scene->getBfcBlockManagerFactory()->cullOnChannel(BFCCullableType::CullablePointLight, cameraList->pointLights, cameraFrustum); cameraList->spotLights = spotLightList; cameraList->pointLights = pointLightList; AGE::GetRenderThread()->getQueue()->emplaceCommand<AGE::DRBCameraDrawableListCommand>(cameraList); } } void RenderCameraSystem::updateEnd(float time) { } }<commit_msg>spotlight frustum in debug<commit_after>#include "RenderCameraSystem.hpp" #include <Components/CameraComponent.hpp> #include <Components/SpotLight.hh> #include <Components/DirectionalLightComponent.hh> #include <Components/Light.hh> #include <Core/Engine.hh> #include <Core/AScene.hh> #include <glm/gtc/matrix_transform.hpp> #include <BFC/BFCLinkTracker.hpp> #include <BFC/BFCBlockManagerFactory.hpp> #include <BFC/BFCCullableObject.hpp> #include <Graphic/DRBCameraDrawableList.hpp> #include <Graphic/BFCCullableTypes.hpp> #include <Threads/ThreadManager.hpp> #include <Threads/RenderThread.hpp> #include <Threads/MainThread.hpp> #include <Threads/Commands/ToRenderCommands.hpp> #include "Utils/Frustum.hh" namespace AGE { RenderCameraSystem::RenderCameraSystem(AScene *scene) : System(std::move(scene)), _cameras(std::move(scene)), _spotLights(std::move(scene)), _directionnalLights(std::move(scene)), _pointLights(std::move(scene)) { _name = "Camera system"; } bool RenderCameraSystem::initialize() { _cameras.requireComponent<CameraComponent>(); _spotLights.requireComponent<SpotLightComponent>(); _directionnalLights.requireComponent<DirectionalLightComponent>(); _pointLights.requireComponent<PointLightComponent>(); return (true); } void RenderCameraSystem::updateBegin(float time) { } void RenderCameraSystem::mainUpdate(float time) { _scene->getBfcLinkTracker()->reset(); // check if the render thread does not already have stuff to draw if (GetMainThread()->isRenderFrame() == false) { return; } std::list<std::shared_ptr<DRBSpotLightDrawableList>> spotLightList; std::list<std::shared_ptr<DRBData>> pointLightList; for (auto spotEntity : _spotLights.getCollection()) { auto spot = spotEntity->getComponent<SpotLightComponent>(); auto spotDrawableList = std::make_shared<DRBSpotLightDrawableList>(); spotDrawableList->spotLight = spot->getCullableHandle().getPtr()->getDatas(); float spotFov = glm::max(0.001f, (1.0f - spot->getCutOff()) * 180.0f); glm::mat4 spotViewProj = glm::perspective(spotFov, 1.0f, 0.1f, 1000.0f) * glm::inverse(spotEntity->getLink().getGlobalTransform()); Frustum spotlightFrustum; spotlightFrustum.setMatrix(spotViewProj); // Draw spotlight frustum debug: glm::vec4 worldPos = glm::inverse(spotViewProj) * glm::vec4(-1, -1, -1, 1.0f); glm::vec3 aNear = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(-1, 1, -1, 1.0f); glm::vec3 bNear = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(1, 1, -1, 1.0f); glm::vec3 cNear = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(1, -1, -1, 1.0f); glm::vec3 dNear = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(-1, -1, 1, 1.0f); glm::vec3 aFar = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(-1, 1, 1, 1.0f); glm::vec3 bFar = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(1, 1, 1, 1.0f); glm::vec3 cFar = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(1, -1, 1, 1.0f); glm::vec3 dFar = glm::vec3(worldPos / worldPos.w); AGE::GetRenderThread()->getQueue()->emplaceCommand<Commands::ToRender::Draw3DQuad>(aNear, bNear, cNear, dNear); AGE::GetRenderThread()->getQueue()->emplaceCommand<Commands::ToRender::Draw3DQuad>(aFar, bFar, cFar, dFar); AGE::GetRenderThread()->getQueue()->emplaceCommand<Commands::ToRender::Draw3DLine>(aNear, aFar); AGE::GetRenderThread()->getQueue()->emplaceCommand<Commands::ToRender::Draw3DLine>(bNear, bFar); AGE::GetRenderThread()->getQueue()->emplaceCommand<Commands::ToRender::Draw3DLine>(cNear, cFar); AGE::GetRenderThread()->getQueue()->emplaceCommand<Commands::ToRender::Draw3DLine>(dNear, dFar); _scene->getBfcBlockManagerFactory()->cullOnChannel(BFCCullableType::CullableMesh, spotDrawableList->meshs, spotlightFrustum); spotLightList.push_back(spotDrawableList); } for (auto pointLightEntity : _pointLights.getCollection()) { auto point = pointLightEntity->getComponent<PointLightComponent>(); pointLightList.push_back(point->getCullableHandle().getPtr()->getDatas()); } for (auto cameraEntity : _cameras.getCollection()) { Frustum cameraFrustum; auto camera = cameraEntity->getComponent<CameraComponent>(); auto cameraList = std::make_shared<DRBCameraDrawableList>(); cameraList->cameraInfos.data = camera->getData(); cameraList->cameraInfos.view = glm::inverse(cameraEntity->getLink().getGlobalTransform()); cameraFrustum.setMatrix(camera->getProjection() * cameraList->cameraInfos.view); _scene->getBfcBlockManagerFactory()->cullOnChannel(BFCCullableType::CullableMesh, cameraList->meshs, cameraFrustum); _scene->getBfcBlockManagerFactory()->cullOnChannel(BFCCullableType::CullablePointLight, cameraList->pointLights, cameraFrustum); cameraList->spotLights = spotLightList; cameraList->pointLights = pointLightList; AGE::GetRenderThread()->getQueue()->emplaceCommand<AGE::DRBCameraDrawableListCommand>(cameraList); } } void RenderCameraSystem::updateEnd(float time) { } }<|endoftext|>
<commit_before>/* * Copyright 2012 BrewPi/Elco Jacobs. * * This file is part of BrewPi. * * BrewPi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "Brewpi.h" #include "RotaryEncoder.h" #include "Pins.h" #include "util/atomic.h" #include <limits.h> #include "Ticks.h" #include "Display.h" #include "FastDigitalPin.h" #include "Brewpi.h" RotaryEncoder rotaryEncoder; #if rotarySwitchPin != 7 #error Review interrupt vectors when not using pin 7 for menu push #endif #if rotaryAPin != 8 #error Review interrupt vectors when not using pin 8 for menu right #endif #if rotaryBPin != 9 #error Review interrupt vectors when not using pin 9 for menu left #endif #if ENABLE_ROTARY_ENCODER #if defined(USBCON) // Arduino Leonardo ISR(INT6_vect){ rotaryEncoder.setPushed(); } ISR(PCINT0_vect){ //todo rotaryEncoder.rotationHandler(); static bool prevPinA = 0; static bool prevPinB = 0; bool currPinA = bitRead(PINB,4); bool currPinB = bitRead(PINB,5); if(currPinA != prevPinA){ rotaryEncoder.pinAHandler(currPinA); } if(currPinB != prevPinB){ rotaryEncoder.pinBHandler(currPinB); } prevPinA = currPinA; prevPinB = currPinB; } #else // Arduino UNO or older ISR(PCINT2_vect){ if(!bitRead(PIND,7)){ // high to low transition rotaryEncoder.setPushed(); } } ISR(PCINT0_vect){ //todo rotaryEncoder.rotationHandler(); static bool prevPinA = 0; static bool prevPinB = 0; bool currPinA = bitRead(PINB,0); bool currPinB = bitRead(PINB,1); if(currPinA != prevPinA){ rotaryEncoder.pinAHandler(currPinA); } if(currPinB != prevPinB){ rotaryEncoder.pinBHandler(currPinB); } prevPinA = currPinA; prevPinB = currPinB; } #endif #endif void RotaryEncoder::setPushed(void){ pushFlag = true; display.resetBacklightTimer(); } void RotaryEncoder::pinAHandler(bool pinState){ if(ticks.micros() - pinATime < ROTARY_THRESHOLD){ return; } pinAHistory = pinASignal; pinASignal = pinState; if ( pinAHistory==pinASignal ){ return; // not a transition } pinATime = ticks.micros(); if ( pinASignal == pinBSignal ){ steps++; } else{ steps--; } // loop around at edges if(steps > maximum){ steps = minimum; } if(steps < minimum){ steps = maximum; } display.resetBacklightTimer(); } void RotaryEncoder::pinBHandler(bool pinState){ if (ticks.micros() - pinBTime < ROTARY_THRESHOLD ){ return; } pinBHistory = pinBSignal; pinBSignal = pinState; if ( pinBHistory==pinBSignal ){ return; // not a transition } pinBTime = ticks.micros(); } void RotaryEncoder::init(void){ maximum = INT_MAX; minimum = INT_MIN; prevRead = 0; steps = 0; pushFlag = 0; pinASignal = 1; pinBSignal = 1; pinAHistory = 1; pinBHistory = 1; pinATime = 0; pinBTime = 0; #if(USE_INTERNAL_PULL_UP_RESISTORS) fastPinMode(rotaryAPin, INPUT_PULLUP); fastPinMode(rotaryBPin, INPUT_PULLUP); fastPinMode(rotarySwitchPin, INPUT_PULLUP); #else fastPinMode(rotaryAPin, INPUT); fastPinMode(rotaryBPin, INPUT); fastPinMode(rotarySwitchPin, INPUT); #endif pinAHandler(true); // call functions ones here for proper initialization pinBHandler(true); #if ENABLE_ROTARY_ENCODER #if defined(USBCON) // Arduino Leonardo // falling edge interrupt for switch on INT6 EICRB |= (1<<ISC61) | (0<<ISC60); // enable interrupt for INT6 EIMSK |= (1<<INT6); // enable pin change interrupts PCICR |= (1<<PCIE0); // enable pin change interrupt on Arduino pin 8 and 9 PCMSK0 |= (1<<PCINT5) | (1<<PCINT4); #else // Arduino UNO // enable PCINT0 (PCINT0 and PCINT1 pin) and PCINT2 vector (PCINT23 pin) PCICR |= (1<<PCIE2) | (1<<PCIE0); // enable mask bits for PCINT0 and PCINT1 PCMSK0 |= (1<<PCINT0) | (1<<PCINT1); // enable mask bit for PCINT23 PCMSK2 |= (1<<PCINT23); #endif #endif } void RotaryEncoder::setRange(int start, int minVal, int maxVal){ ATOMIC_BLOCK(ATOMIC_RESTORESTATE){ // this part cannot be interrupted // Multiply by two to convert to half steps steps = start; minimum = minVal; maximum = maxVal; // +1 to make sure that one step is still two half steps at overflow prevRead = start; } } bool RotaryEncoder::changed(void){ // returns one if the value changed since the last call of changed. static int prevValue = 0; if(read() != prevValue){ prevValue = read(); return 1; } if(pushFlag == true){ return 1; } return 0; } int RotaryEncoder::read(void){ ATOMIC_BLOCK(ATOMIC_RESTORESTATE){ prevRead = steps; return prevRead; } return 0; } <commit_msg>First step of rotary encoder was in wrong direction after reset, this fixes it.<commit_after>/* * Copyright 2012 BrewPi/Elco Jacobs. * * This file is part of BrewPi. * * BrewPi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "Brewpi.h" #include "RotaryEncoder.h" #include "Pins.h" #include "util/atomic.h" #include <limits.h> #include "Ticks.h" #include "Display.h" #include "FastDigitalPin.h" #include "Brewpi.h" RotaryEncoder rotaryEncoder; #if rotarySwitchPin != 7 #error Review interrupt vectors when not using pin 7 for menu push #endif #if rotaryAPin != 8 #error Review interrupt vectors when not using pin 8 for menu right #endif #if rotaryBPin != 9 #error Review interrupt vectors when not using pin 9 for menu left #endif #if ENABLE_ROTARY_ENCODER #if defined(USBCON) // Arduino Leonardo ISR(INT6_vect){ rotaryEncoder.setPushed(); } ISR(PCINT0_vect){ //todo rotaryEncoder.rotationHandler(); static bool prevPinA = 1; static bool prevPinB = 1; bool currPinA = bitRead(PINB,4); bool currPinB = bitRead(PINB,5); if(currPinA != prevPinA){ rotaryEncoder.pinAHandler(currPinA); } if(currPinB != prevPinB){ rotaryEncoder.pinBHandler(currPinB); } prevPinA = currPinA; prevPinB = currPinB; } #else // Arduino UNO or older ISR(PCINT2_vect){ if(!bitRead(PIND,7)){ // high to low transition rotaryEncoder.setPushed(); } } ISR(PCINT0_vect){ //todo rotaryEncoder.rotationHandler(); static bool prevPinA = 1; static bool prevPinB = 1; bool currPinA = bitRead(PINB,0); bool currPinB = bitRead(PINB,1); if(currPinA != prevPinA){ rotaryEncoder.pinAHandler(currPinA); } if(currPinB != prevPinB){ rotaryEncoder.pinBHandler(currPinB); } prevPinA = currPinA; prevPinB = currPinB; } #endif #endif void RotaryEncoder::setPushed(void){ pushFlag = true; display.resetBacklightTimer(); } void RotaryEncoder::pinAHandler(bool pinState){ if(ticks.micros() - pinATime < ROTARY_THRESHOLD){ return; } pinAHistory = pinASignal; pinASignal = pinState; if ( pinAHistory==pinASignal ){ return; // not a transition } pinATime = ticks.micros(); if ( pinASignal == pinBSignal ){ steps++; } else{ steps--; } // loop around at edges if(steps > maximum){ steps = minimum; } if(steps < minimum){ steps = maximum; } display.resetBacklightTimer(); } void RotaryEncoder::pinBHandler(bool pinState){ if (ticks.micros() - pinBTime < ROTARY_THRESHOLD ){ return; } pinBHistory = pinBSignal; pinBSignal = pinState; if ( pinBHistory==pinBSignal ){ return; // not a transition } pinBTime = ticks.micros(); } void RotaryEncoder::init(void){ maximum = INT_MAX; minimum = INT_MIN; prevRead = 0; steps = 0; pushFlag = 0; pinASignal = 1; pinBSignal = 1; pinAHistory = 1; pinBHistory = 1; pinATime = 0; pinBTime = 0; #if(USE_INTERNAL_PULL_UP_RESISTORS) fastPinMode(rotaryAPin, INPUT_PULLUP); fastPinMode(rotaryBPin, INPUT_PULLUP); fastPinMode(rotarySwitchPin, INPUT_PULLUP); #else fastPinMode(rotaryAPin, INPUT); fastPinMode(rotaryBPin, INPUT); fastPinMode(rotarySwitchPin, INPUT); #endif pinAHandler(true); // call functions ones here for proper initialization pinBHandler(true); #if ENABLE_ROTARY_ENCODER #if defined(USBCON) // Arduino Leonardo // falling edge interrupt for switch on INT6 EICRB |= (1<<ISC61) | (0<<ISC60); // enable interrupt for INT6 EIMSK |= (1<<INT6); // enable pin change interrupts PCICR |= (1<<PCIE0); // enable pin change interrupt on Arduino pin 8 and 9 PCMSK0 |= (1<<PCINT5) | (1<<PCINT4); #else // Arduino UNO // enable PCINT0 (PCINT0 and PCINT1 pin) and PCINT2 vector (PCINT23 pin) PCICR |= (1<<PCIE2) | (1<<PCIE0); // enable mask bits for PCINT0 and PCINT1 PCMSK0 |= (1<<PCINT0) | (1<<PCINT1); // enable mask bit for PCINT23 PCMSK2 |= (1<<PCINT23); #endif #endif } void RotaryEncoder::setRange(int start, int minVal, int maxVal){ ATOMIC_BLOCK(ATOMIC_RESTORESTATE){ // this part cannot be interrupted // Multiply by two to convert to half steps steps = start; minimum = minVal; maximum = maxVal; // +1 to make sure that one step is still two half steps at overflow prevRead = start; } } bool RotaryEncoder::changed(void){ // returns one if the value changed since the last call of changed. static int prevValue = 0; if(read() != prevValue){ prevValue = read(); return 1; } if(pushFlag == true){ return 1; } return 0; } int RotaryEncoder::read(void){ ATOMIC_BLOCK(ATOMIC_RESTORESTATE){ prevRead = steps; return prevRead; } return 0; } <|endoftext|>
<commit_before>#include "openmc/source.h" #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) #define HAS_DYNAMIC_LINKING #endif #include <algorithm> // for move #ifdef HAS_DYNAMIC_LINKING #include <dlfcn.h> // for dlopen, dlsym, dlclose, dlerror #endif #include <fmt/core.h> #include "xtensor/xadapt.hpp" #include "openmc/bank.h" #include "openmc/cell.h" #include "openmc/error.h" #include "openmc/file_utils.h" #include "openmc/hdf5_interface.h" #include "openmc/material.h" #include "openmc/message_passing.h" #include "openmc/mgxs_interface.h" #include "openmc/nuclide.h" #include "openmc/capi.h" #include "openmc/random_lcg.h" #include "openmc/search.h" #include "openmc/settings.h" #include "openmc/simulation.h" #include "openmc/state_point.h" #include "openmc/xml_interface.h" namespace openmc { //============================================================================== // Global variables //============================================================================== namespace model { typedef Particle::Bank (*sample_t)(uint64_t &seed); sample_t custom_source_function; void* custom_source_library; std::vector<SourceDistribution> external_sources; } //============================================================================== // SourceDistribution implementation //============================================================================== SourceDistribution::SourceDistribution(UPtrSpace space, UPtrAngle angle, UPtrDist energy) : space_{std::move(space)}, angle_{std::move(angle)}, energy_{std::move(energy)} { } SourceDistribution::SourceDistribution(pugi::xml_node node) { // Check for particle type if (check_for_node(node, "particle")) { auto temp_str = get_node_value(node, "particle", true, true); if (temp_str == "neutron") { particle_ = Particle::Type::neutron; } else if (temp_str == "photon") { particle_ = Particle::Type::photon; settings::photon_transport = true; } else { fatal_error(std::string("Unknown source particle type: ") + temp_str); } } // Check for source strength if (check_for_node(node, "strength")) { strength_ = std::stod(get_node_value(node, "strength")); } // Check for external source file if (check_for_node(node, "file")) { // Copy path of source file settings::path_source = get_node_value(node, "file", false, true); // Check if source file exists if (!file_exists(settings::path_source)) { fatal_error(fmt::format("Source file '{}' does not exist.", settings::path_source)); } } else if (check_for_node(node, "library")) { settings::path_source_library = get_node_value(node, "library", false, true); if (!file_exists(settings::path_source_library)) { fatal_error(fmt::format("Source library '{}' does not exist.", settings::path_source_library)); } } else { // Spatial distribution for external source if (check_for_node(node, "space")) { // Get pointer to spatial distribution pugi::xml_node node_space = node.child("space"); // Check for type of spatial distribution and read std::string type; if (check_for_node(node_space, "type")) type = get_node_value(node_space, "type", true, true); if (type == "cartesian") { space_ = UPtrSpace{new CartesianIndependent(node_space)}; } else if (type == "cylindrical") { space_ = UPtrSpace{new CylindricalIndependent(node_space)}; } else if (type == "spherical") { space_ = UPtrSpace{new SphericalIndependent(node_space)}; } else if (type == "box") { space_ = UPtrSpace{new SpatialBox(node_space)}; } else if (type == "fission") { space_ = UPtrSpace{new SpatialBox(node_space, true)}; } else if (type == "point") { space_ = UPtrSpace{new SpatialPoint(node_space)}; } else { fatal_error(fmt::format( "Invalid spatial distribution for external source: {}", type)); } } else { // If no spatial distribution specified, make it a point source space_ = UPtrSpace{new SpatialPoint()}; } // Determine external source angular distribution if (check_for_node(node, "angle")) { // Get pointer to angular distribution pugi::xml_node node_angle = node.child("angle"); // Check for type of angular distribution std::string type; if (check_for_node(node_angle, "type")) type = get_node_value(node_angle, "type", true, true); if (type == "isotropic") { angle_ = UPtrAngle{new Isotropic()}; } else if (type == "monodirectional") { angle_ = UPtrAngle{new Monodirectional(node_angle)}; } else if (type == "mu-phi") { angle_ = UPtrAngle{new PolarAzimuthal(node_angle)}; } else { fatal_error(fmt::format( "Invalid angular distribution for external source: {}", type)); } } else { angle_ = UPtrAngle{new Isotropic()}; } // Determine external source energy distribution if (check_for_node(node, "energy")) { pugi::xml_node node_dist = node.child("energy"); energy_ = distribution_from_xml(node_dist); } else { // Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1 energy_ = UPtrDist{new Watt(0.988e6, 2.249e-6)}; } } } Particle::Bank SourceDistribution::sample(uint64_t* seed) const { Particle::Bank site; // Set weight to one by default site.wgt = 1.0; // Repeat sampling source location until a good site has been found bool found = false; int n_reject = 0; static int n_accept = 0; while (!found) { // Set particle type site.particle = particle_; // Sample spatial distribution site.r = space_->sample(seed); double xyz[] {site.r.x, site.r.y, site.r.z}; // Now search to see if location exists in geometry int32_t cell_index, instance; int err = openmc_find_cell(xyz, &cell_index, &instance); found = (err != OPENMC_E_GEOMETRY); // Check if spatial site is in fissionable material if (found) { auto space_box = dynamic_cast<SpatialBox*>(space_.get()); if (space_box) { if (space_box->only_fissionable()) { // Determine material const auto& c = model::cells[cell_index]; auto mat_index = c->material_.size() == 1 ? c->material_[0] : c->material_[instance]; if (mat_index == MATERIAL_VOID) { found = false; } else { if (!model::materials[mat_index]->fissionable_) found = false; } } } } // Check for rejection if (!found) { ++n_reject; if (n_reject >= EXTSRC_REJECT_THRESHOLD && static_cast<double>(n_accept)/n_reject <= EXTSRC_REJECT_FRACTION) { fatal_error("More than 95% of external source sites sampled were " "rejected. Please check your external source definition."); } } } // Increment number of accepted samples ++n_accept; // Sample angle site.u = angle_->sample(seed); // Check for monoenergetic source above maximum particle energy auto p = static_cast<int>(particle_); auto energy_ptr = dynamic_cast<Discrete*>(energy_.get()); if (energy_ptr) { auto energies = xt::adapt(energy_ptr->x()); if (xt::any(energies > data::energy_max[p])) { fatal_error("Source energy above range of energies of at least " "one cross section table"); } else if (xt::any(energies < data::energy_min[p])) { fatal_error("Source energy below range of energies of at least " "one cross section table"); } } while (true) { // Sample energy spectrum site.E = energy_->sample(seed); // Resample if energy falls outside minimum or maximum particle energy if (site.E < data::energy_max[p] && site.E > data::energy_min[p]) break; } // Set delayed group site.delayed_group = 0; return site; } //============================================================================== // Non-member functions //============================================================================== void initialize_source() { write_message("Initializing source particles...", 5); if (!settings::path_source.empty()) { // Read the source from a binary file instead of sampling from some // assumed source distribution write_message(fmt::format("Reading source file from {}...", settings::path_source), 6); // Open the binary file hid_t file_id = file_open(settings::path_source, 'r', true); // Read the file type std::string filetype; read_attribute(file_id, "filetype", filetype); // Check to make sure this is a source file if (filetype != "source" && filetype != "statepoint") { fatal_error("Specified starting source file not a source file type."); } // Read in the source bank read_source_bank(file_id); // Close file file_close(file_id); } else if (!settings::path_source_library.empty()) { write_message(fmt::format("Sampling from library source {}...", settings::path_source), 6); fill_source_bank_custom_source(); } else { // Generation source sites from specified distribution in user input for (int64_t i = 0; i < simulation::work_per_rank; ++i) { // initialize random number seed int64_t id = simulation::total_gen*settings::n_particles + simulation::work_index[mpi::rank] + i + 1; uint64_t seed = init_seed(id, STREAM_SOURCE); // sample external source distribution simulation::source_bank[i] = sample_external_source(&seed); } } // Write out initial source if (settings::write_initial_source) { write_message("Writing out initial source...", 5); std::string filename = settings::path_output + "initial_source.h5"; hid_t file_id = file_open(filename, 'w', true); write_source_bank(file_id); file_close(file_id); } } Particle::Bank sample_external_source(uint64_t* seed) { // Determine total source strength double total_strength = 0.0; for (auto& s : model::external_sources) total_strength += s.strength(); // Sample from among multiple source distributions int i = 0; if (model::external_sources.size() > 1) { double xi = prn(seed)*total_strength; double c = 0.0; for (; i < model::external_sources.size(); ++i) { c += model::external_sources[i].strength(); if (xi < c) break; } } // Sample source site from i-th source distribution Particle::Bank site {model::external_sources[i].sample(seed)}; // If running in MG, convert site.E to group if (!settings::run_CE) { site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(), data::mg.rev_energy_bins_.end(), site.E); site.E = data::mg.num_energy_groups_ - site.E - 1.; } return site; } void free_memory_source() { model::external_sources.clear(); } //Load custom source library void load_custom_source_library() { #ifdef HAS_DYNAMIC_LINKING // Open the library model::source_library = dlopen(settings::path_source_library.c_str(), RTLD_LAZY); if (!model::source_library) { fatal_error("Couldn't open source library " + settings::path_source_library); } // reset errors dlerror(); // get the function from the library //using sample_t = Particle::Bank (*)(uint64_t* seed); model::sample_source = reinterpret_cast<model::sample_t>(dlsym(model::source_library, "sample_source")); // check for any dlsym errors auto dlsym_error = dlerror(); if (dlsym_error) { dlclose(model::source_library); fatal_error(fmt::format("Couldn't open the sample_source symbol: {}", dlsym_error)); } #else fatal_error("Custom source libraries have not yet been implemented for " "non-POSIX systems"); #endif } //Release custom source library void close_custom_source_library() { dlclose(model::source_library); } //Sample source particle from custom library Particle::Bank sample_custom_source_library(uint64_t* seed) { return model::sample_source(*seed); } // fill the source bank from the external source void fill_source_bank_custom_source() { // Load the custom library load_custom_source_library(); // Generation source sites from specified distribution in the // library source for (int64_t i = 0; i < simulation::work_per_rank; ++i) { // initialize random number seed int64_t id = (simulation::total_gen + overall_generation()) * settings::n_particles + simulation::work_index[mpi::rank] + i + 1; uint64_t seed = init_seed(id, STREAM_SOURCE); // sample custom library source simulation::source_bank[i] = sample_custom_source_library(&seed); } // release the library close_custom_source_library(); } } // namespace openmc <commit_msg>Rename custom source library and function and move to anonymous namespace<commit_after>#include "openmc/source.h" #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) #define HAS_DYNAMIC_LINKING #endif #include <algorithm> // for move #ifdef HAS_DYNAMIC_LINKING #include <dlfcn.h> // for dlopen, dlsym, dlclose, dlerror #endif #include <fmt/core.h> #include "xtensor/xadapt.hpp" #include "openmc/bank.h" #include "openmc/cell.h" #include "openmc/error.h" #include "openmc/file_utils.h" #include "openmc/hdf5_interface.h" #include "openmc/material.h" #include "openmc/message_passing.h" #include "openmc/mgxs_interface.h" #include "openmc/nuclide.h" #include "openmc/capi.h" #include "openmc/random_lcg.h" #include "openmc/search.h" #include "openmc/settings.h" #include "openmc/simulation.h" #include "openmc/state_point.h" #include "openmc/xml_interface.h" namespace openmc { //============================================================================== // Global variables //============================================================================== namespace model { std::vector<SourceDistribution> external_sources; } namespace { typedef Particle::Bank (*sample_t)(uint64_t &seed); sample_t custom_source_function; void* custom_source_library; } //============================================================================== // SourceDistribution implementation //============================================================================== SourceDistribution::SourceDistribution(UPtrSpace space, UPtrAngle angle, UPtrDist energy) : space_{std::move(space)}, angle_{std::move(angle)}, energy_{std::move(energy)} { } SourceDistribution::SourceDistribution(pugi::xml_node node) { // Check for particle type if (check_for_node(node, "particle")) { auto temp_str = get_node_value(node, "particle", true, true); if (temp_str == "neutron") { particle_ = Particle::Type::neutron; } else if (temp_str == "photon") { particle_ = Particle::Type::photon; settings::photon_transport = true; } else { fatal_error(std::string("Unknown source particle type: ") + temp_str); } } // Check for source strength if (check_for_node(node, "strength")) { strength_ = std::stod(get_node_value(node, "strength")); } // Check for external source file if (check_for_node(node, "file")) { // Copy path of source file settings::path_source = get_node_value(node, "file", false, true); // Check if source file exists if (!file_exists(settings::path_source)) { fatal_error(fmt::format("Source file '{}' does not exist.", settings::path_source)); } } else if (check_for_node(node, "library")) { settings::path_source_library = get_node_value(node, "library", false, true); if (!file_exists(settings::path_source_library)) { fatal_error(fmt::format("Source library '{}' does not exist.", settings::path_source_library)); } } else { // Spatial distribution for external source if (check_for_node(node, "space")) { // Get pointer to spatial distribution pugi::xml_node node_space = node.child("space"); // Check for type of spatial distribution and read std::string type; if (check_for_node(node_space, "type")) type = get_node_value(node_space, "type", true, true); if (type == "cartesian") { space_ = UPtrSpace{new CartesianIndependent(node_space)}; } else if (type == "cylindrical") { space_ = UPtrSpace{new CylindricalIndependent(node_space)}; } else if (type == "spherical") { space_ = UPtrSpace{new SphericalIndependent(node_space)}; } else if (type == "box") { space_ = UPtrSpace{new SpatialBox(node_space)}; } else if (type == "fission") { space_ = UPtrSpace{new SpatialBox(node_space, true)}; } else if (type == "point") { space_ = UPtrSpace{new SpatialPoint(node_space)}; } else { fatal_error(fmt::format( "Invalid spatial distribution for external source: {}", type)); } } else { // If no spatial distribution specified, make it a point source space_ = UPtrSpace{new SpatialPoint()}; } // Determine external source angular distribution if (check_for_node(node, "angle")) { // Get pointer to angular distribution pugi::xml_node node_angle = node.child("angle"); // Check for type of angular distribution std::string type; if (check_for_node(node_angle, "type")) type = get_node_value(node_angle, "type", true, true); if (type == "isotropic") { angle_ = UPtrAngle{new Isotropic()}; } else if (type == "monodirectional") { angle_ = UPtrAngle{new Monodirectional(node_angle)}; } else if (type == "mu-phi") { angle_ = UPtrAngle{new PolarAzimuthal(node_angle)}; } else { fatal_error(fmt::format( "Invalid angular distribution for external source: {}", type)); } } else { angle_ = UPtrAngle{new Isotropic()}; } // Determine external source energy distribution if (check_for_node(node, "energy")) { pugi::xml_node node_dist = node.child("energy"); energy_ = distribution_from_xml(node_dist); } else { // Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1 energy_ = UPtrDist{new Watt(0.988e6, 2.249e-6)}; } } } Particle::Bank SourceDistribution::sample(uint64_t* seed) const { Particle::Bank site; // Set weight to one by default site.wgt = 1.0; // Repeat sampling source location until a good site has been found bool found = false; int n_reject = 0; static int n_accept = 0; while (!found) { // Set particle type site.particle = particle_; // Sample spatial distribution site.r = space_->sample(seed); double xyz[] {site.r.x, site.r.y, site.r.z}; // Now search to see if location exists in geometry int32_t cell_index, instance; int err = openmc_find_cell(xyz, &cell_index, &instance); found = (err != OPENMC_E_GEOMETRY); // Check if spatial site is in fissionable material if (found) { auto space_box = dynamic_cast<SpatialBox*>(space_.get()); if (space_box) { if (space_box->only_fissionable()) { // Determine material const auto& c = model::cells[cell_index]; auto mat_index = c->material_.size() == 1 ? c->material_[0] : c->material_[instance]; if (mat_index == MATERIAL_VOID) { found = false; } else { if (!model::materials[mat_index]->fissionable_) found = false; } } } } // Check for rejection if (!found) { ++n_reject; if (n_reject >= EXTSRC_REJECT_THRESHOLD && static_cast<double>(n_accept)/n_reject <= EXTSRC_REJECT_FRACTION) { fatal_error("More than 95% of external source sites sampled were " "rejected. Please check your external source definition."); } } } // Increment number of accepted samples ++n_accept; // Sample angle site.u = angle_->sample(seed); // Check for monoenergetic source above maximum particle energy auto p = static_cast<int>(particle_); auto energy_ptr = dynamic_cast<Discrete*>(energy_.get()); if (energy_ptr) { auto energies = xt::adapt(energy_ptr->x()); if (xt::any(energies > data::energy_max[p])) { fatal_error("Source energy above range of energies of at least " "one cross section table"); } else if (xt::any(energies < data::energy_min[p])) { fatal_error("Source energy below range of energies of at least " "one cross section table"); } } while (true) { // Sample energy spectrum site.E = energy_->sample(seed); // Resample if energy falls outside minimum or maximum particle energy if (site.E < data::energy_max[p] && site.E > data::energy_min[p]) break; } // Set delayed group site.delayed_group = 0; return site; } //============================================================================== // Non-member functions //============================================================================== void initialize_source() { write_message("Initializing source particles...", 5); if (!settings::path_source.empty()) { // Read the source from a binary file instead of sampling from some // assumed source distribution write_message(fmt::format("Reading source file from {}...", settings::path_source), 6); // Open the binary file hid_t file_id = file_open(settings::path_source, 'r', true); // Read the file type std::string filetype; read_attribute(file_id, "filetype", filetype); // Check to make sure this is a source file if (filetype != "source" && filetype != "statepoint") { fatal_error("Specified starting source file not a source file type."); } // Read in the source bank read_source_bank(file_id); // Close file file_close(file_id); } else if (!settings::path_source_library.empty()) { write_message(fmt::format("Sampling from library source {}...", settings::path_source), 6); fill_source_bank_custom_source(); } else { // Generation source sites from specified distribution in user input for (int64_t i = 0; i < simulation::work_per_rank; ++i) { // initialize random number seed int64_t id = simulation::total_gen*settings::n_particles + simulation::work_index[mpi::rank] + i + 1; uint64_t seed = init_seed(id, STREAM_SOURCE); // sample external source distribution simulation::source_bank[i] = sample_external_source(&seed); } } // Write out initial source if (settings::write_initial_source) { write_message("Writing out initial source...", 5); std::string filename = settings::path_output + "initial_source.h5"; hid_t file_id = file_open(filename, 'w', true); write_source_bank(file_id); file_close(file_id); } } Particle::Bank sample_external_source(uint64_t* seed) { // Determine total source strength double total_strength = 0.0; for (auto& s : model::external_sources) total_strength += s.strength(); // Sample from among multiple source distributions int i = 0; if (model::external_sources.size() > 1) { double xi = prn(seed)*total_strength; double c = 0.0; for (; i < model::external_sources.size(); ++i) { c += model::external_sources[i].strength(); if (xi < c) break; } } // Sample source site from i-th source distribution Particle::Bank site {model::external_sources[i].sample(seed)}; // If running in MG, convert site.E to group if (!settings::run_CE) { site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(), data::mg.rev_energy_bins_.end(), site.E); site.E = data::mg.num_energy_groups_ - site.E - 1.; } return site; } void free_memory_source() { model::external_sources.clear(); } //Load custom source library void load_custom_source_library() { #ifdef HAS_DYNAMIC_LINKING // Open the library custom_source_library = dlopen(settings::path_source_library.c_str(), RTLD_LAZY); if (!custom_source_library) { fatal_error("Couldn't open source library " + settings::path_source_library); } // reset errors dlerror(); // get the function from the library //using sample_t = Particle::Bank (*)(uint64_t* seed); custom_source_function = reinterpret_cast<sample_t>(dlsym(custom_source_library, "sample_source")); // check for any dlsym errors auto dlsym_error = dlerror(); if (dlsym_error) { dlclose(custom_source_library); fatal_error(fmt::format("Couldn't open the sample_source symbol: {}", dlsym_error)); } #else fatal_error("Custom source libraries have not yet been implemented for " "non-POSIX systems"); #endif } //Release custom source library void close_custom_source_library() { dlclose(custom_source_library); } //Sample source particle from custom library Particle::Bank sample_custom_source_library(uint64_t* seed) { return custom_source_function(*seed); } // fill the source bank from the external source void fill_source_bank_custom_source() { // Load the custom library load_custom_source_library(); // Generation source sites from specified distribution in the // library source for (int64_t i = 0; i < simulation::work_per_rank; ++i) { // initialize random number seed int64_t id = (simulation::total_gen + overall_generation()) * settings::n_particles + simulation::work_index[mpi::rank] + i + 1; uint64_t seed = init_seed(id, STREAM_SOURCE); // sample custom library source simulation::source_bank[i] = sample_custom_source_library(&seed); } // release the library close_custom_source_library(); } } // namespace openmc <|endoftext|>
<commit_before><commit_msg>update uoj10680<commit_after><|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_cme.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ // *INDENT-OFF* /// /// @file p9_pm_recovery_ffdc_cme.C /// @brief Models CME platform for the FFDC collection of PM complex /// /// *HWP HWP Owner: Greg Still <stillgs@us.ibm.com> /// *HWP FW Owner: Prem S Jha <premjha2@in.ibm.com> /// *HWP Team: PM /// *HWP Level: 2 /// *HWP Consumed by: Hostboot // // *INDENT-OFF* //-------------------------------------------------------------------------- // Includes //-------------------------------------------------------------------------- #include <p9_pm_recovery_ffdc_cme.H> #include <p9_hcd_memmap_cme_sram.H> #include <p9_ppe_defs.H> #include <stddef.h> #include <endian.h> namespace p9_stop_recov_ffdc { PlatCme::PlatCme( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt ) : PlatPmComplex( i_procChipTgt, FFDC_PPE_IMG_HDR_START, FFDC_CME_TRACE_START, FFDC_CME_DASH_BOARD_START, PLAT_CME ) { } //---------------------------------------------------------------------- fapi2::ReturnCode PlatCme::collectFfdc( void * i_pHomerBuf ) { FAPI_DBG(">> PlatCme::collectFfdc"); fapi2::ReturnCode l_retCode = fapi2::FAPI2_RC_SUCCESS; auto l_exList = getProcChip().getChildren< fapi2::TARGET_TYPE_EX > ( fapi2::TARGET_STATE_PRESENT ); uint8_t l_quadPos = 0; uint8_t l_exPos = 0; uint8_t l_cmePos = 0; uint8_t l_ffdcValdityVect = PPE_FFDC_ALL_VALID; uint8_t l_haltState = PPE_HALT_COND_UNKNOWN; uint8_t *l_pFfdcLoc = NULL; HomerFfdcRegion * l_pHomerFfdc = ( HomerFfdcRegion *)( (uint8_t *)i_pHomerBuf + FFDC_REGION_HOMER_BASE_OFFSET ); for( auto ex : l_exList ) { l_ffdcValdityVect = PPE_FFDC_ALL_VALID; FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, ex, l_cmePos ), "FAPI_ATTR_GET Failed To Read EX Position" ); if( !ex.isFunctional() ) { //Marking CME FFDC region as Invalid FAPI_TRY( updateCmeFfdcHeader( l_pFfdcLoc, l_cmePos, l_ffdcValdityVect, l_haltState ), "Failed To Update CME FFDC Header for CME 0x%0d", l_cmePos ); continue; } l_exPos = l_cmePos % 2; l_quadPos = l_cmePos >> 1; l_pFfdcLoc = &l_pHomerFfdc->iv_quadFfdc[l_quadPos].iv_quadCmeBlock[l_exPos][0]; FAPI_INF("CME FFDC Quad Pos %d Ex Pos %d ", l_quadPos, l_exPos ); //In case of error , invalidate FFDC in header. // @TODO this is still after reset, which would have already // halted the ppe. We need a wa to record this before reset // and pass it down, or have a spl r-m-w update per member // of the PPE Header? // l_retCode = getPpeHaltState ( // getCmeBaseAddress (l_cmePos), // l_haltState); l_retCode = collectPpeState ( getCmeBaseAddress (l_cmePos), l_pFfdcLoc ); if ( l_retCode != fapi2::FAPI2_RC_SUCCESS ) { FAPI_ERR ( "Error collecting CME State, CME Pos 0x08x", l_cmePos ); l_ffdcValdityVect &= ~PPE_STATE_VALID; } l_retCode = collectTrace( l_pFfdcLoc, ex ); if( l_retCode ) { FAPI_ERR("Error in collecting CME Trace CME Pos 0x%08x", l_cmePos ); l_ffdcValdityVect &= ~PPE_TRACE_VALID; } l_retCode = collectGlobals( l_pFfdcLoc, ex ); if( l_retCode ) { FAPI_ERR("Error in collecting CME Globals, CME Pos 0x%08x", l_cmePos ); l_ffdcValdityVect &= ~PPE_DASHBOARD_VALID; } l_retCode = collectImageHeader( l_pFfdcLoc, ex ); if( l_retCode ) { FAPI_ERR("Error in collecting CME Image header, CME Pos 0x%08x", l_cmePos ); l_ffdcValdityVect &= ~PPE_IMAGE_HEADER_VALID; } FAPI_TRY( updateCmeFfdcHeader( l_pFfdcLoc, l_cmePos, l_ffdcValdityVect, l_haltState ), "Failed To Update CME FFDC Header for CME 0x%0d", l_cmePos ); } fapi_try_exit: FAPI_DBG("<< PlatCme::collectFfdc"); return fapi2::current_err; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatCme::collectTrace( uint8_t * i_pTraceBuf, const fapi2::Target<fapi2::TARGET_TYPE_EX >& i_exTgt ) { FAPI_DBG(">> PlatCme::collectTrace" ); PpeFfdcLayout * l_pCmeFfdc = ( PpeFfdcLayout *) ( i_pTraceBuf ); uint8_t * l_pTraceLoc = &l_pCmeFfdc->iv_ppeTraces[0]; FAPI_TRY( PlatPmComplex::collectSramInfo ( i_exTgt, l_pTraceLoc, TRACES, FFDC_PPE_TRACES_SIZE ), "Trace Collection Failed" ); fapi_try_exit: FAPI_DBG("<< PlatCme::collectTrace" ); return fapi2::current_err; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatCme::collectGlobals( uint8_t * i_pCmeGlobals, const fapi2::Target<fapi2::TARGET_TYPE_EX >& i_exTgt ) { FAPI_DBG(">> PlatCme::collectGlobals" ); PpeFfdcLayout * l_pCmeFfdc = ( PpeFfdcLayout *) ( i_pCmeGlobals ); uint8_t * l_pTraceLoc = &l_pCmeFfdc->iv_ppeGlobals[0]; FAPI_TRY( PlatPmComplex::collectSramInfo ( i_exTgt, l_pTraceLoc, DASH_BOARD_VAR, FFDC_PPE_SCORE_BOARD_SIZE ), "Failed To Collect CME Global Variables" ); fapi_try_exit: FAPI_DBG("<< PlatCme::collectGlobals" ); return fapi2::current_err; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatCme::collectInternalReg( uint8_t * i_pCmeIntReg, const fapi2::Target<fapi2::TARGET_TYPE_EX >& i_exTgt ) { return fapi2::FAPI2_RC_SUCCESS; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatCme::collectImageHeader( uint8_t * i_pCmeImgHdr, const fapi2::Target<fapi2::TARGET_TYPE_EX >& i_exTgt ) { FAPI_DBG(">> PlatCme::collectImageHeader" ); PpeFfdcLayout *l_pCmeFfdc = ( PpeFfdcLayout *) ( i_pCmeImgHdr ); uint8_t * l_pTraceLoc = &l_pCmeFfdc->iv_ppeImageHeader[0]; FAPI_TRY( PlatPmComplex::collectSramInfo ( i_exTgt, l_pTraceLoc, IMAGE_HEADER, FFDC_PPE_IMG_HDR_SIZE ), "Failed To Collect CME Image Header" ); fapi_try_exit: FAPI_DBG("<< PlatCme::collectImageHeader" ); return fapi2::current_err; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatCme::updateCmeFfdcHeader( uint8_t * i_pHomerBuf, uint8_t i_cmePos, uint8_t l_ffdcValdityVect, uint8_t i_haltState ) { FAPI_DBG(">> updateCmeFfdcHeader" ); PpeFfdcHeader * l_pCmeFfdcHdr = ( (PpeFfdcHeader *)(( PpeFfdcHdrRegion * ) i_pHomerBuf )); l_pCmeFfdcHdr->iv_ppeMagicNumber = htobe32(FFDC_CME_MAGIC_NUM); l_pCmeFfdcHdr->iv_ppeNumber = i_cmePos; PlatPmComplex::updatePpeFfdcHeader( l_pCmeFfdcHdr, l_ffdcValdityVect, i_haltState ); FAPI_DBG("<< updateCmeFfdcHeader" ); return fapi2::FAPI2_RC_SUCCESS; } //----------------------------------------------------------------------- extern "C" { fapi2::ReturnCode p9_pm_recovery_ffdc_cme( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP >& i_procChip, void * i_pFfdcBuf ) { FAPI_IMP(">> p9_pm_recovery_ffdc_cme" ); PlatCme l_cmeFfdc( i_procChip ); FAPI_TRY( l_cmeFfdc.collectFfdc( i_pFfdcBuf ), "Failed To Collect CME FFDC" ); fapi_try_exit: FAPI_IMP("<< p9_pm_recovery_ffdc_cme" ); return fapi2::current_err; } } }//namespace p9_stop_recov_ffdc ends <commit_msg>PM Recovery FFDC: Added support to collect Register data for PPM<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_cme.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ // *INDENT-OFF* /// /// @file p9_pm_recovery_ffdc_cme.C /// @brief Models CME platform for the FFDC collection of PM complex /// /// *HWP HWP Owner: Greg Still <stillgs@us.ibm.com> /// *HWP FW Owner: Prem S Jha <premjha2@in.ibm.com> /// *HWP Team: PM /// *HWP Level: 2 /// *HWP Consumed by: Hostboot // // *INDENT-OFF* //-------------------------------------------------------------------------- // Includes //-------------------------------------------------------------------------- #include <p9_pm_recovery_ffdc_cme.H> #include <p9_hcd_memmap_cme_sram.H> #include <collect_reg_ffdc.H> #include <p9_ppe_defs.H> #include <stddef.h> #include <endian.h> namespace p9_stop_recov_ffdc { PlatCme::PlatCme( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt ) : PlatPmComplex( i_procChipTgt, FFDC_PPE_IMG_HDR_START, FFDC_CME_TRACE_START, FFDC_CME_DASH_BOARD_START, PLAT_CME ) { } //---------------------------------------------------------------------- fapi2::ReturnCode PlatCme::collectFfdc( void * i_pHomerBuf ) { FAPI_DBG(">> PlatCme::collectFfdc"); fapi2::ReturnCode l_retCode = fapi2::FAPI2_RC_SUCCESS; auto l_exList = getProcChip().getChildren< fapi2::TARGET_TYPE_EX > ( fapi2::TARGET_STATE_PRESENT ); uint8_t l_quadPos = 0; uint8_t l_exPos = 0; uint8_t l_cmePos = 0; uint8_t l_ffdcValdityVect = PPE_FFDC_ALL_VALID; uint8_t l_haltState = PPE_HALT_COND_UNKNOWN; uint8_t *l_pFfdcLoc = NULL; HomerFfdcRegion * l_pHomerFfdc = ( HomerFfdcRegion *)( (uint8_t *)i_pHomerBuf + FFDC_REGION_HOMER_BASE_OFFSET ); for( auto ex : l_exList ) { l_ffdcValdityVect = PPE_FFDC_ALL_VALID; FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, ex, l_cmePos ), "FAPI_ATTR_GET Failed To Read EX Position" ); if( !ex.isFunctional() ) { //Marking CME FFDC region as Invalid l_ffdcValdityVect = PPE_FFDC_INVALID; FAPI_TRY( updateCmeFfdcHeader( l_pFfdcLoc, l_cmePos, l_ffdcValdityVect, l_haltState ), "Failed To Update CME FFDC Header for CME 0x%0d", l_cmePos ); continue; } l_exPos = l_cmePos % 2; l_quadPos = l_cmePos >> 1; l_pFfdcLoc = &l_pHomerFfdc->iv_quadFfdc[l_quadPos].iv_quadCmeBlock[l_exPos][0]; FAPI_INF("CME FFDC Quad Pos %d Ex Pos %d ", l_quadPos, l_exPos ); //In case of error , invalidate FFDC in header. // @TODO this is still after reset, which would have already // halted the ppe. We need a wa to record this before reset // and pass it down, or have a spl r-m-w update per member // of the PPE Header? // l_retCode = getPpeHaltState ( // getCmeBaseAddress (l_cmePos), // l_haltState); l_retCode = collectPpeState ( getCmeBaseAddress (l_cmePos), l_pFfdcLoc ); if ( l_retCode != fapi2::FAPI2_RC_SUCCESS ) { FAPI_ERR ( "Error collecting CME State, CME Pos 0x08x", l_cmePos ); l_ffdcValdityVect &= ~PPE_STATE_VALID; } l_retCode = collectTrace( l_pFfdcLoc, ex ); if( l_retCode ) { FAPI_ERR("Error in collecting CME Trace CME Pos 0x%08x", l_cmePos ); l_ffdcValdityVect &= ~PPE_TRACE_VALID; } l_retCode = collectGlobals( l_pFfdcLoc, ex ); if( l_retCode ) { FAPI_ERR("Error in collecting CME Globals, CME Pos 0x%08x", l_cmePos ); l_ffdcValdityVect &= ~PPE_DASHBOARD_VALID; } l_retCode = collectImageHeader( l_pFfdcLoc, ex ); if( l_retCode ) { FAPI_ERR("Error in collecting CME Image header, CME Pos 0x%08x", l_cmePos ); l_ffdcValdityVect &= ~PPE_IMAGE_HEADER_VALID; } l_retCode = collectInternalReg( l_pFfdcLoc, ex , l_cmePos); if( l_retCode ) { FAPI_ERR("Error in collecting CME Internal Regs, CME Pos 0x%08x", l_cmePos ); l_ffdcValdityVect &= ~PPE_INT_REG_VALID; } FAPI_TRY( updateCmeFfdcHeader( l_pFfdcLoc, l_cmePos, l_ffdcValdityVect, l_haltState ), "Failed To Update CME FFDC Header for CME 0x%0d", l_cmePos ); } fapi_try_exit: FAPI_DBG("<< PlatCme::collectFfdc"); return fapi2::current_err; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatCme::collectTrace( uint8_t * i_pTraceBuf, const fapi2::Target<fapi2::TARGET_TYPE_EX >& i_exTgt ) { FAPI_DBG(">> PlatCme::collectTrace" ); PpeFfdcLayout * l_pCmeFfdc = ( PpeFfdcLayout *) ( i_pTraceBuf ); uint8_t * l_pTraceLoc = &l_pCmeFfdc->iv_ppeTraces[0]; FAPI_TRY( PlatPmComplex::collectSramInfo ( i_exTgt, l_pTraceLoc, TRACES, FFDC_PPE_TRACES_SIZE ), "Trace Collection Failed" ); fapi_try_exit: FAPI_DBG("<< PlatCme::collectTrace" ); return fapi2::current_err; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatCme::collectGlobals( uint8_t * i_pCmeGlobals, const fapi2::Target<fapi2::TARGET_TYPE_EX >& i_exTgt ) { FAPI_DBG(">> PlatCme::collectGlobals" ); PpeFfdcLayout * l_pCmeFfdc = ( PpeFfdcLayout *) ( i_pCmeGlobals ); uint8_t * l_pTraceLoc = &l_pCmeFfdc->iv_ppeGlobals[0]; FAPI_TRY( PlatPmComplex::collectSramInfo ( i_exTgt, l_pTraceLoc, DASH_BOARD_VAR, FFDC_PPE_SCORE_BOARD_SIZE ), "Failed To Collect CME Global Variables" ); fapi_try_exit: FAPI_DBG("<< PlatCme::collectGlobals" ); return fapi2::current_err; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatCme::collectInternalReg( uint8_t * i_pCmeIntReg, const fapi2::Target<fapi2::TARGET_TYPE_EX >& i_exTgt , const uint8_t i_exPos) { FAPI_DBG(">> PlatCme::collectInternalReg" ); PpeFfdcLayout * l_pCmeFfdc = ( PpeFfdcLayout *) ( i_pCmeIntReg); uint8_t * l_pIntRegs = &l_pCmeFfdc->iv_ppeInternalReg[0]; FAPI_INF("CME Internal FFDC Pos %d ", i_exPos); FAPI_TRY(collectRegisterData<fapi2::TARGET_TYPE_EX> (i_exTgt, l_pIntRegs, static_cast<fapi2::HwpFfdcId>(fapi2::CME_INTERNAL_FFDC_REGISTERS)), "Failed to collect register data for CME instance %u",i_exPos); fapi_try_exit: FAPI_DBG("<< PlatCme::collectInternalReg" ); return fapi2::FAPI2_RC_SUCCESS; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatCme::collectImageHeader( uint8_t * i_pCmeImgHdr, const fapi2::Target<fapi2::TARGET_TYPE_EX >& i_exTgt ) { FAPI_DBG(">> PlatCme::collectImageHeader" ); PpeFfdcLayout *l_pCmeFfdc = ( PpeFfdcLayout *) ( i_pCmeImgHdr ); uint8_t * l_pTraceLoc = &l_pCmeFfdc->iv_ppeImageHeader[0]; FAPI_TRY( PlatPmComplex::collectSramInfo ( i_exTgt, l_pTraceLoc, IMAGE_HEADER, FFDC_PPE_IMG_HDR_SIZE ), "Failed To Collect CME Image Header" ); fapi_try_exit: FAPI_DBG("<< PlatCme::collectImageHeader" ); return fapi2::current_err; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatCme::updateCmeFfdcHeader( uint8_t * i_pHomerBuf, uint8_t i_cmePos, uint8_t l_ffdcValdityVect, uint8_t i_haltState ) { FAPI_DBG(">> updateCmeFfdcHeader" ); PpeFfdcHeader * l_pCmeFfdcHdr = ( (PpeFfdcHeader *)(( PpeFfdcHdrRegion * ) i_pHomerBuf )); l_pCmeFfdcHdr->iv_ppeMagicNumber = htobe32(FFDC_CME_MAGIC_NUM); l_pCmeFfdcHdr->iv_ppeNumber = i_cmePos; PlatPmComplex::updatePpeFfdcHeader( l_pCmeFfdcHdr, l_ffdcValdityVect, i_haltState ); FAPI_DBG("<< updateCmeFfdcHeader" ); return fapi2::FAPI2_RC_SUCCESS; } //----------------------------------------------------------------------- extern "C" { fapi2::ReturnCode p9_pm_recovery_ffdc_cme( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP >& i_procChip, void * i_pFfdcBuf ) { FAPI_IMP(">> p9_pm_recovery_ffdc_cme" ); PlatCme l_cmeFfdc( i_procChip ); FAPI_TRY( l_cmeFfdc.collectFfdc( i_pFfdcBuf ), "Failed To Collect CME FFDC" ); fapi_try_exit: FAPI_IMP("<< p9_pm_recovery_ffdc_cme" ); return fapi2::current_err; } } }//namespace p9_stop_recov_ffdc ends <|endoftext|>
<commit_before>// Copyright (c) 2013, Maria Teresa Lazaro Grañon // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "g2o/stuff/command_args.h" #include <string> #include <sstream> #include "slam/graph_slam.h" #include "ros_utils/ros_handler.h" #include "ros_utils/graph_ros_publisher.h" #include "ros_map_publisher/graph2occupancy.h" #include "ros_map_publisher/occupancy_map_server.h" using namespace g2o; #include <sys/time.h> //Log files int logData; ofstream timesfile, bytesfile; double timeval_diff(struct timeval *a, struct timeval *b) { return (double)(a->tv_sec + (double)a->tv_usec/1000000) - (double)(b->tv_sec + (double)b->tv_usec/1000000); } int main(int argc, char **argv) { CommandArgs arg; double resolution; double maxScore; double kernelRadius; int minInliers; int windowLoopClosure; double inlierThreshold; int idRobot; int nRobots; std::string outputFilename; std::string odometryTopic, scanTopic, odomFrame, mapFrame, baseFrame; std::vector<double> initialPose; initialPose.clear(); bool publishTransform; float localizationAngularUpdate, localizationLinearUpdate; float maxRange, usableRange; arg.param("resolution", resolution, 0.025, "resolution of the matching grid"); arg.param("maxScore", maxScore, 0.15, "score of the matcher, the higher the less matches"); arg.param("kernelRadius", kernelRadius, 0.2, "radius of the convolution kernel"); arg.param("minInliers", minInliers, 7, "min inliers"); arg.param("windowLoopClosure", windowLoopClosure, 10, "sliding window for loop closures"); arg.param("inlierThreshold", inlierThreshold, 2., "inlier threshold"); arg.param("idRobot", idRobot, 0, "robot identifier" ); arg.param("nRobots", nRobots, 1, "number of robots" ); arg.param("angularUpdate", localizationAngularUpdate, M_PI_4, "angular rotation interval for updating the graph, in radians"); arg.param("linearUpdate", localizationLinearUpdate, 0.25, "linear translation interval for updating the graph, in meters"); arg.param("odometryTopic", odometryTopic, "odom", "odometry ROS topic"); arg.param("scanTopic", scanTopic, "scan", "scan ROS topic"); arg.param("odomFrame", odomFrame, "odom", "odom frame"); arg.param("mapFrame", mapFrame, "map", "map frame"); arg.param("baseFrame", baseFrame, "/base_link", "base robot frame"); arg.param("initialPose", initialPose, std::vector<double>(), "Pose of the first vertex in the graph. Usage: -initial_pose 0,0,0"); arg.param("publishTransform", publishTransform, false, "Publish map transform"); arg.param("o", outputFilename, "", "file where to save output"); arg.parseArgs(argc, argv); //map parameters float mapResolution = 0.05; float occupiedThreshold = 0.65; float rows = 0; float cols = 0; float gain = 3.0; float squareSize = 0; float angle = M_PI_2; float freeThreshold = 0.196; ros::init(argc, argv, "srslam"); RosHandler rh(idRobot, nRobots, REAL_EXPERIMENT); rh.setOdomTopic(odometryTopic); rh.setScanTopic(scanTopic); rh.setBaseFrame(baseFrame); rh.useOdom(true); rh.useLaser(true); rh.init(); rh.run(); maxRange = rh.getLaserMaxRange(); usableRange = maxRange; //For estimation SE2 currEst = rh.getOdom(); std::cout << "My initial position is: " << currEst.translation().x() << " " << currEst.translation().y() << " " << currEst.rotation().angle() << std::endl; SE2 odomPosk_1 = currEst; std::cout << "My initial odometry is: " << odomPosk_1.translation().x() << " " << odomPosk_1.translation().y() << " " << odomPosk_1.rotation().angle() << std::endl; //Graph building GraphSLAM gslam; gslam.setIdRobot(idRobot); int baseId = 10000; gslam.setBaseId(baseId); gslam.init(resolution, kernelRadius, windowLoopClosure, maxScore, inlierThreshold, minInliers); //Map building cv::Mat occupancyMap; Eigen::Vector2f mapCenter; Graph2occupancy mapCreator(gslam.graph(), &occupancyMap, currEst, mapResolution, occupiedThreshold, rows, cols, maxRange, usableRange, gain, squareSize, angle, freeThreshold); OccupancyMapServer mapServer(&occupancyMap, idRobot, SIM_EXPERIMENT, mapFrame, occupiedThreshold, freeThreshold); RobotLaser* rlaser = rh.getLaser(); gslam.setInitialData(currEst, odomPosk_1, rlaser); GraphRosPublisher graphPublisher(gslam.graph(), mapFrame, odomFrame); if (publishTransform) graphPublisher.publishMapTransform(gslam.lastVertex()->estimate(), odomPosk_1); char buf[100]; sprintf(buf, "robot-%i-%s", idRobot, outputFilename.c_str()); ofstream ofmap(buf); gslam.graph()->saveVertex(ofmap, gslam.lastVertex()); mapCreator.computeMap(); mapCenter = mapCreator.getMapCenter(); mapServer.setOffset(mapCenter); mapServer.setResolution(mapResolution); mapServer.publishMapMetaData(); mapServer.publishMap(); ros::Rate loop_rate(10); while (ros::ok()){ ros::spinOnce(); SE2 odomPosk = rh.getOdom(); //current odometry SE2 relodom = odomPosk_1.inverse() * odomPosk; currEst *= relodom; odomPosk_1 = odomPosk; if((distanceSE2(gslam.lastVertex()->estimate(), currEst) > localizationLinearUpdate) || (fabs(gslam.lastVertex()->estimate().rotation().angle()-currEst.rotation().angle()) > localizationAngularUpdate)){ //Add new data RobotLaser* laseri = rh.getLaser(); gslam.addDataSM(odomPosk, laseri); gslam.findConstraints(); struct timeval t_ini, t_fin; double secs; gettimeofday(&t_ini, NULL); gslam.optimize(5); gettimeofday(&t_fin, NULL); secs = timeval_diff(&t_fin, &t_ini); printf("Optimization took %.16g milliseconds\n", secs * 1000.0); currEst = gslam.lastVertex()->estimate(); char buf[100]; sprintf(buf, "robot-%i-%s", idRobot, outputFilename.c_str()); gslam.saveGraph(buf); //Publish graph to visualize it on Rviz graphPublisher.publishGraph(); //Publish map transform with corrected estimate if (publishTransform) graphPublisher.publishMapTransform(gslam.lastVertex()->estimate(), odomPosk_1); mapCreator.computeMap(); mapCenter = mapCreator.getMapCenter(); mapServer.setOffset(mapCenter); }else { //Publish map transform with last corrected estimate + odometry drift if (publishTransform) graphPublisher.publishMapTransform(currEst, odomPosk_1); } mapServer.publishMapMetaData(); mapServer.publishMap(); loop_rate.sleep(); } cerr << "Last Optimization..."; gslam.optimize(5); gslam.saveGraph(buf); cerr << "Done" << endl; return 0; } <commit_msg>updated srslam with params initialPose, publishMap and publishGraph<commit_after>// Copyright (c) 2013, Maria Teresa Lazaro Grañon // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "g2o/stuff/command_args.h" #include <string> #include <sstream> #include "slam/graph_slam.h" #include "ros_utils/ros_handler.h" #include "ros_utils/graph_ros_publisher.h" #include "ros_map_publisher/graph2occupancy.h" #include "ros_map_publisher/occupancy_map_server.h" using namespace g2o; #include <sys/time.h> //Log files int logData; ofstream timesfile, bytesfile; double timeval_diff(struct timeval *a, struct timeval *b) { return (double)(a->tv_sec + (double)a->tv_usec/1000000) - (double)(b->tv_sec + (double)b->tv_usec/1000000); } int main(int argc, char **argv) { CommandArgs arg; double resolution; double maxScore; double kernelRadius; int minInliers; int windowLoopClosure; double inlierThreshold; int idRobot; int nRobots; std::string outputFilename; std::string odometryTopic, scanTopic, odomFrame, mapFrame, baseFrame; std::vector<double> initialPose; initialPose.clear(); bool publishMap, publishGraph; float localizationAngularUpdate, localizationLinearUpdate; float maxRange, usableRange; arg.param("resolution", resolution, 0.025, "resolution of the matching grid"); arg.param("maxScore", maxScore, 0.15, "score of the matcher, the higher the less matches"); arg.param("kernelRadius", kernelRadius, 0.2, "radius of the convolution kernel"); arg.param("minInliers", minInliers, 7, "min inliers"); arg.param("windowLoopClosure", windowLoopClosure, 10, "sliding window for loop closures"); arg.param("inlierThreshold", inlierThreshold, 2., "inlier threshold"); arg.param("idRobot", idRobot, 0, "robot identifier" ); arg.param("nRobots", nRobots, 1, "number of robots" ); arg.param("angularUpdate", localizationAngularUpdate, M_PI_4, "angular rotation interval for updating the graph, in radians"); arg.param("linearUpdate", localizationLinearUpdate, 0.25, "linear translation interval for updating the graph, in meters"); arg.param("odometryTopic", odometryTopic, "odom", "odometry ROS topic"); arg.param("scanTopic", scanTopic, "scan", "scan ROS topic"); arg.param("odomFrame", odomFrame, "odom", "odom frame"); arg.param("mapFrame", mapFrame, "map", "map frame"); arg.param("baseFrame", baseFrame, "/base_link", "base robot frame"); arg.param("initialPose", initialPose, std::vector<double>(), "Pose of the first vertex in the graph. Usage: -initial_pose 0,0,0"); arg.param("publishMap", publishMap, false, "Publish map"); arg.param("publishGraph", publishGraph, false, "Publish graph"); arg.param("o", outputFilename, "", "file where to save output"); arg.parseArgs(argc, argv); //map parameters float mapResolution = 0.05; float occupiedThreshold = 0.65; float rows = 0; float cols = 0; float gain = 3.0; float squareSize = 0; float angle = M_PI_2; float freeThreshold = 0.196; ros::init(argc, argv, "srslam"); RosHandler rh(idRobot, nRobots, REAL_EXPERIMENT); rh.setOdomTopic(odometryTopic); rh.setScanTopic(scanTopic); rh.setBaseFrame(baseFrame); rh.useOdom(true); rh.useLaser(true); rh.init(); rh.run(); maxRange = rh.getLaserMaxRange(); usableRange = maxRange; //For estimation SE2 currEst; SE2 odomPosk_1 = rh.getOdom(); if (initialPose.size()){ if (initialPose.size()==3){ currEst = SE2(initialPose[0],initialPose[1],initialPose[2]); }else { std::cerr << "Error. Provide a valid initial pose (x, y, theta)" << std::endl; exit(0); } }else{ currEst = odomPosk_1; } std::cout << "My initial position is: " << currEst.translation().x() << " " << currEst.translation().y() << " " << currEst.rotation().angle() << std::endl; std::cout << "My initial odometry is: " << odomPosk_1.translation().x() << " " << odomPosk_1.translation().y() << " " << odomPosk_1.rotation().angle() << std::endl; //Graph building GraphSLAM gslam; gslam.setIdRobot(idRobot); int baseId = 10000; gslam.setBaseId(baseId); gslam.init(resolution, kernelRadius, windowLoopClosure, maxScore, inlierThreshold, minInliers); RobotLaser* rlaser = rh.getLaser(); gslam.setInitialData(currEst, rlaser); cv::Mat occupancyMap; Eigen::Vector2f mapCenter; //Map building Graph2occupancy mapCreator(gslam.graph(), &occupancyMap, currEst, mapResolution, occupiedThreshold, rows, cols, maxRange, usableRange, gain, squareSize, angle, freeThreshold); OccupancyMapServer mapServer(&occupancyMap, idRobot, SIM_EXPERIMENT, mapFrame, occupiedThreshold, freeThreshold); GraphRosPublisher graphPublisher(gslam.graph(), mapFrame, odomFrame); if (publishMap){ mapCreator.computeMap(); mapCenter = mapCreator.getMapCenter(); mapServer.setOffset(mapCenter); mapServer.setResolution(mapResolution); mapServer.publishMapMetaData(); mapServer.publishMap(); } if (publishGraph) graphPublisher.publishGraph(); if (publishMap || publishGraph) graphPublisher.publishMapTransform(gslam.lastVertex()->estimate(), odomPosk_1); //Saving g2o file char buf[100]; sprintf(buf, "robot-%i-%s", idRobot, outputFilename.c_str()); ofstream ofmap(buf); gslam.graph()->saveVertex(ofmap, gslam.lastVertex()); ros::Rate loop_rate(10); while (ros::ok()){ ros::spinOnce(); SE2 odomPosk = rh.getOdom(); //current odometry SE2 relodom = odomPosk_1.inverse() * odomPosk; currEst *= relodom; odomPosk_1 = odomPosk; if((distanceSE2(gslam.lastVertex()->estimate(), currEst) > localizationLinearUpdate) || (fabs(gslam.lastVertex()->estimate().rotation().angle()-currEst.rotation().angle()) > localizationAngularUpdate)){ //Add new data RobotLaser* laseri = rh.getLaser(); gslam.addDataSM(currEst, laseri); gslam.findConstraints(); struct timeval t_ini, t_fin; double secs; gettimeofday(&t_ini, NULL); gslam.optimize(5); gettimeofday(&t_fin, NULL); secs = timeval_diff(&t_fin, &t_ini); printf("Optimization took %.16g milliseconds\n", secs * 1000.0); currEst = gslam.lastVertex()->estimate(); char buf[100]; sprintf(buf, "robot-%i-%s", idRobot, outputFilename.c_str()); gslam.saveGraph(buf); if (publishMap || publishGraph) graphPublisher.publishMapTransform(gslam.lastVertex()->estimate(), odomPosk_1); //Publish graph to visualize it on Rviz if (publishGraph) graphPublisher.publishGraph(); if (publishMap){ //Update map mapCreator.computeMap(); mapCenter = mapCreator.getMapCenter(); mapServer.setOffset(mapCenter); } }else { //Publish map transform with last corrected estimate + odometry drift if (publishMap || publishGraph) graphPublisher.publishMapTransform(currEst, odomPosk_1); } //Publish map if (publishMap){ mapServer.publishMapMetaData(); mapServer.publishMap(); } loop_rate.sleep(); } cerr << "Last Optimization..."; gslam.optimize(5); gslam.saveGraph(buf); cerr << "Done" << endl; return 0; } <|endoftext|>
<commit_before>/* rsspp - Copyright (C) 2008-2012 Andreas Krennmair <ak@newsbeuter.org> * Licensed under the MIT/X Consortium License. See file LICENSE * for more information. */ #include <config.h> #include <rsspp.h> #include <rsspp_internal.h> #include <libxml/parser.h> #include <libxml/tree.h> #include <curl/curl.h> #include <logger.h> #include <utils.h> #include <cstring> #include <utils.h> #include <remote_api.h> using namespace newsbeuter; static size_t my_write_data(void *buffer, size_t size, size_t nmemb, void *userp) { std::string * pbuf = static_cast<std::string *>(userp); pbuf->append(static_cast<const char *>(buffer), size * nmemb); return size * nmemb; } namespace rsspp { parser::parser(unsigned int timeout, const char * user_agent, const char * proxy, const char * proxy_auth, curl_proxytype proxy_type) : to(timeout), ua(user_agent), prx(proxy), prxauth(proxy_auth), prxtype(proxy_type), doc(0), lm(0) { } parser::~parser() { if (doc) xmlFreeDoc(doc); } struct header_values { time_t lastmodified; std::string etag; header_values() : lastmodified(0) { } }; static size_t handle_headers(void * ptr, size_t size, size_t nmemb, void * data) { char * header = new char[size*nmemb + 1]; header_values * values = (header_values *)data; memcpy(header, ptr, size*nmemb); header[size*nmemb] = '\0'; if (!strncasecmp("Last-Modified:", header, 14)) { time_t r = curl_getdate(header+14, NULL); if (r == -1) { LOG(LOG_DEBUG, "handle_headers: last-modified %s (curl_getdate FAILED)", header+14); } else { values->lastmodified = curl_getdate(header+14, NULL); LOG(LOG_DEBUG, "handle_headers: got last-modified %s (%d)", header+14, values->lastmodified); } } else if (!strncasecmp("ETag:",header, 5)) { values->etag = std::string(header+5); utils::trim(values->etag); LOG(LOG_DEBUG, "handle_headers: got etag %s", values->etag.c_str()); } delete[] header; return size * nmemb; } feed parser::parse_url(const std::string& url, time_t lastmodified, const std::string& etag, newsbeuter::remote_api * api, const std::string& cookie_cache, CURL *ehandle) { std::string buf; CURLcode ret; CURL * easyhandle = ehandle; if (!easyhandle) { easyhandle = curl_easy_init(); if (!easyhandle) { throw exception(_("couldn't initialize libcurl")); } } if (ua) { curl_easy_setopt(easyhandle, CURLOPT_USERAGENT, ua); } if (api) { api->configure_handle(easyhandle); } curl_easy_setopt(easyhandle, CURLOPT_URL, url.c_str()); curl_easy_setopt(easyhandle, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, my_write_data); curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &buf); curl_easy_setopt(easyhandle, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(easyhandle, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(easyhandle, CURLOPT_MAXREDIRS, 10); curl_easy_setopt(easyhandle, CURLOPT_FAILONERROR, 1); curl_easy_setopt(easyhandle, CURLOPT_ENCODING, "gzip, deflate"); if (cookie_cache != "") { curl_easy_setopt(easyhandle, CURLOPT_COOKIEFILE, cookie_cache.c_str()); curl_easy_setopt(easyhandle, CURLOPT_COOKIEJAR, cookie_cache.c_str()); } if (to != 0) curl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, to); if (prx) curl_easy_setopt(easyhandle, CURLOPT_PROXY, prx); if (prxauth) { curl_easy_setopt(easyhandle, CURLOPT_PROXYAUTH, CURLAUTH_ANY); curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, prxauth); } curl_easy_setopt(easyhandle, CURLOPT_PROXYTYPE, prxtype); header_values hdrs; curl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs); curl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers); curl_easy_setopt(easyhandle, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE); if (lastmodified != 0) curl_easy_setopt(easyhandle, CURLOPT_TIMEVALUE, lastmodified); else curl_easy_setopt(easyhandle, CURLOPT_TIMEVALUE, 0); curl_slist * custom_headers = NULL; if (etag.length() > 0) { custom_headers = curl_slist_append(custom_headers, utils::strprintf("If-None-Match: %s", etag.c_str()).c_str()); curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, custom_headers); } ret = curl_easy_perform(easyhandle); lm = hdrs.lastmodified; et = hdrs.etag; if (custom_headers) { curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, 0); curl_slist_free_all(custom_headers); } LOG(LOG_DEBUG, "rsspp::parser::parse_url: ret = %d", ret); long status; curl_easy_getinfo(easyhandle, CURLINFO_HTTP_CONNECTCODE, &status); if (status >= 400) { LOG(LOG_USERERROR, _("Error: trying to download feed `%s' returned HTTP status code %ld."), url.c_str(), status); } if (!ehandle) curl_easy_cleanup(easyhandle); if (ret != 0) { LOG(LOG_ERROR, "rsspp::parser::parse_url: curl_easy_perform returned err %d: %s", ret, curl_easy_strerror(ret)); throw exception(curl_easy_strerror(ret)); } LOG(LOG_INFO, "parser::parse_url: retrieved data for %s: %s", url.c_str(), buf.c_str()); if (buf.length() > 0) { LOG(LOG_DEBUG, "parser::parse_url: handing over data to parse_buffer()"); return parse_buffer(buf.c_str(), buf.length(), url.c_str()); } return feed(); } feed parser::parse_buffer(const char * buffer, size_t size, const char * url) { doc = xmlReadMemory(buffer, size, url, NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING); if (doc == NULL) { throw exception(_("could not parse buffer")); } xmlNode* root_element = xmlDocGetRootElement(doc); feed f = parse_xmlnode(root_element); if (doc->encoding) { f.encoding = (const char *)doc->encoding; } LOG(LOG_INFO, "parser::parse_buffer: encoding = %s", f.encoding.c_str()); return f; } feed parser::parse_file(const std::string& filename) { doc = xmlReadFile(filename.c_str(), NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING); if (doc == NULL) { throw exception(_("could not parse file")); } xmlNode* root_element = xmlDocGetRootElement(doc); feed f = parse_xmlnode(root_element); if (doc->encoding) { f.encoding = (const char *)doc->encoding; } LOG(LOG_INFO, "parser::parse_file: encoding = %s", f.encoding.c_str()); return f; } feed parser::parse_xmlnode(xmlNode* node) { feed f; if (node) { if (node->name && node->type == XML_ELEMENT_NODE) { if (strcmp((const char *)node->name, "rss")==0) { const char * version = (const char *)xmlGetProp(node, (const xmlChar *)"version"); if (!version) { xmlFree((void *)version); throw exception(_("no RSS version")); } if (strcmp(version, "0.91")==0) f.rss_version = RSS_0_91; else if (strcmp(version, "0.92")==0) f.rss_version = RSS_0_92; else if (strcmp(version, "0.94")==0) f.rss_version = RSS_0_94; else if (strcmp(version, "2.0")==0 || strcmp(version, "2")==0) f.rss_version = RSS_2_0; else { xmlFree((void *)version); throw exception(_("invalid RSS version")); } xmlFree((void *)version); } else if (strcmp((const char *)node->name, "RDF")==0) { f.rss_version = RSS_1_0; } else if (strcmp((const char *)node->name, "feed")==0) { if (node->ns && node->ns->href) { if (strcmp((const char *)node->ns->href, ATOM_0_3_URI)==0) { f.rss_version = ATOM_0_3; } else if (strcmp((const char *)node->ns->href, ATOM_1_0_URI)==0) { f.rss_version = ATOM_1_0; } else { const char * version = (const char *)xmlGetProp(node, (const xmlChar *)"version"); if (!version) { xmlFree((void *)version); throw exception(_("invalid Atom version")); } if (strcmp(version, "0.3")==0) { xmlFree((void *)version); f.rss_version = ATOM_0_3_NONS; } else { xmlFree((void *)version); throw exception(_("invalid Atom version")); } } } else { throw exception(_("no Atom version")); } } std::tr1::shared_ptr<rss_parser> parser = rss_parser_factory::get_object(f, doc); try { parser->parse_feed(f, node); } catch (exception& e) { throw; } } } else { throw exception(_("XML root node is NULL")); } return f; } void parser::global_init() { LIBXML_TEST_VERSION curl_global_init(CURL_GLOBAL_ALL); } void parser::global_cleanup() { xmlCleanupParser(); curl_global_cleanup(); } } <commit_msg>only set If-Modified-Since header if lastmodified != 0.<commit_after>/* rsspp - Copyright (C) 2008-2012 Andreas Krennmair <ak@newsbeuter.org> * Licensed under the MIT/X Consortium License. See file LICENSE * for more information. */ #include <config.h> #include <rsspp.h> #include <rsspp_internal.h> #include <libxml/parser.h> #include <libxml/tree.h> #include <curl/curl.h> #include <logger.h> #include <utils.h> #include <cstring> #include <utils.h> #include <remote_api.h> using namespace newsbeuter; static size_t my_write_data(void *buffer, size_t size, size_t nmemb, void *userp) { std::string * pbuf = static_cast<std::string *>(userp); pbuf->append(static_cast<const char *>(buffer), size * nmemb); return size * nmemb; } namespace rsspp { parser::parser(unsigned int timeout, const char * user_agent, const char * proxy, const char * proxy_auth, curl_proxytype proxy_type) : to(timeout), ua(user_agent), prx(proxy), prxauth(proxy_auth), prxtype(proxy_type), doc(0), lm(0) { } parser::~parser() { if (doc) xmlFreeDoc(doc); } struct header_values { time_t lastmodified; std::string etag; header_values() : lastmodified(0) { } }; static size_t handle_headers(void * ptr, size_t size, size_t nmemb, void * data) { char * header = new char[size*nmemb + 1]; header_values * values = (header_values *)data; memcpy(header, ptr, size*nmemb); header[size*nmemb] = '\0'; if (!strncasecmp("Last-Modified:", header, 14)) { time_t r = curl_getdate(header+14, NULL); if (r == -1) { LOG(LOG_DEBUG, "handle_headers: last-modified %s (curl_getdate FAILED)", header+14); } else { values->lastmodified = curl_getdate(header+14, NULL); LOG(LOG_DEBUG, "handle_headers: got last-modified %s (%d)", header+14, values->lastmodified); } } else if (!strncasecmp("ETag:",header, 5)) { values->etag = std::string(header+5); utils::trim(values->etag); LOG(LOG_DEBUG, "handle_headers: got etag %s", values->etag.c_str()); } delete[] header; return size * nmemb; } feed parser::parse_url(const std::string& url, time_t lastmodified, const std::string& etag, newsbeuter::remote_api * api, const std::string& cookie_cache, CURL *ehandle) { std::string buf; CURLcode ret; CURL * easyhandle = ehandle; if (!easyhandle) { easyhandle = curl_easy_init(); if (!easyhandle) { throw exception(_("couldn't initialize libcurl")); } } if (ua) { curl_easy_setopt(easyhandle, CURLOPT_USERAGENT, ua); } if (api) { api->configure_handle(easyhandle); } curl_easy_setopt(easyhandle, CURLOPT_URL, url.c_str()); curl_easy_setopt(easyhandle, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, my_write_data); curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &buf); curl_easy_setopt(easyhandle, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(easyhandle, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(easyhandle, CURLOPT_MAXREDIRS, 10); curl_easy_setopt(easyhandle, CURLOPT_FAILONERROR, 1); curl_easy_setopt(easyhandle, CURLOPT_ENCODING, "gzip, deflate"); if (cookie_cache != "") { curl_easy_setopt(easyhandle, CURLOPT_COOKIEFILE, cookie_cache.c_str()); curl_easy_setopt(easyhandle, CURLOPT_COOKIEJAR, cookie_cache.c_str()); } if (to != 0) curl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, to); if (prx) curl_easy_setopt(easyhandle, CURLOPT_PROXY, prx); if (prxauth) { curl_easy_setopt(easyhandle, CURLOPT_PROXYAUTH, CURLAUTH_ANY); curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, prxauth); } curl_easy_setopt(easyhandle, CURLOPT_PROXYTYPE, prxtype); header_values hdrs; curl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs); curl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers); if (lastmodified != 0) { curl_easy_setopt(easyhandle, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE); curl_easy_setopt(easyhandle, CURLOPT_TIMEVALUE, lastmodified); } curl_slist * custom_headers = NULL; if (etag.length() > 0) { custom_headers = curl_slist_append(custom_headers, utils::strprintf("If-None-Match: %s", etag.c_str()).c_str()); curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, custom_headers); } ret = curl_easy_perform(easyhandle); lm = hdrs.lastmodified; et = hdrs.etag; if (custom_headers) { curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, 0); curl_slist_free_all(custom_headers); } LOG(LOG_DEBUG, "rsspp::parser::parse_url: ret = %d", ret); long status; curl_easy_getinfo(easyhandle, CURLINFO_HTTP_CONNECTCODE, &status); if (status >= 400) { LOG(LOG_USERERROR, _("Error: trying to download feed `%s' returned HTTP status code %ld."), url.c_str(), status); } if (!ehandle) curl_easy_cleanup(easyhandle); if (ret != 0) { LOG(LOG_ERROR, "rsspp::parser::parse_url: curl_easy_perform returned err %d: %s", ret, curl_easy_strerror(ret)); throw exception(curl_easy_strerror(ret)); } LOG(LOG_INFO, "parser::parse_url: retrieved data for %s: %s", url.c_str(), buf.c_str()); if (buf.length() > 0) { LOG(LOG_DEBUG, "parser::parse_url: handing over data to parse_buffer()"); return parse_buffer(buf.c_str(), buf.length(), url.c_str()); } return feed(); } feed parser::parse_buffer(const char * buffer, size_t size, const char * url) { doc = xmlReadMemory(buffer, size, url, NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING); if (doc == NULL) { throw exception(_("could not parse buffer")); } xmlNode* root_element = xmlDocGetRootElement(doc); feed f = parse_xmlnode(root_element); if (doc->encoding) { f.encoding = (const char *)doc->encoding; } LOG(LOG_INFO, "parser::parse_buffer: encoding = %s", f.encoding.c_str()); return f; } feed parser::parse_file(const std::string& filename) { doc = xmlReadFile(filename.c_str(), NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING); if (doc == NULL) { throw exception(_("could not parse file")); } xmlNode* root_element = xmlDocGetRootElement(doc); feed f = parse_xmlnode(root_element); if (doc->encoding) { f.encoding = (const char *)doc->encoding; } LOG(LOG_INFO, "parser::parse_file: encoding = %s", f.encoding.c_str()); return f; } feed parser::parse_xmlnode(xmlNode* node) { feed f; if (node) { if (node->name && node->type == XML_ELEMENT_NODE) { if (strcmp((const char *)node->name, "rss")==0) { const char * version = (const char *)xmlGetProp(node, (const xmlChar *)"version"); if (!version) { xmlFree((void *)version); throw exception(_("no RSS version")); } if (strcmp(version, "0.91")==0) f.rss_version = RSS_0_91; else if (strcmp(version, "0.92")==0) f.rss_version = RSS_0_92; else if (strcmp(version, "0.94")==0) f.rss_version = RSS_0_94; else if (strcmp(version, "2.0")==0 || strcmp(version, "2")==0) f.rss_version = RSS_2_0; else { xmlFree((void *)version); throw exception(_("invalid RSS version")); } xmlFree((void *)version); } else if (strcmp((const char *)node->name, "RDF")==0) { f.rss_version = RSS_1_0; } else if (strcmp((const char *)node->name, "feed")==0) { if (node->ns && node->ns->href) { if (strcmp((const char *)node->ns->href, ATOM_0_3_URI)==0) { f.rss_version = ATOM_0_3; } else if (strcmp((const char *)node->ns->href, ATOM_1_0_URI)==0) { f.rss_version = ATOM_1_0; } else { const char * version = (const char *)xmlGetProp(node, (const xmlChar *)"version"); if (!version) { xmlFree((void *)version); throw exception(_("invalid Atom version")); } if (strcmp(version, "0.3")==0) { xmlFree((void *)version); f.rss_version = ATOM_0_3_NONS; } else { xmlFree((void *)version); throw exception(_("invalid Atom version")); } } } else { throw exception(_("no Atom version")); } } std::tr1::shared_ptr<rss_parser> parser = rss_parser_factory::get_object(f, doc); try { parser->parse_feed(f, node); } catch (exception& e) { throw; } } } else { throw exception(_("XML root node is NULL")); } return f; } void parser::global_init() { LIBXML_TEST_VERSION curl_global_init(CURL_GLOBAL_ALL); } void parser::global_cleanup() { xmlCleanupParser(); curl_global_cleanup(); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbMultiChannelExtractROI.h" #include "otbStreamingShrinkImageFilter.h" namespace otb { namespace Wrapper { class Quicklook : public Application { public: /** Standard class typedefs. */ typedef Quicklook Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(Quicklook, otb::Application); /** Typedefs */ typedef float InputPixelType; typedef float OutputPixelType; typedef otb::MultiChannelExtractROI< InputPixelType, OutputPixelType > ExtractROIFilterType; typedef ExtractROIFilterType::InputImageType InputImageType; typedef ExtractROIFilterType::OutputImageType OutputImageType; typedef otb::StreamingShrinkImageFilter <ExtractROIFilterType::OutputImageType, ExtractROIFilterType::OutputImageType> ShrinkImageFilterType; private: void DoInit() ITK_OVERRIDE { SetName("Quicklook"); SetDescription("Generates a subsampled version of an image extract"); SetDocName("Quick Look"); SetDocLongDescription("Generates a subsampled version of an extract of an image defined by ROIStart and ROISize.\n " "This extract is subsampled using the ratio OR the output image Size."); SetDocLimitations(" This application does not provide yet the optimal way to decode coarser level of resolution from JPEG2000 images (like in Monteverdi).\n" "Trying to subsampled huge JPEG200 image with the application will lead to poor performances for now."); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); AddDocTag(Tags::Manip); AddParameter(ParameterType_InputImage, "in", "Input Image"); SetParameterDescription( "in", "The image to read" ); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription( "out" , "The subsampled image" ); AddParameter(ParameterType_ListView, "cl", "Channel List"); SetParameterDescription( "cl" , "Selected channels" ); MandatoryOff("cl"); AddParameter(ParameterType_Int, "rox", "ROI Origin X"); SetParameterDescription( "rox" , "first point of ROI in x-direction" ); MandatoryOff("rox"); AddParameter(ParameterType_Int, "roy", "ROI Origin Y"); SetParameterDescription( "roy" , "first point of ROI in y-direction" ); MandatoryOff("roy"); AddParameter(ParameterType_Int, "rsx", "ROI Size X"); SetParameterDescription( "rsx" , "size of ROI in x-direction" ); MandatoryOff("rsx"); AddParameter(ParameterType_Int, "rsy", "ROI Size Y"); SetParameterDescription( "rsy" , "size of ROI in y-direction" ); MandatoryOff("rsy"); AddParameter(ParameterType_Int, "sr", "Sampling ratio"); SetParameterDescription( "sr" , "Sampling Ratio, default is 2" ); SetDefaultParameterInt("sr", 2); SetMinimumParameterIntValue("sr", 1); MandatoryOff("sr"); AddParameter(ParameterType_Int, "sx", "Size X"); SetParameterDescription( "sx" , "quicklook size in x-direction (used if no sampling ration is given)" ); MandatoryOff("sx"); DisableParameter("sx"); AddParameter(ParameterType_Int, "sy", "Size Y"); SetParameterDescription( "sy" , "quicklook size in y-direction (used if no sampling ration is given)" ); MandatoryOff("sy"); DisableParameter("sy"); SetDefaultParameterInt("rox", 0); SetDefaultParameterInt("roy", 0); SetDefaultParameterInt("rsx", 0); SetDefaultParameterInt("rsy", 0); // Doc example parameter settings SetDocExampleParameterValue("in", "qb_RoadExtract.tif"); SetDocExampleParameterValue("out", "quicklookImage.tif"); SetOfficialDocLink(); } void DoUpdateParameters() ITK_OVERRIDE { // Update the sizes only if the user does not defined a size if ( HasValue("in") ) { InputImageType::Pointer inImage = GetParameterImage("in"); InputImageType::RegionType largestRegion = inImage->GetLargestPossibleRegion(); // Update the values of the channels to be selected unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel(); if (nbComponents != GetChoiceKeys("cl").size()) { ClearChoices("cl"); for (unsigned int idx = 0; idx < nbComponents; ++idx) { std::ostringstream key, item; key<<"cl.channel"<<idx+1; item<<"Channel"<<idx+1; AddChoice(key.str(), item.str()); } } if (!HasUserValue("rsx") && !HasUserValue("rsy") ) { SetParameterInt("rsx",largestRegion.GetSize()[0]); SetParameterInt("rsy",largestRegion.GetSize()[1]); } // Put the limit of the index and the size relative the image SetMinimumParameterIntValue("rsx", 0); SetMaximumParameterIntValue("rsx", largestRegion.GetSize(0)); SetMinimumParameterIntValue("rsy", 0); SetMaximumParameterIntValue("rsy", largestRegion.GetSize(1)); SetMinimumParameterIntValue("rox", 0); SetMaximumParameterIntValue("rox", largestRegion.GetSize(0)-1); SetMinimumParameterIntValue("roy", 0); SetMaximumParameterIntValue("roy", largestRegion.GetSize(1)-1); // Crop the roi region to be included in the largest possible // region if(!this->CropRegionOfInterest()) { // Put the index of the ROI to origin and try to crop again SetParameterInt("rox",0); SetParameterInt("roy",0); this->CropRegionOfInterest(); } } } bool CropRegionOfInterest() { FloatVectorImageType::RegionType region; region.SetSize(0, GetParameterInt("rsx")); region.SetSize(1, GetParameterInt("rsy")); region.SetIndex(0, GetParameterInt("rox")); region.SetIndex(1, GetParameterInt("roy")); if ( HasValue("in") ) { if (region.Crop(GetParameterImage("in")->GetLargestPossibleRegion())) { SetParameterInt( "rsx", region.GetSize(0)); SetParameterInt( "rsy", region.GetSize(1)); SetParameterInt( "rox", region.GetIndex(0)); SetParameterInt( "roy", region.GetIndex(1)); return true; } } return false; } void DoExecute() ITK_OVERRIDE { InputImageType::Pointer inImage = GetParameterImage("in"); m_ExtractROIFilter = ExtractROIFilterType::New(); m_ResamplingFilter = ShrinkImageFilterType::New(); // The image on which the quicklook will be generated // Will eventually be the m_ExtractROIFilter output if (HasUserValue("rox") || HasUserValue("roy") || HasUserValue("rsx") || HasUserValue("rsy") || (GetSelectedItems("cl").size() > 0)) { m_ExtractROIFilter->SetInput(inImage); m_ExtractROIFilter->SetStartX(GetParameterInt("rox")); m_ExtractROIFilter->SetStartY(GetParameterInt("roy")); m_ExtractROIFilter->SetSizeX(GetParameterInt("rsx")); m_ExtractROIFilter->SetSizeY(GetParameterInt("rsy")); if ((GetSelectedItems("cl").size() > 0)) { for (unsigned int idx = 0; idx < GetSelectedItems("cl").size(); ++idx) { m_ExtractROIFilter->SetChannel(GetSelectedItems("cl")[idx] + 1 ); } } else { unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel(); for (unsigned int idx = 0; idx < nbComponents; ++idx) { m_ExtractROIFilter->SetChannel(idx + 1); } } m_ResamplingFilter->SetInput( m_ExtractROIFilter->GetOutput() ); } else { m_ResamplingFilter->SetInput(inImage); } unsigned int Ratio = static_cast<unsigned int>(GetParameterInt("sr")); unsigned int SamplingRatioX = 1; unsigned int SamplingRatioY = 1; if ( !HasUserValue("sr") ) { if ( IsParameterEnabled("sx") && IsParameterEnabled("sy") ) { SamplingRatioX = GetParameterInt("rsx") / GetParameterInt("sx"); SamplingRatioY = GetParameterInt("rsy") / GetParameterInt("sy"); if (SamplingRatioX > Ratio) Ratio = SamplingRatioX; if (SamplingRatioY > Ratio) Ratio = SamplingRatioY; } else { if ( IsParameterEnabled("sx") ) { Ratio = GetParameterInt("rsx") / GetParameterInt("sx"); } if ( IsParameterEnabled("sy") ) { Ratio = GetParameterInt("rsy") / GetParameterInt("sy"); } } } if ( Ratio < 1) { otbAppLogFATAL( << "Error in SizeX and/or SizeY : ratio must be greater than 1."); return; } otbAppLogINFO( << "Ratio used: "<<Ratio << "."); m_ResamplingFilter->SetShrinkFactor( Ratio ); m_ResamplingFilter->Update(); SetParameterOutputImage("out", m_ResamplingFilter->GetOutput()); } ExtractROIFilterType::Pointer m_ExtractROIFilter; ShrinkImageFilterType::Pointer m_ResamplingFilter; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::Quicklook) <commit_msg>BUG: only modify parameters if different<commit_after>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbMultiChannelExtractROI.h" #include "otbStreamingShrinkImageFilter.h" namespace otb { namespace Wrapper { class Quicklook : public Application { public: /** Standard class typedefs. */ typedef Quicklook Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(Quicklook, otb::Application); /** Typedefs */ typedef float InputPixelType; typedef float OutputPixelType; typedef otb::MultiChannelExtractROI< InputPixelType, OutputPixelType > ExtractROIFilterType; typedef ExtractROIFilterType::InputImageType InputImageType; typedef ExtractROIFilterType::OutputImageType OutputImageType; typedef otb::StreamingShrinkImageFilter <ExtractROIFilterType::OutputImageType, ExtractROIFilterType::OutputImageType> ShrinkImageFilterType; private: void DoInit() ITK_OVERRIDE { SetName("Quicklook"); SetDescription("Generates a subsampled version of an image extract"); SetDocName("Quick Look"); SetDocLongDescription("Generates a subsampled version of an extract of an image defined by ROIStart and ROISize.\n " "This extract is subsampled using the ratio OR the output image Size."); SetDocLimitations(" This application does not provide yet the optimal way to decode coarser level of resolution from JPEG2000 images (like in Monteverdi).\n" "Trying to subsampled huge JPEG200 image with the application will lead to poor performances for now."); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); AddDocTag(Tags::Manip); AddParameter(ParameterType_InputImage, "in", "Input Image"); SetParameterDescription( "in", "The image to read" ); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription( "out" , "The subsampled image" ); AddParameter(ParameterType_ListView, "cl", "Channel List"); SetParameterDescription( "cl" , "Selected channels" ); MandatoryOff("cl"); AddParameter(ParameterType_Int, "rox", "ROI Origin X"); SetParameterDescription( "rox" , "first point of ROI in x-direction" ); MandatoryOff("rox"); AddParameter(ParameterType_Int, "roy", "ROI Origin Y"); SetParameterDescription( "roy" , "first point of ROI in y-direction" ); MandatoryOff("roy"); AddParameter(ParameterType_Int, "rsx", "ROI Size X"); SetParameterDescription( "rsx" , "size of ROI in x-direction" ); MandatoryOff("rsx"); AddParameter(ParameterType_Int, "rsy", "ROI Size Y"); SetParameterDescription( "rsy" , "size of ROI in y-direction" ); MandatoryOff("rsy"); AddParameter(ParameterType_Int, "sr", "Sampling ratio"); SetParameterDescription( "sr" , "Sampling Ratio, default is 2" ); SetDefaultParameterInt("sr", 2); SetMinimumParameterIntValue("sr", 1); MandatoryOff("sr"); AddParameter(ParameterType_Int, "sx", "Size X"); SetParameterDescription( "sx" , "quicklook size in x-direction (used if no sampling ration is given)" ); MandatoryOff("sx"); DisableParameter("sx"); AddParameter(ParameterType_Int, "sy", "Size Y"); SetParameterDescription( "sy" , "quicklook size in y-direction (used if no sampling ration is given)" ); MandatoryOff("sy"); DisableParameter("sy"); SetDefaultParameterInt("rox", 0); SetDefaultParameterInt("roy", 0); SetDefaultParameterInt("rsx", 0); SetDefaultParameterInt("rsy", 0); // Doc example parameter settings SetDocExampleParameterValue("in", "qb_RoadExtract.tif"); SetDocExampleParameterValue("out", "quicklookImage.tif"); SetOfficialDocLink(); } void DoUpdateParameters() ITK_OVERRIDE { // Update the sizes only if the user does not defined a size if ( HasValue("in") ) { InputImageType::Pointer inImage = GetParameterImage("in"); InputImageType::RegionType largestRegion = inImage->GetLargestPossibleRegion(); // Update the values of the channels to be selected unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel(); if (nbComponents != GetChoiceKeys("cl").size()) { ClearChoices("cl"); for (unsigned int idx = 0; idx < nbComponents; ++idx) { std::ostringstream key, item; key<<"cl.channel"<<idx+1; item<<"Channel"<<idx+1; AddChoice(key.str(), item.str()); } } if (!HasUserValue("rsx") && !HasUserValue("rsy") ) { SetParameterInt("rsx",largestRegion.GetSize()[0]); SetParameterInt("rsy",largestRegion.GetSize()[1]); } // Put the limit of the index and the size relative the image SetMinimumParameterIntValue("rsx", 0); SetMaximumParameterIntValue("rsx", largestRegion.GetSize(0)); SetMinimumParameterIntValue("rsy", 0); SetMaximumParameterIntValue("rsy", largestRegion.GetSize(1)); SetMinimumParameterIntValue("rox", 0); SetMaximumParameterIntValue("rox", largestRegion.GetSize(0)-1); SetMinimumParameterIntValue("roy", 0); SetMaximumParameterIntValue("roy", largestRegion.GetSize(1)-1); // Crop the roi region to be included in the largest possible // region if(!this->CropRegionOfInterest()) { // Put the index of the ROI to origin and try to crop again SetParameterInt("rox",0); SetParameterInt("roy",0); this->CropRegionOfInterest(); } } } bool CropRegionOfInterest() { FloatVectorImageType::RegionType region; region.SetSize(0, GetParameterInt("rsx")); region.SetSize(1, GetParameterInt("rsy")); region.SetIndex(0, GetParameterInt("rox")); region.SetIndex(1, GetParameterInt("roy")); FloatVectorImageType::RegionType region0 = region; if ( HasValue("in") ) { if (region.Crop(GetParameterImage("in")->GetLargestPossibleRegion())) { if (region0.GetSize(0) != region.GetSize(0)) SetParameterInt( "rsx", region.GetSize(0)); if (region0.GetSize(1) != region.GetSize(1)) SetParameterInt( "rsy", region.GetSize(1)); if (region0.GetIndex(0) != region.GetIndex(0)) SetParameterInt( "rox", region.GetIndex(0)); if (region0.GetIndex(1) != region.GetIndex(1)) SetParameterInt( "roy", region.GetIndex(1)); return true; } } return false; } void DoExecute() ITK_OVERRIDE { InputImageType::Pointer inImage = GetParameterImage("in"); m_ExtractROIFilter = ExtractROIFilterType::New(); m_ResamplingFilter = ShrinkImageFilterType::New(); // The image on which the quicklook will be generated // Will eventually be the m_ExtractROIFilter output if (HasUserValue("rox") || HasUserValue("roy") || HasUserValue("rsx") || HasUserValue("rsy") || (GetSelectedItems("cl").size() > 0)) { m_ExtractROIFilter->SetInput(inImage); m_ExtractROIFilter->SetStartX(GetParameterInt("rox")); m_ExtractROIFilter->SetStartY(GetParameterInt("roy")); m_ExtractROIFilter->SetSizeX(GetParameterInt("rsx")); m_ExtractROIFilter->SetSizeY(GetParameterInt("rsy")); if ((GetSelectedItems("cl").size() > 0)) { for (unsigned int idx = 0; idx < GetSelectedItems("cl").size(); ++idx) { m_ExtractROIFilter->SetChannel(GetSelectedItems("cl")[idx] + 1 ); } } else { unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel(); for (unsigned int idx = 0; idx < nbComponents; ++idx) { m_ExtractROIFilter->SetChannel(idx + 1); } } m_ResamplingFilter->SetInput( m_ExtractROIFilter->GetOutput() ); } else { m_ResamplingFilter->SetInput(inImage); } unsigned int Ratio = static_cast<unsigned int>(GetParameterInt("sr")); unsigned int SamplingRatioX = 1; unsigned int SamplingRatioY = 1; if ( !HasUserValue("sr") ) { if ( IsParameterEnabled("sx") && IsParameterEnabled("sy") ) { SamplingRatioX = GetParameterInt("rsx") / GetParameterInt("sx"); SamplingRatioY = GetParameterInt("rsy") / GetParameterInt("sy"); if (SamplingRatioX > Ratio) Ratio = SamplingRatioX; if (SamplingRatioY > Ratio) Ratio = SamplingRatioY; } else { if ( IsParameterEnabled("sx") ) { Ratio = GetParameterInt("rsx") / GetParameterInt("sx"); } if ( IsParameterEnabled("sy") ) { Ratio = GetParameterInt("rsy") / GetParameterInt("sy"); } } } if ( Ratio < 1) { otbAppLogFATAL( << "Error in SizeX and/or SizeY : ratio must be greater than 1."); return; } otbAppLogINFO( << "Ratio used: "<<Ratio << "."); m_ResamplingFilter->SetShrinkFactor( Ratio ); m_ResamplingFilter->Update(); SetParameterOutputImage("out", m_ResamplingFilter->GetOutput()); } ExtractROIFilterType::Pointer m_ExtractROIFilter; ShrinkImageFilterType::Pointer m_ResamplingFilter; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::Quicklook) <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "linenoise/linenoise.h" #include "raptor.h" #include "routing/raptor_api.h" #include "type/data.h" #include "utils/timer.h" #include "type/response.pb.h" #include "routing_cli_utils.h" #include "ptreferential/ptreferential_api.h" #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include "type/pb_converter.h" namespace nr = navitia::routing; namespace nt = navitia::type; namespace bt = boost::posix_time; namespace po = boost::program_options ; namespace pb = pbnavitia; void completion(const char *buf, linenoiseCompletions *lc) { if (buf[0] == 'j' || buf[0] == '\0') { linenoiseAddCompletion(lc,"journey"); } if (buf[0] == 'p' || buf[0] == '\0') { linenoiseAddCompletion(lc,"ptref"); } } int main(int argc, char **argv) { if (argc < 2) { std::cerr << "A filename is needed" << std::endl; return 1; } std::string start, target, date; nt::Data data; data.load(std::string(argv[1])); navitia::cli::compute_options compute_opt; po::variables_map vm; char *line; nr::RAPTOR raptor(data); /* Parse options, with --multiline we enable multi line editing. */ linenoiseSetCompletionCallback(completion); linenoiseHistoryLoad("history.txt"); /* Load the history at startup */ while((line = linenoise("hello> ")) != NULL) { linenoiseHistoryAdd(line); linenoiseHistorySave("history.txt"); std::string str_line(line); auto splitted_line = po::split_unix(str_line); if (splitted_line.empty()) { continue; } if (splitted_line[0] == "journey") { po::store(po::command_line_parser(splitted_line).options(compute_opt.desc).run(), vm); po::notify(vm); compute_opt.compute(vm, raptor); } else if (splitted_line[0] == "ptref") { if (splitted_line.size() < 2) { std::cerr << "an ID is needed" << std::endl; } const std::string id = splitted_line[1]; #define SHOW_ID_CLI(type_name, collection_name) \ auto collection_name##_map = data.pt_data->collection_name##_map;\ if ( collection_name##_map.find(id) != collection_name##_map.end()) {\ pbnavitia::type_name p;\ navitia::fill_pb_object(collection_name##_map.at(id), data, &p);\ std::cout << p.DebugString() << std::endl;} ITERATE_NAVITIA_PT_TYPES(SHOW_ID_CLI) } } return 0; } <commit_msg>Cli: add comment<commit_after>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "linenoise/linenoise.h" #include "raptor.h" #include "routing/raptor_api.h" #include "type/data.h" #include "utils/timer.h" #include "type/response.pb.h" #include "routing_cli_utils.h" #include "ptreferential/ptreferential_api.h" #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include "type/pb_converter.h" namespace nr = navitia::routing; namespace nt = navitia::type; namespace bt = boost::posix_time; namespace po = boost::program_options ; namespace pb = pbnavitia; void completion(const char *buf, linenoiseCompletions *lc) { if (buf[0] == 'j' || buf[0] == '\0') { linenoiseAddCompletion(lc,"journey"); } if (buf[0] == 'p' || buf[0] == '\0') { linenoiseAddCompletion(lc,"ptref"); } } /* This program takes a path to a nav.lz4 navitia's file * It will be loaded at the begginning of the program */ int main(int argc, char **argv) { if (argc < 2) { std::cerr << "A filename is needed" << std::endl; return 1; } std::string start, target, date; nt::Data data; data.load(std::string(argv[1])); navitia::cli::compute_options compute_opt; po::variables_map vm; char *line; nr::RAPTOR raptor(data); /* Parse options, with --multiline we enable multi line editing. */ linenoiseSetCompletionCallback(completion); linenoiseHistoryLoad("history.txt"); /* Load the history at startup */ while((line = linenoise("hello> ")) != NULL) { linenoiseHistoryAdd(line); linenoiseHistorySave("history.txt"); std::string str_line(line); auto splitted_line = po::split_unix(str_line); if (splitted_line.empty()) { continue; } if (splitted_line[0] == "journey") { po::store(po::command_line_parser(splitted_line).options(compute_opt.desc).run(), vm); po::notify(vm); compute_opt.compute(vm, raptor); } else if (splitted_line[0] == "ptref") { if (splitted_line.size() < 2) { std::cerr << "an ID is needed" << std::endl; } const std::string id = splitted_line[1]; #define SHOW_ID_CLI(type_name, collection_name) \ auto collection_name##_map = data.pt_data->collection_name##_map;\ if ( collection_name##_map.find(id) != collection_name##_map.end()) {\ pbnavitia::type_name p;\ navitia::fill_pb_object(collection_name##_map.at(id), data, &p);\ std::cout << p.DebugString() << std::endl;} ITERATE_NAVITIA_PT_TYPES(SHOW_ID_CLI) } } return 0; } <|endoftext|>
<commit_before><commit_msg>coverity#1130457 Uncaught exception<commit_after><|endoftext|>
<commit_before>// [WriteFile Name=ExportTiles, Category=Layers] // [Legal] // Copyright 2016 Esri. // 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. // [Legal] #include "ExportTiles.h" #include <QUrl> #include "Map.h" #include "MapQuickView.h" #include "Basemap.h" #include "ExportTiles.h" #include "ArcGISTiledLayer.h" #include "ExportTileCacheTask.h" #include "Envelope.h" #include "GeometryEngine.h" #include "SpatialReference.h" #include "TileCache.h" using namespace Esri::ArcGISRuntime; ExportTiles::ExportTiles(QQuickItem* parent) : QQuickItem(parent), m_map(nullptr), m_mapView(nullptr), m_serviceUrl("http://sampleserver6.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer"), m_exportTileCacheTask(nullptr) { } ExportTiles::~ExportTiles() { } void ExportTiles::componentComplete() { QQuickItem::componentComplete(); // find QML MapView component m_mapView = findChild<MapQuickView*>("mapView"); // create a tiled basemap ArcGISTiledLayer* tiledLayer = new ArcGISTiledLayer(m_serviceUrl); Basemap* basemap = new Basemap(tiledLayer, this); // create a new map instance m_map = new Map(basemap, this); // set an initial viewpoint Envelope env(12362601, 936021, 10187678, 2567213, SpatialReference(3857)); Viewpoint viewpoint(env); m_map->setInitialViewpoint(viewpoint); // set map on the map view m_mapView->setMap(m_map); // create the task from the tiled layer's map service info once it is loaded connect(tiledLayer, &ArcGISTiledLayer::doneLoading, [this, tiledLayer](Error) { m_exportTileCacheTask = new ExportTileCacheTask(tiledLayer->mapServiceInfo(), this); }); } void ExportTiles::exportTileCacheFromCorners(double xCorner1, double yCorner1, double xCorner2, double yCorner2, QString dataPath) { // create an envelope from the QML rectangle corners auto corner1 = m_mapView->screenToLocation(xCorner1, yCorner1); auto corner2 = m_mapView->screenToLocation(xCorner2, yCorner2); auto extent = Envelope(corner1, corner2); auto tileCacheExtent = GeometryEngine::project(extent, SpatialReference::webMercator()); // connect to sync task doneLoading signal connect(m_exportTileCacheTask, &ExportTileCacheTask::defaultExportTileCacheParametersCompleted, [this, &dataPath](QUuid, ExportTileCacheParameters parameters) { m_parameters = parameters; // execute the task and obtain the job auto exportJob = m_exportTileCacheTask->exportTileCache(m_parameters, dataPath); // check if there is a valid job if (exportJob) { // connect to the job's status changed signal connect(exportJob, &ExportTileCacheJob::jobStatusChanged, [this, exportJob]() { // connect to the job's status changed signal to know once it is done switch (exportJob->jobStatus()) { case JobStatus::Failed: emit updateStatus("Export failed"); emit hideWindow(5000, false); break; case JobStatus::NotStarted: emit updateStatus("Job not started"); break; case JobStatus::Paused: emit updateStatus("Job paused"); break; case JobStatus::Started: emit updateStatus("In progress..."); break; case JobStatus::Succeeded: emit updateStatus("Adding TPK..."); emit hideWindow(1500, true); displayOutputTileCache(exportJob->result()); break; default: break; } }); // start the export job exportJob->start(); } else { emit updateStatus("Export failed"); emit hideWindow(5000, false); } }); // generate parameters m_exportTileCacheTask->createDefaultExportTileCacheParameters(tileCacheExtent, m_mapView->mapScale(), m_exportTileCacheTask->mapServiceInfo().maxScale()); } // display the tile cache once the task is complete void ExportTiles::displayOutputTileCache(TileCache* tileCache) { // create a new tiled layer from the output tile cache auto tiledLayer = new ArcGISTiledLayer(tileCache, this); // add the new layer to a basemap auto basemap = new Basemap(tiledLayer, this); // set the new basemap on the map m_map->setBasemap(basemap); // zoom to the new layer and hide window once loaded connect(tiledLayer, &ArcGISTiledLayer::doneLoading, [this, tiledLayer]() { if (tiledLayer->loadStatus() == LoadStatus::Loaded) { m_mapView->setViewpointScale(m_mapView->mapScale() * 0.5); } }); } <commit_msg>Fix ExportTiles connection to take by val<commit_after>// [WriteFile Name=ExportTiles, Category=Layers] // [Legal] // Copyright 2016 Esri. // 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. // [Legal] #include "ExportTiles.h" #include <QUrl> #include "Map.h" #include "MapQuickView.h" #include "Basemap.h" #include "ExportTiles.h" #include "ArcGISTiledLayer.h" #include "ExportTileCacheTask.h" #include "Envelope.h" #include "GeometryEngine.h" #include "SpatialReference.h" #include "TileCache.h" using namespace Esri::ArcGISRuntime; ExportTiles::ExportTiles(QQuickItem* parent) : QQuickItem(parent), m_map(nullptr), m_mapView(nullptr), m_serviceUrl("http://sampleserver6.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer"), m_exportTileCacheTask(nullptr) { } ExportTiles::~ExportTiles() { } void ExportTiles::componentComplete() { QQuickItem::componentComplete(); // find QML MapView component m_mapView = findChild<MapQuickView*>("mapView"); // create a tiled basemap ArcGISTiledLayer* tiledLayer = new ArcGISTiledLayer(m_serviceUrl); Basemap* basemap = new Basemap(tiledLayer, this); // create a new map instance m_map = new Map(basemap, this); // set an initial viewpoint Envelope env(12362601, 936021, 10187678, 2567213, SpatialReference(3857)); Viewpoint viewpoint(env); m_map->setInitialViewpoint(viewpoint); // set map on the map view m_mapView->setMap(m_map); // create the task from the tiled layer's map service info once it is loaded connect(tiledLayer, &ArcGISTiledLayer::doneLoading, [this, tiledLayer](Error) { m_exportTileCacheTask = new ExportTileCacheTask(tiledLayer->mapServiceInfo(), this); }); } void ExportTiles::exportTileCacheFromCorners(double xCorner1, double yCorner1, double xCorner2, double yCorner2, QString dataPath) { // create an envelope from the QML rectangle corners auto corner1 = m_mapView->screenToLocation(xCorner1, yCorner1); auto corner2 = m_mapView->screenToLocation(xCorner2, yCorner2); auto extent = Envelope(corner1, corner2); auto tileCacheExtent = GeometryEngine::project(extent, SpatialReference::webMercator()); // connect to sync task doneLoading signal connect(m_exportTileCacheTask, &ExportTileCacheTask::defaultExportTileCacheParametersCompleted, [this, dataPath](QUuid, ExportTileCacheParameters parameters) { m_parameters = parameters; // execute the task and obtain the job auto exportJob = m_exportTileCacheTask->exportTileCache(m_parameters, dataPath); // check if there is a valid job if (exportJob) { // connect to the job's status changed signal connect(exportJob, &ExportTileCacheJob::jobStatusChanged, [this, exportJob]() { // connect to the job's status changed signal to know once it is done switch (exportJob->jobStatus()) { case JobStatus::Failed: emit updateStatus("Export failed"); emit hideWindow(5000, false); break; case JobStatus::NotStarted: emit updateStatus("Job not started"); break; case JobStatus::Paused: emit updateStatus("Job paused"); break; case JobStatus::Started: emit updateStatus("In progress..."); break; case JobStatus::Succeeded: emit updateStatus("Adding TPK..."); emit hideWindow(1500, true); displayOutputTileCache(exportJob->result()); break; default: break; } }); // start the export job exportJob->start(); } else { emit updateStatus("Export failed"); emit hideWindow(5000, false); } }); // generate parameters m_exportTileCacheTask->createDefaultExportTileCacheParameters(tileCacheExtent, m_mapView->mapScale(), m_exportTileCacheTask->mapServiceInfo().maxScale()); } // display the tile cache once the task is complete void ExportTiles::displayOutputTileCache(TileCache* tileCache) { // create a new tiled layer from the output tile cache auto tiledLayer = new ArcGISTiledLayer(tileCache, this); // add the new layer to a basemap auto basemap = new Basemap(tiledLayer, this); // set the new basemap on the map m_map->setBasemap(basemap); // zoom to the new layer and hide window once loaded connect(tiledLayer, &ArcGISTiledLayer::doneLoading, [this, tiledLayer]() { if (tiledLayer->loadStatus() == LoadStatus::Loaded) { m_mapView->setViewpointScale(m_mapView->mapScale() * 0.5); } }); } <|endoftext|>
<commit_before>#ifndef DUNE_STUFF_FUNCTION_INTERFACE_HH #define DUNE_STUFF_FUNCTION_INTERFACE_HH #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include <config.h> #endif // ifdef HAVE_CMAKE_CONFIG #include <vector> #include <dune/common/shared_ptr.hh> #include <dune/common/fvector.hh> #include <dune/common/dynvector.hh> #include <dune/common/function.hh> #include <dune/stuff/common/color.hh> #include <dune/stuff/common/parameter.hh> namespace Dune { namespace Stuff { namespace Function { //! forward template< class RangeFieldImp > class Coefficient; template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim > class Interface { public: typedef Interface< DomainFieldImp, domainDim, RangeFieldImp, rangeDim > ThisType; typedef DomainFieldImp DomainFieldType; static const int dimDomain = domainDim; typedef Dune::FieldVector< DomainFieldType, dimDomain > DomainType; typedef RangeFieldImp RangeFieldType; static const int dimRange = rangeDim; typedef Dune::FieldVector< RangeFieldType, dimRange > RangeType; typedef Common::Parameter::FieldType ParamFieldType; static const int maxParamDim = Common::Parameter::maxDim; typedef Common::Parameter::Type ParamType; typedef ThisType ComponentType; typedef Coefficient< RangeFieldType > CoefficientType; static const std::string id() { return "function"; } /** \defgroup type ´´Theis method has to be implemented for parametric functions and determines, * which evaluate() is callable.'' */ /* @{ */ virtual bool parametric() const { return false; } /* @} */ /** \defgroup info ´´These methods should be implemented in order to identify the function.'' */ /* @{ */ virtual std::string name() const { return id(); } virtual int order() const { return -1; } /* @} */ /** \defgroup nonparametric-must ´´These methods have to be implemented, if parametric() == false.'' */ /* @{ */ virtual void evaluate(const DomainType& /*_x*/, RangeType& /*_ret*/) const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == false!"); } /* @} */ /** \defgroup parametric-must ´´These methods have to be implemented, if parametric() == true.'' */ /* @{ */ virtual void evaluate(const DomainType& /*_x*/, const ParamType& /*_mu*/, RangeType& /*_ret*/) const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!"); } virtual size_t paramSize() const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!"); } virtual const std::vector< ParamType >& paramRange() const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!"); } virtual const std::vector< std::string >& paramExplanation() const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!"); } virtual bool separable() const { return false; } /* @} */ /** \defgroup separable ´´These methods have to be implemented, if separable() == true.'' */ /* @{ */ virtual size_t numComponents() const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if separable() == true!"); } virtual const std::vector< Dune::shared_ptr< const ComponentType > >& components() const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if separable() == true!"); } virtual size_t numCoefficients() const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if separable() == true!"); } virtual const std::vector< Dune::shared_ptr< const CoefficientType > >& coefficients() const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if separable() == true!"); } /* @} */ /** \defgroup provided ´´These methods are provided by the interface itself, but may not be implemented optimal.'' */ /* @{ */ virtual RangeType evaluate(const DomainType& _x) const { assert(!parametric()); RangeType ret; evaluate(_x, ret); return ret; } // virtual RangeType evaluate(const DomainType& x, const ParamType& mu) const // { // RangeType ret; // evaluate(x, mu, ret); // return ret; // } // virtual void evaluate(const ParamType& x, const ParamType& mu, RangeType& ret) const // { // // process input // assert(x.size() == dimDomain); // DomainType x_fvector; // for (int i = 0; i < dimDomain; ++i) // x_fvector[i] = x(i); // // evaluate // evaluate(x_fvector, mu, ret); // } // virtual void evaluate(const DomainType& x, const ParamType& mu, ParamType& ret) const // { // // evaluate // RangeType ret_fvector; // evaluate(x, mu, ret_fvector); // // process output // assert(ret.size() == dimRange); // for (int i = 0; i < dimRange; ++i) // ret(i) = ret_fvector[i]; // } // virtual void evaluate(const ParamType& x, const ParamType& mu, ParamType& ret) const // { // // process input // assert(x.size() == dimDomain); // DomainType x_fvector; // for (int i = 0; i < dimDomain; ++i) // x_fvector[i] = x(i); // // evaluate // RangeType ret_fvector; // evaluate(x_fvector, mu, ret_fvector); // // process output // assert(ret.size() == dimRange); // for (int i = 0; i < dimRange; ++i) // ret(i) = ret_fvector[i]; // } // virtual ParamType evaluate(const ParamType& x, const ParamType& mu) const // { // ParamType ret; // evaluate(x, mu, ret); // return ret; // } // void report(std::ostream& out = std::cout, std::string prefix = "") const // { // out << prefix << "parameter explanation:" << std::endl; // assert(paramExplanation().size() == paramSize()); // assert(paramRange().size() == 2); // assert(paramRange()[0].size() == paramSize()); // assert(paramRange()[1].size() == paramSize()); // for (unsigned int pp = 0; pp < paramSize(); ++pp) // out << prefix << " " << paramExplanation()[pp] << ", between " << paramRange()[0](pp) << " and " << paramRange()[1](pp) << std::endl; // } /* @} */ }; // class Interface } // namespace Function } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTION_INTERFACE_HH <commit_msg>[function.interface] paramSize() returns 0 in the nonparametric case<commit_after>#ifndef DUNE_STUFF_FUNCTION_INTERFACE_HH #define DUNE_STUFF_FUNCTION_INTERFACE_HH #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include <config.h> #endif // ifdef HAVE_CMAKE_CONFIG #include <vector> #include <dune/common/shared_ptr.hh> #include <dune/common/fvector.hh> #include <dune/common/dynvector.hh> #include <dune/common/function.hh> #include <dune/stuff/common/color.hh> #include <dune/stuff/common/parameter.hh> namespace Dune { namespace Stuff { namespace Function { //! forward template< class RangeFieldImp > class Coefficient; template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim > class Interface { public: typedef Interface< DomainFieldImp, domainDim, RangeFieldImp, rangeDim > ThisType; typedef DomainFieldImp DomainFieldType; static const int dimDomain = domainDim; typedef Dune::FieldVector< DomainFieldType, dimDomain > DomainType; typedef RangeFieldImp RangeFieldType; static const int dimRange = rangeDim; typedef Dune::FieldVector< RangeFieldType, dimRange > RangeType; typedef Common::Parameter::FieldType ParamFieldType; static const int maxParamDim = Common::Parameter::maxDim; typedef Common::Parameter::Type ParamType; typedef ThisType ComponentType; typedef Coefficient< RangeFieldType > CoefficientType; static const std::string id() { return "function"; } /** \defgroup type ´´Theis method has to be implemented for parametric functions and determines, * which evaluate() is callable.'' */ /* @{ */ virtual bool parametric() const { return false; } /* @} */ /** \defgroup info ´´These methods should be implemented in order to identify the function.'' */ /* @{ */ virtual std::string name() const { return id(); } virtual int order() const { return -1; } /* @} */ /** \defgroup nonparametric-must ´´These methods have to be implemented, if parametric() == false.'' */ /* @{ */ virtual void evaluate(const DomainType& /*_x*/, RangeType& /*_ret*/) const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == false!"); } /* @} */ /** \defgroup parametric-must ´´These methods have to be implemented, if parametric() == true.'' */ /* @{ */ virtual void evaluate(const DomainType& /*_x*/, const ParamType& /*_mu*/, RangeType& /*_ret*/) const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!"); } virtual size_t paramSize() const { if (!parametric()) return 0; else DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!"); } virtual const std::vector< ParamType >& paramRange() const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!"); } virtual const std::vector< std::string >& paramExplanation() const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!"); } virtual bool separable() const { return false; } /* @} */ /** \defgroup separable ´´These methods have to be implemented, if separable() == true.'' */ /* @{ */ virtual size_t numComponents() const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if separable() == true!"); } virtual const std::vector< Dune::shared_ptr< const ComponentType > >& components() const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if separable() == true!"); } virtual size_t numCoefficients() const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if separable() == true!"); } virtual const std::vector< Dune::shared_ptr< const CoefficientType > >& coefficients() const { DUNE_THROW(Dune::NotImplemented, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if separable() == true!"); } /* @} */ /** \defgroup provided ´´These methods are provided by the interface itself, but may not be implemented optimal.'' */ /* @{ */ virtual RangeType evaluate(const DomainType& _x) const { assert(!parametric()); RangeType ret; evaluate(_x, ret); return ret; } // virtual RangeType evaluate(const DomainType& x, const ParamType& mu) const // { // RangeType ret; // evaluate(x, mu, ret); // return ret; // } // virtual void evaluate(const ParamType& x, const ParamType& mu, RangeType& ret) const // { // // process input // assert(x.size() == dimDomain); // DomainType x_fvector; // for (int i = 0; i < dimDomain; ++i) // x_fvector[i] = x(i); // // evaluate // evaluate(x_fvector, mu, ret); // } // virtual void evaluate(const DomainType& x, const ParamType& mu, ParamType& ret) const // { // // evaluate // RangeType ret_fvector; // evaluate(x, mu, ret_fvector); // // process output // assert(ret.size() == dimRange); // for (int i = 0; i < dimRange; ++i) // ret(i) = ret_fvector[i]; // } // virtual void evaluate(const ParamType& x, const ParamType& mu, ParamType& ret) const // { // // process input // assert(x.size() == dimDomain); // DomainType x_fvector; // for (int i = 0; i < dimDomain; ++i) // x_fvector[i] = x(i); // // evaluate // RangeType ret_fvector; // evaluate(x_fvector, mu, ret_fvector); // // process output // assert(ret.size() == dimRange); // for (int i = 0; i < dimRange; ++i) // ret(i) = ret_fvector[i]; // } // virtual ParamType evaluate(const ParamType& x, const ParamType& mu) const // { // ParamType ret; // evaluate(x, mu, ret); // return ret; // } // void report(std::ostream& out = std::cout, std::string prefix = "") const // { // out << prefix << "parameter explanation:" << std::endl; // assert(paramExplanation().size() == paramSize()); // assert(paramRange().size() == 2); // assert(paramRange()[0].size() == paramSize()); // assert(paramRange()[1].size() == paramSize()); // for (unsigned int pp = 0; pp < paramSize(); ++pp) // out << prefix << " " << paramExplanation()[pp] << ", between " << paramRange()[0](pp) << " and " << paramRange()[1](pp) << std::endl; // } /* @} */ }; // class Interface } // namespace Function } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTION_INTERFACE_HH <|endoftext|>
<commit_before>/* Copyright 2017 Christian */ #include <sstream> #include "ros/ros.h" #include "std_msgs/String.h" /** * This tutorial demonstrates simple sending of messages over the ROS system. */ int main(int argc, char **argv) { /** * The ros::init() function needs to see argc and argv so that it can perform * any ROS arguments and name remapping that were provided at the command line. * For programmatic remappings you can use a different version of init() which takes * remappings directly, but for most command-line programs, passing argc and argv is * the easiest way to do it. The third argument to init() is the name of the node. * * You must call one of the versions of ros::init() before using any other * part of the ROS system. */ ros::init(argc, argv, "talker"); /** * NodeHandle is the main access point to communications with the ROS system. * The first NodeHandle constructed will fully initialize this node, and the last * NodeHandle destructed will close down the node. */ ros::NodeHandle n; /** * The advertise() function is how you tell ROS that you want to * publish on a given topic name. This invokes a call to the ROS * master node, which keeps a registry of who is publishing and who * is subscribing. After this advertise() call is made, the master * node will notify anyone who is trying to subscribe to this topic name, * and they will in turn negotiate a peer-to-peer connection with this * node. advertise() returns a Publisher object which allows you to * publish messages on that topic through a call to publish(). Once * all copies of the returned Publisher object are destroyed, the topic * will be automatically unadvertised. * * The second parameter to advertise() is the size of the message queue * used for publishing messages. If messages are published more quickly * than we can send them, the number here specifies how many messages to * buffer up before throwing some away. */ ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000); ros::Rate loop_rate(10); /** * A count of how many messages we have sent. This is used to create * a unique string for each message. */ int year = 2017; while (ros::ok()) { /** * This is a message object. You stuff it with data, and then publish it. */ std_msgs::String msg; std::stringstream ss; ss << "Welcome Class ENPM808X of " << year; msg.data = ss.str(); ROS_INFO("%s", msg.data.c_str()); /** * The publish() function is how you send messages. The parameter * is the message object. The type of this object must agree with the type * given as a template parameter to the advertise<>() call, as was done * in the constructor above. */ chatter_pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); ++year; } return 0; } <commit_msg>Modifying Talker node to broadcast a tf frame<commit_after>/* Copyright 2017 Christian */ #include <tf/transform_broadcaster.h> #include <sstream> #include "ros/ros.h" #include "std_msgs/String.h" /** * This tutorial has been modified to broadcast tf frames over the ROS system. */ int main(int argc, char **argv) { /** * The ros::init() function needs to see argc and argv so that it can perform * any ROS arguments and name remapping that were provided at the command line. * For programmatic remappings you can use a different version of init() which takes * remappings directly, but for most command-line programs, passing argc and argv is * the easiest way to do it. The third argument to init() is the name of the node. * * You must call one of the versions of ros::init() before using any other * part of the ROS system. */ ros::init(argc, argv, "talker"); /** * NodeHandle is the main access point to communications with the ROS system. * The first NodeHandle constructed will fully initialize this node, and the last * NodeHandle destructed will close down the node. */ ros::NodeHandle n; /** * The advertise() function is how you tell ROS that you want to * publish on a given topic name. This invokes a call to the ROS * master node, which keeps a registry of who is publishing and who * is subscribing. After this advertise() call is made, the master * node will notify anyone who is trying to subscribe to this topic name, * and they will in turn negotiate a peer-to-peer connection with this * node. advertise() returns a Publisher object which allows you to * publish messages on that topic through a call to publish(). Once * all copies of the returned Publisher object are destroyed, the topic * will be automatically unadvertised. * * The second parameter to advertise() is the size of the message queue * used for publishing messages. If messages are published more quickly * than we can send them, the number here specifies how many messages to * buffer up before throwing some away. */ ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000); /** * loop_rate is an object that defines that frequency in Hz at which the while loop * will work */ ros::Rate loop_rate(10); /** * tfBroadcaster is an object that will be used to broadcast the trasnform */ tf::TransformBroadcaster tfBroadcaster; /** * A count of how many messages we have sent. This is used to create * a unique string for each message. */ int year = 2017; while (ros::ok()) { /** * This is a message object. You stuff it with data, and then publish it. */ std_msgs::String msg; std::stringstream ss; ss << "Welcome Class ENPM808X of " << year; msg.data = ss.str(); ROS_INFO("%s", msg.data.c_str()); /** * The publish() function is how you send messages. The parameter * is the message object. The type of this object must agree with the type * given as a template parameter to the advertise<>() call, as was done * in the constructor above. */ chatter_pub.publish(msg); /** * The transform object will contain the rotation and translation parameters */ tf::Transform transform; /** * Setting the world frame reference in the transform vector x = 0.2 ,y = 0, z = 0.3 */ transform.setOrigin(tf::Vector3(0.2, 0.0, 0.3)); /** * Quaternion object used to define rotation */ tf::Quaternion tfQuatrn; /** * Setting rotation to be only in the z plane (180 turn around Z axis) */ tfQuatrn.setRPY(0, 0, 1); /** * Embedding translation and rotation data into transform object */ transform.setRotation(tfQuatrn); /** * Broadcasting the transform using 4 parameters: * transform contains translation and rotation matrix * Time::now() contains the time stamp of the system * world parent frame name * talk child fram name */ tfBroadcaster.sendTransform(tf::StampedTransform(transform, ros::Time::now(), "world", "talk")); ros::spinOnce(); loop_rate.sleep(); } return 0; } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Kirsten Weber #ifndef DUNE_STUFF_FUNCTIONS_CONSTANT_HH #define DUNE_STUFF_FUNCTIONS_CONSTANT_HH #include <memory> #include <dune/stuff/common/configuration.hh> #include "interfaces.hh" namespace Dune { namespace Stuff { namespace Functions { namespace internal { template< class K, int dim > struct UnitMatrix { typedef FieldMatrix< K, dim, dim > type; static type value() { type ret(0); for (size_t dd = 0; dd < dim; ++dd) ret[dd][dd] = 1; return ret; } }; // struct UnitMatrix template< class K > struct UnitMatrix< K, 1 > { typedef FieldVector< K, 1 > type; static type value() { return type(1); } }; // struct UnitMatrix template< class K, int dim > typename UnitMatrix< K, dim >::type unit_matrix() { return UnitMatrix< K, dim >::value(); } } // namespace internal template< class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1 > class Constant : public GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols> { typedef GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType; typedef Constant < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType; template< class R, size_t r, size_t rC > struct Get{ static std::string value_str() { std::string str = "["; for (size_t rr = 0; rr < r; ++rr) { if (rr > 0) str += "; "; for (size_t cc = 0; cc < rC; ++cc) { if (cc > 0) str += " "; if (cc == rr) str += "1"; else str += "0"; } } str += "]"; return str; } }; template< class R, int rC > struct Get< R, 1, rC >{ static std::string value_str() { std::string str = "["; for (size_t cc = 0; cc < rC; ++cc) { if (cc > 0) str += " "; str += "1"; } str += "]"; return str; } }; template< class R, int r > struct Get< R, r, 1 >{ static std::string value_str() { return Get< R, 1, r >::value_str(); } }; template< class R > struct Get< R, 1, 1 >{ static std::string value_str() { return "1"; } }; public: typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; using typename BaseType::LocalfunctionType; static const bool available = true; static std::string static_id() { return BaseType::static_id() + ".constant"; } static Common::Configuration default_config(const std::string sub_name = "") { Common::Configuration config; config["value"] = Get< RangeFieldImp, rangeDim, rangeDimCols >::value_str(); config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); return Common::make_unique< ThisType >( cfg.get("value", default_cfg.get< RangeType >("value")), cfg.get("name", default_cfg.get< std::string >("name"))); } // ... create(...) explicit Constant(const RangeType& constant, const std::string name_in = static_id()) : constant_(constant) , name_(name_in) {} explicit Constant(const RangeFieldImp& constant, const std::string name_in = static_id()) : constant_(constant) , name_(name_in) {} Constant(const ThisType& other) = default; virtual std::string type() const override final { return BaseType::static_id() + ".constant"; } virtual size_t order() const override final { return 0; } virtual void evaluate(const DomainType& /*x*/, RangeType& ret) const override final { ret = constant_; } virtual void jacobian(const DomainType& /*x*/, JacobianRangeType& ret) const override final { ret *= 0.0; } virtual std::string name() const override final { return name_; } private: const RangeType constant_; const std::string name_; }; } // namespace Functions } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTIONS_CONSTANT_HH <commit_msg>[functions.constant] fixed int/size_t template arguments<commit_after>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Kirsten Weber #ifndef DUNE_STUFF_FUNCTIONS_CONSTANT_HH #define DUNE_STUFF_FUNCTIONS_CONSTANT_HH #include <memory> #include <dune/stuff/common/configuration.hh> #include "interfaces.hh" namespace Dune { namespace Stuff { namespace Functions { namespace internal { template< class K, int dim > struct UnitMatrix { typedef FieldMatrix< K, dim, dim > type; static type value() { type ret(0); for (size_t dd = 0; dd < dim; ++dd) ret[dd][dd] = 1; return ret; } }; // struct UnitMatrix template< class K > struct UnitMatrix< K, 1 > { typedef FieldVector< K, 1 > type; static type value() { return type(1); } }; // struct UnitMatrix template< class K, int dim > typename UnitMatrix< K, dim >::type unit_matrix() { return UnitMatrix< K, dim >::value(); } } // namespace internal template< class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1 > class Constant : public GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols> { typedef GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType; typedef Constant < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType; template< class R, size_t r, size_t rC > struct Get{ static std::string value_str() { std::string str = "["; for (size_t rr = 0; rr < r; ++rr) { if (rr > 0) str += "; "; for (size_t cc = 0; cc < rC; ++cc) { if (cc > 0) str += " "; if (cc == rr) str += "1"; else str += "0"; } } str += "]"; return str; } }; template< class R, size_t rC > struct Get< R, 1, rC >{ static std::string value_str() { std::string str = "["; for (size_t cc = 0; cc < rC; ++cc) { if (cc > 0) str += " "; str += "1"; } str += "]"; return str; } }; template< class R, size_t r > struct Get< R, r, 1 >{ static std::string value_str() { return Get< R, 1, r >::value_str(); } }; template< class R > struct Get< R, 1, 1 >{ static std::string value_str() { return "1"; } }; public: typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; using typename BaseType::LocalfunctionType; static const bool available = true; static std::string static_id() { return BaseType::static_id() + ".constant"; } static Common::Configuration default_config(const std::string sub_name = "") { Common::Configuration config; config["value"] = Get< RangeFieldImp, rangeDim, rangeDimCols >::value_str(); config["name"] = static_id(); config.report(); if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); return Common::make_unique< ThisType >( cfg.get("value", default_cfg.get< RangeType >("value")), cfg.get("name", default_cfg.get< std::string >("name"))); } // ... create(...) explicit Constant(const RangeType& constant, const std::string name_in = static_id()) : constant_(constant) , name_(name_in) {} explicit Constant(const RangeFieldImp& constant, const std::string name_in = static_id()) : constant_(constant) , name_(name_in) {} Constant(const ThisType& other) = default; virtual std::string type() const override final { return BaseType::static_id() + ".constant"; } virtual size_t order() const override final { return 0; } virtual void evaluate(const DomainType& /*x*/, RangeType& ret) const override final { ret = constant_; } virtual void jacobian(const DomainType& /*x*/, JacobianRangeType& ret) const override final { ret *= 0.0; } virtual std::string name() const override final { return name_; } private: const RangeType constant_; const std::string name_; }; } // namespace Functions } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTIONS_CONSTANT_HH <|endoftext|>
<commit_before>#ifndef DUNE_STUFF_LA_CONTAINER_EIGEN_HH #define DUNE_STUFF_LA_CONTAINER_EIGEN_HH #ifdef HAVE_EIGEN #include <Eigen/Core> #include <Eigen/Sparse> #include "pattern.hh" namespace Dune { namespace Stuff { namespace LA { namespace Container { namespace Eigen { template< class ElementImp = double > class SparseMatrix : ::Eigen::SparseMatrix< ElementImp, ::Eigen::RowMajor > { public: typedef ElementImp ElementType; typedef ::Eigen::SparseMatrix< ElementType, ::Eigen::RowMajor > BaseType; typedef SparseMatrix< ElementType > ThisType; typedef typename BaseType::Index size_type; SparseMatrix(const size_type _rows, const size_type _cols) : BaseType(_rows, _cols) {} SparseMatrix(const size_type _rows, const size_type _cols, const Dune::Stuff::LA::Container::Pattern::Default& _pattern) : BaseType(_rows, _cols) { assert(size_type(_pattern.rows()) == _rows && "Given pattern too short!"); typedef Dune::Stuff::LA::Container::Pattern::Default PatternType; typedef PatternType::ColumnsType ColumnsType; for (size_type row = 0; row < size_type(_pattern.rows()); ++row) { BaseType::startVec(row); const ColumnsType& columns = _pattern.columns(row); for (typename ColumnsType::const_iterator columnIt = columns.begin(); columnIt != columns.end(); ++columnIt) { const size_type column = *columnIt; BaseType::insertBackByOuterInner(row, column); } // create diagonal entry (insertBackByOuterInner() can not handle empty rows) if (columns.size() == 0) BaseType::insertBackByOuterInner(row, row); } BaseType::finalize(); BaseType::makeCompressed(); BaseType::setZero(); } // SparseMatrix(...) SparseMatrix(const size_type _rows, const size_type _cols, const size_type _nonZerosPerRow) : BaseType(_rows, _cols) { BaseType::reserve(_nonZerosPerRow); BaseType::setZero(); } void reserve(const size_type _nonZerosPerRow) { BaseType::reserve(_nonZerosPerRow); BaseType::setZero(); } size_type rows() const { return BaseType::rows(); } size_type cols() const { return BaseType::cols(); } void add(const size_type i, const size_type j, const ElementType& val) { BaseType::coeffRef(i, j) += val; } void set(const size_type i, const size_type j, const ElementType& val) { BaseType::coeffRef(i, j) = val; } const ElementType get(const size_type i, const size_type j) const { return BaseType::coeff(i, j); } BaseType& base() { return *this; } const BaseType& base() const { return *this; } }; // class SparseMatrix template< class ElementImp = double > class DenseMatrix : ::Eigen::Matrix< ElementImp, ::Eigen::Dynamic, ::Eigen::Dynamic > { public: typedef ElementImp ElementType; typedef ::Eigen::Matrix< ElementType, ::Eigen::Dynamic, ::Eigen::Dynamic > BaseType; typedef DenseMatrix< ElementType > ThisType; typedef typename BaseType::Index size_type; DenseMatrix(const size_type _rows, const size_type _cols) : BaseType(_rows, _cols) { BaseType::setZero(); } DenseMatrix(const size_type _rows, const size_type _cols, const Dune::Stuff::LA::Container::Pattern::Default&) : BaseType(_rows, _cols) { BaseType::setZero(); } // SparseMatrix(...) DenseMatrix(const size_type _rows, const size_type _cols, const size_type) : BaseType(_rows, _cols) { BaseType::setZero(); } void reserve(const size_type) { BaseType::setZero(); } size_type rows() const { return BaseType::rows(); } size_type cols() const { return BaseType::cols(); } void add(const size_type i, const size_type j, const ElementType& val) { BaseType::operator()(i, j) += val; } void set(const size_type i, const size_type j, const ElementType& val) { BaseType::operator()(i, j) = val; } const ElementType get(const size_type i, const size_type j) const { return BaseType::operator()(i, j); } BaseType& base() { return *this; } const BaseType& base() const { return *this; } }; // class DenseMatrix template< class ElementImp = double> class DenseVector : public ::Eigen::Matrix< ElementImp, ::Eigen::Dynamic, 1 > { public: typedef ElementImp ElementType; typedef typename ::Eigen::Matrix< ElementType, ::Eigen::Dynamic, 1 > BaseType; typedef typename BaseType::Index size_type; DenseVector(const size_type _size) : BaseType(_size) { BaseType::setZero(); } size_type size() const { return BaseType::size(); } void add(const size_type i, const ElementType& val) { BaseType::operator()(i) += val; } void set(const size_type i, const ElementType& val) { BaseType::operator()(i) = val; } const ElementType get(const size_type i) const { return BaseType::operator()(i); } const ElementType& operator[](const size_type i) const { return BaseType::coeff(i); } ElementType& operator[](const size_type i) { return BaseType::coeffRef(i); } }; // class DenseVector } // namespace Container } // namespace Eigen } // namespace LA } // namespace Stuff } // namespace Dune #endif // HAVE_EIGEN #endif // DUNE_STUFF_LA_CONTAINER_EIGEN_HH <commit_msg>[la.container.eigen] fixed eigen guard<commit_after>#ifndef DUNE_STUFF_LA_CONTAINER_EIGEN_HH #define DUNE_STUFF_LA_CONTAINER_EIGEN_HH #if HAVE_EIGEN #include <Eigen/Core> #include <Eigen/Sparse> #include "pattern.hh" namespace Dune { namespace Stuff { namespace LA { namespace Container { namespace Eigen { template< class ElementImp = double > class SparseMatrix : ::Eigen::SparseMatrix< ElementImp, ::Eigen::RowMajor > { public: typedef ElementImp ElementType; typedef ::Eigen::SparseMatrix< ElementType, ::Eigen::RowMajor > BaseType; typedef SparseMatrix< ElementType > ThisType; typedef typename BaseType::Index size_type; SparseMatrix(const size_type _rows, const size_type _cols) : BaseType(_rows, _cols) {} SparseMatrix(const size_type _rows, const size_type _cols, const Dune::Stuff::LA::Container::Pattern::Default& _pattern) : BaseType(_rows, _cols) { assert(size_type(_pattern.rows()) == _rows && "Given pattern too short!"); typedef Dune::Stuff::LA::Container::Pattern::Default PatternType; typedef PatternType::ColumnsType ColumnsType; for (size_type row = 0; row < size_type(_pattern.rows()); ++row) { BaseType::startVec(row); const ColumnsType& columns = _pattern.columns(row); for (typename ColumnsType::const_iterator columnIt = columns.begin(); columnIt != columns.end(); ++columnIt) { const size_type column = *columnIt; BaseType::insertBackByOuterInner(row, column); } // create diagonal entry (insertBackByOuterInner() can not handle empty rows) if (columns.size() == 0) BaseType::insertBackByOuterInner(row, row); } BaseType::finalize(); BaseType::makeCompressed(); BaseType::setZero(); } // SparseMatrix(...) SparseMatrix(const size_type _rows, const size_type _cols, const size_type _nonZerosPerRow) : BaseType(_rows, _cols) { BaseType::reserve(_nonZerosPerRow); BaseType::setZero(); } void reserve(const size_type _nonZerosPerRow) { BaseType::reserve(_nonZerosPerRow); BaseType::setZero(); } size_type rows() const { return BaseType::rows(); } size_type cols() const { return BaseType::cols(); } void add(const size_type i, const size_type j, const ElementType& val) { BaseType::coeffRef(i, j) += val; } void set(const size_type i, const size_type j, const ElementType& val) { BaseType::coeffRef(i, j) = val; } const ElementType get(const size_type i, const size_type j) const { return BaseType::coeff(i, j); } BaseType& base() { return *this; } const BaseType& base() const { return *this; } }; // class SparseMatrix template< class ElementImp = double > class DenseMatrix : ::Eigen::Matrix< ElementImp, ::Eigen::Dynamic, ::Eigen::Dynamic > { public: typedef ElementImp ElementType; typedef ::Eigen::Matrix< ElementType, ::Eigen::Dynamic, ::Eigen::Dynamic > BaseType; typedef DenseMatrix< ElementType > ThisType; typedef typename BaseType::Index size_type; DenseMatrix(const size_type _rows, const size_type _cols) : BaseType(_rows, _cols) { BaseType::setZero(); } DenseMatrix(const size_type _rows, const size_type _cols, const Dune::Stuff::LA::Container::Pattern::Default&) : BaseType(_rows, _cols) { BaseType::setZero(); } // SparseMatrix(...) DenseMatrix(const size_type _rows, const size_type _cols, const size_type) : BaseType(_rows, _cols) { BaseType::setZero(); } void reserve(const size_type) { BaseType::setZero(); } size_type rows() const { return BaseType::rows(); } size_type cols() const { return BaseType::cols(); } void add(const size_type i, const size_type j, const ElementType& val) { BaseType::operator()(i, j) += val; } void set(const size_type i, const size_type j, const ElementType& val) { BaseType::operator()(i, j) = val; } const ElementType get(const size_type i, const size_type j) const { return BaseType::operator()(i, j); } BaseType& base() { return *this; } const BaseType& base() const { return *this; } }; // class DenseMatrix template< class ElementImp = double> class DenseVector : public ::Eigen::Matrix< ElementImp, ::Eigen::Dynamic, 1 > { public: typedef ElementImp ElementType; typedef typename ::Eigen::Matrix< ElementType, ::Eigen::Dynamic, 1 > BaseType; typedef typename BaseType::Index size_type; DenseVector(const size_type _size) : BaseType(_size) { BaseType::setZero(); } size_type size() const { return BaseType::size(); } void add(const size_type i, const ElementType& val) { BaseType::operator()(i) += val; } void set(const size_type i, const ElementType& val) { BaseType::operator()(i) = val; } const ElementType get(const size_type i) const { return BaseType::operator()(i); } const ElementType& operator[](const size_type i) const { return BaseType::coeff(i); } ElementType& operator[](const size_type i) { return BaseType::coeffRef(i); } }; // class DenseVector } // namespace Container } // namespace Eigen } // namespace LA } // namespace Stuff } // namespace Dune #endif // HAVE_EIGEN #endif // DUNE_STUFF_LA_CONTAINER_EIGEN_HH <|endoftext|>
<commit_before>/* * VapourSynth D2V Plugin * * Copyright (c) 2012 Derek Buitenhuis * * This file is part of d2vsource. * * d2vsource 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. * * d2vsource 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 d2vsource; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <iostream> #include <string> #include <vector> extern "C" { #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> #include <stdio.h> } #include "compat.hpp" #include "d2v.hpp" #include "decode.hpp" #include "gop.hpp" using namespace std; /* * AVIO seek function to handle GOP offsets and multi-file support * in libavformat without it knowing about it. */ static int64_t file_seek(void *opaque, int64_t offset, int whence) { decodecontext *ctx = (decodecontext *) opaque; switch(whence) { case SEEK_SET: { /* * This mutli-file seek is likely very broken, but I don't * really care much, since it is only used in avformat_find_stream_info, * which does its job fine as-is. */ int64_t real_offset = offset + ctx->orig_file_offset; unsigned int i; for(i = ctx->orig_file; i < ctx->cur_file; i++) real_offset -= ctx->file_sizes[i]; while(real_offset > ctx->file_sizes[ctx->cur_file] && ctx->cur_file != ctx->files.size() - 1) { real_offset -= ctx->file_sizes[ctx->cur_file]; ctx->cur_file++; } while(real_offset < 0 && ctx->cur_file) { ctx->cur_file--; real_offset += ctx->file_sizes[ctx->cur_file]; } fseeko(ctx->files[ctx->cur_file], real_offset, SEEK_SET); return offset; } case AVSEEK_SIZE: { /* * Return the total filesize of all files combined, * adjusted for GOP offset. */ int64_t size = -(ctx->orig_file_offset); unsigned int i; for(i = ctx->orig_file; i < ctx->file_sizes.size(); i++) size += ctx->file_sizes[i]; return size; } default: /* Shouldn't need to support anything else for our use case. */ cout << "Unsupported seek!" << endl; return -1; } } /* * AVIO packet reading function to handle GOP offsets and multi-file support * in libavformat without it knowing about it. */ static int read_packet(void *opaque, uint8_t *buf, int size) { decodecontext *ctx = (decodecontext *) opaque; int ret; /* * If we read in less than we got asked for, and we're * not on the last file, then start reading seamlessly * on the next file. */ ret = fread(buf, 1, size, ctx->files[ctx->cur_file]); if (ret < size && ctx->cur_file != ctx->files.size() - 1) { ctx->cur_file++; fseeko(ctx->files[ctx->cur_file], 0, SEEK_SET); fread(buf + ret, 1, size - ret, ctx->files[ctx->cur_file]); } else { return ret; } return size; } /* Conditionally free all memebers of decodecontext. */ void decodefreep(decodecontext **ctx) { decodecontext *lctx = *ctx; unsigned int i; if (!lctx) return; av_freep(&lctx->in); av_free_packet(&lctx->inpkt); if (lctx->fctx) { if (lctx->fctx->pb) av_freep(&lctx->fctx->pb); avformat_close_input(&lctx->fctx); } for(i = 0; i < lctx->files.size(); i++) fclose(lctx->files[i]); lctx->files.clear(); lctx->file_sizes.clear(); if (lctx->avctx) { avcodec_close(lctx->avctx); av_freep(&lctx->avctx); } delete lctx->fakename; delete lctx; *ctx = NULL; } /* Initialize everything we can with regards to decoding */ decodecontext *decodeinit(d2vcontext *dctx, string& err) { decodecontext *ret; int i, av_ret; ret = new decodecontext; /* Zero the context to aid in conditional freeing later. */ memset(ret, 0, sizeof(*ret)); /* Holds our "filename" we pass to libavformat. */ ret->fakename = new string; /* Set our stream index to -1 (uninitialized). */ ret->stream_index = -1; /* Open each file and stash its size. */ for(i = 0; i < dctx->num_files; i++) { FILE *in; int64_t size; in = fopen(dctx->files[i].c_str(), "rb"); if (!in) { err = "Cannot open file: "; err += dctx->files[i]; goto fail; } fseeko(in, 0, SEEK_END); size = ftello(in); fseeko(in, 0, SEEK_SET); ret->file_sizes.push_back(size); ret->files.push_back(in); } /* * Register all of our demuxers, parsers, and decoders. * Ideally, to create a smaller binary, we only enable the * following: * * Demuxers: mpegvideo, mpegps, mpegts. * Parsers: mpegvideo, mpegaudio. * Decoders: mpeg1video, mpeg2video. */ avcodec_register_all(); av_register_all(); /* Set the correct decoder. */ if (dctx->mpeg_type == 1) { ret->incodec = avcodec_find_decoder(AV_CODEC_ID_MPEG1VIDEO); } else if (dctx->mpeg_type == 2) { ret->incodec = avcodec_find_decoder(AV_CODEC_ID_MPEG2VIDEO); } else { err = "Invalid MPEG Type."; goto fail; } /* Allocate the codec's context. */ ret->avctx = avcodec_alloc_context3(ret->incodec); if (!ret->avctx) { err = "Cannot allocate AVCodecContext."; goto fail; } /* Set the IDCT algorithm. */ ret->avctx->idct_algo = dctx->idct_algo; /* * Enable EMU_EDGE so that we can use buffers that are * not padded by 32 pixels. */ ret->avctx->flags |= CODEC_FLAG_EMU_EDGE; /* Open it. */ av_ret = avcodec_open2(ret->avctx, ret->incodec, NULL); if (av_ret < 0) { err = "Cannot open decoder."; goto fail; } /* Allocate the scratch buffer for our custom AVIO context. */ ret->in = (uint8_t *) av_malloc(32 * 1024); if (!ret->in) { err = "Cannot alloc inbuf."; goto fail; } /* We don't want to hear all the info it has. */ av_log_set_level(AV_LOG_PANIC); return ret; fail: decodefreep(&ret); return NULL; } int decodeframe(int frame_num, d2vcontext *ctx, decodecontext *dctx, AVFrame *out, string& err) { frame f; gop g; unsigned int i; int o, j, av_ret, offset; bool next; /* Get our frame and the GOP its in. */ f = ctx->frames[frame_num]; g = ctx->gops[f.gop]; /* * The offset is how many frames we have to decode from our * current position in order to get to the frame we want. * The initial offset is obtaiend during the parsing of the * D2V file, but it may be more in an open GOP situation, * which we handle below. */ offset = f.offset; /* * If we're in a open GOP situation, then start decoding * from the previous GOP (one at most is needed), and adjust * out offset accordingly. */ if (!(g.info & GOP_FLAG_CLOSED) && (f.gop - 1 > 0)) { int n = frame_num; frame t = ctx->frames[n]; g = ctx->gops[f.gop - 1]; /* * Find the offset of the last frame in the * previous GOP and add it to our offset. */ while(t.offset) t = ctx->frames[--n]; t = ctx->frames[--n]; /* * Subtract one from the offset to compensate for * libavcodec delay, I think. */ offset += t.offset - 1; } /* * Check if we're decoding linearly, and if the GOP * of the current frame and previous frame are either * the same, or also linear. If so, we can decode * linearly. */ next = (dctx->last_gop == f.gop || dctx->last_gop == f.gop - 1) && dctx->last_frame == frame_num - 1; /* Skip GOP initialization if we're decoding linearly. */ if (!next) { /* Free out format and AVIO contexts from the previous seek. */ if (dctx->fctx) { if (dctx->fctx->pb) av_freep(&dctx->fctx->pb); avformat_close_input(&dctx->fctx); } /* Seek to our GOP offset and stash the info. */ fseeko(dctx->files[g.file], g.pos, SEEK_SET); dctx->orig_file_offset = g.pos; dctx->orig_file = g.file; dctx->cur_file = g.file; /* Allocate format context. */ dctx->fctx = avformat_alloc_context(); if (!dctx->fctx) { err = "Cannot allocate AVFormatContext."; goto dfail; } /* * Find the demuxer for our input type, and also set * the "filename" that we pass to libavformat when * we open the demuxer with our custom AVIO context. */ if (ctx->stream_type == ELEMENTARY) { dctx->fctx->iformat = av_find_input_format("mpegvideo"); *dctx->fakename = "fakevideo.m2v"; } else if (ctx->stream_type == PROGRAM) { dctx->fctx->iformat = av_find_input_format("mpeg"); *dctx->fakename = "fakevideo.vob"; } else if (ctx->stream_type == TRANSPORT) { dctx->fctx->iformat = av_find_input_format("mpegts"); *dctx->fakename = "fakevideo.ts"; } else { err = "Unsupported format."; goto dfail; } /* * Initialize out custom AVIO context that libavformat * will use instead of a file. It uses our custom packet * reading and seeking functions that transparently work * with our indexed GOP offsets and multiple files. */ dctx->fctx->pb = avio_alloc_context(dctx->in, 32 * 1024, 0, dctx, read_packet, NULL, file_seek); /* Open the demuxer. */ av_ret = avformat_open_input(&dctx->fctx, (*dctx->fakename).c_str(), NULL, NULL); if (av_ret < 0) { err = "Cannot open buffer in libavformat."; goto dfail; } /* * Flush the buffers of our codec's context so we * don't need to re-initialize it. */ avcodec_flush_buffers(dctx->avctx); /* * Call the abomination function to find out * how many streams we have. */ avformat_find_stream_info(dctx->fctx, NULL); /* Free and re-initialize any existing packet. */ av_free_packet(&dctx->inpkt); av_init_packet(&dctx->inpkt); } /* Set our stream index if we need to. */ if (dctx->stream_index == -1) { for(i = 0; i < dctx->fctx->nb_streams; i++) { if (dctx->fctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) { dctx->stream_index = (int) i; break; } } } /* * We don't need to read a new packet in if we are decoding * linearly, since it's still there from the previous iteration. */ if (!next) av_read_frame(dctx->fctx, &dctx->inpkt); /* If we're decoding linearly, there is obviously no offset. */ o = next ? 0 : offset; for(j = 0; j <= o; j++) { while(dctx->inpkt.stream_index != dctx->stream_index) { av_free_packet(&dctx->inpkt); av_read_frame(dctx->fctx, &dctx->inpkt); } /* * Loop until we have a whole frame, since there can be * multi-packet frames. */ av_ret = 0; while(!av_ret) { AVPacket orig = dctx->inpkt; /* * Decoding might not consume out whole packet, so * stash the original packet info, loop until it * is all consumed, and then restore it, it so * we can free it properly. */ while(dctx->inpkt.size > 0) { int r = avcodec_decode_video2(dctx->avctx, out, &av_ret, &dctx->inpkt); dctx->inpkt.size -= r; dctx->inpkt.data += r; } dctx->inpkt = orig; av_free_packet(&dctx->inpkt); av_read_frame(dctx->fctx, &dctx->inpkt); } } /* * Stash the frame number we just decoded, and the GOP it * is a part of so we can check if we're decoding linearly * later on. */ dctx->last_gop = f.gop; dctx->last_frame = frame_num; return 0; dfail: avformat_close_input(&dctx->fctx); return -1; } <commit_msg>Account for interleaved streams while decoding frames<commit_after>/* * VapourSynth D2V Plugin * * Copyright (c) 2012 Derek Buitenhuis * * This file is part of d2vsource. * * d2vsource 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. * * d2vsource 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 d2vsource; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <iostream> #include <string> #include <vector> extern "C" { #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> #include <stdio.h> } #include "compat.hpp" #include "d2v.hpp" #include "decode.hpp" #include "gop.hpp" using namespace std; /* * AVIO seek function to handle GOP offsets and multi-file support * in libavformat without it knowing about it. */ static int64_t file_seek(void *opaque, int64_t offset, int whence) { decodecontext *ctx = (decodecontext *) opaque; switch(whence) { case SEEK_SET: { /* * This mutli-file seek is likely very broken, but I don't * really care much, since it is only used in avformat_find_stream_info, * which does its job fine as-is. */ int64_t real_offset = offset + ctx->orig_file_offset; unsigned int i; for(i = ctx->orig_file; i < ctx->cur_file; i++) real_offset -= ctx->file_sizes[i]; while(real_offset > ctx->file_sizes[ctx->cur_file] && ctx->cur_file != ctx->files.size() - 1) { real_offset -= ctx->file_sizes[ctx->cur_file]; ctx->cur_file++; } while(real_offset < 0 && ctx->cur_file) { ctx->cur_file--; real_offset += ctx->file_sizes[ctx->cur_file]; } fseeko(ctx->files[ctx->cur_file], real_offset, SEEK_SET); return offset; } case AVSEEK_SIZE: { /* * Return the total filesize of all files combined, * adjusted for GOP offset. */ int64_t size = -(ctx->orig_file_offset); unsigned int i; for(i = ctx->orig_file; i < ctx->file_sizes.size(); i++) size += ctx->file_sizes[i]; return size; } default: /* Shouldn't need to support anything else for our use case. */ cout << "Unsupported seek!" << endl; return -1; } } /* * AVIO packet reading function to handle GOP offsets and multi-file support * in libavformat without it knowing about it. */ static int read_packet(void *opaque, uint8_t *buf, int size) { decodecontext *ctx = (decodecontext *) opaque; int ret; /* * If we read in less than we got asked for, and we're * not on the last file, then start reading seamlessly * on the next file. */ ret = fread(buf, 1, size, ctx->files[ctx->cur_file]); if (ret < size && ctx->cur_file != ctx->files.size() - 1) { ctx->cur_file++; fseeko(ctx->files[ctx->cur_file], 0, SEEK_SET); fread(buf + ret, 1, size - ret, ctx->files[ctx->cur_file]); } else { return ret; } return size; } /* Conditionally free all memebers of decodecontext. */ void decodefreep(decodecontext **ctx) { decodecontext *lctx = *ctx; unsigned int i; if (!lctx) return; av_freep(&lctx->in); av_free_packet(&lctx->inpkt); if (lctx->fctx) { if (lctx->fctx->pb) av_freep(&lctx->fctx->pb); avformat_close_input(&lctx->fctx); } for(i = 0; i < lctx->files.size(); i++) fclose(lctx->files[i]); lctx->files.clear(); lctx->file_sizes.clear(); if (lctx->avctx) { avcodec_close(lctx->avctx); av_freep(&lctx->avctx); } delete lctx->fakename; delete lctx; *ctx = NULL; } /* Initialize everything we can with regards to decoding */ decodecontext *decodeinit(d2vcontext *dctx, string& err) { decodecontext *ret; int i, av_ret; ret = new decodecontext; /* Zero the context to aid in conditional freeing later. */ memset(ret, 0, sizeof(*ret)); /* Holds our "filename" we pass to libavformat. */ ret->fakename = new string; /* Set our stream index to -1 (uninitialized). */ ret->stream_index = -1; /* Open each file and stash its size. */ for(i = 0; i < dctx->num_files; i++) { FILE *in; int64_t size; in = fopen(dctx->files[i].c_str(), "rb"); if (!in) { err = "Cannot open file: "; err += dctx->files[i]; goto fail; } fseeko(in, 0, SEEK_END); size = ftello(in); fseeko(in, 0, SEEK_SET); ret->file_sizes.push_back(size); ret->files.push_back(in); } /* * Register all of our demuxers, parsers, and decoders. * Ideally, to create a smaller binary, we only enable the * following: * * Demuxers: mpegvideo, mpegps, mpegts. * Parsers: mpegvideo, mpegaudio. * Decoders: mpeg1video, mpeg2video. */ avcodec_register_all(); av_register_all(); /* Set the correct decoder. */ if (dctx->mpeg_type == 1) { ret->incodec = avcodec_find_decoder(AV_CODEC_ID_MPEG1VIDEO); } else if (dctx->mpeg_type == 2) { ret->incodec = avcodec_find_decoder(AV_CODEC_ID_MPEG2VIDEO); } else { err = "Invalid MPEG Type."; goto fail; } /* Allocate the codec's context. */ ret->avctx = avcodec_alloc_context3(ret->incodec); if (!ret->avctx) { err = "Cannot allocate AVCodecContext."; goto fail; } /* Set the IDCT algorithm. */ ret->avctx->idct_algo = dctx->idct_algo; /* * Enable EMU_EDGE so that we can use buffers that are * not padded by 32 pixels. */ ret->avctx->flags |= CODEC_FLAG_EMU_EDGE; /* Open it. */ av_ret = avcodec_open2(ret->avctx, ret->incodec, NULL); if (av_ret < 0) { err = "Cannot open decoder."; goto fail; } /* Allocate the scratch buffer for our custom AVIO context. */ ret->in = (uint8_t *) av_malloc(32 * 1024); if (!ret->in) { err = "Cannot alloc inbuf."; goto fail; } /* We don't want to hear all the info it has. */ av_log_set_level(AV_LOG_PANIC); return ret; fail: decodefreep(&ret); return NULL; } int decodeframe(int frame_num, d2vcontext *ctx, decodecontext *dctx, AVFrame *out, string& err) { frame f; gop g; unsigned int i; int o, j, av_ret, offset; bool next; /* Get our frame and the GOP its in. */ f = ctx->frames[frame_num]; g = ctx->gops[f.gop]; /* * The offset is how many frames we have to decode from our * current position in order to get to the frame we want. * The initial offset is obtaiend during the parsing of the * D2V file, but it may be more in an open GOP situation, * which we handle below. */ offset = f.offset; /* * If we're in a open GOP situation, then start decoding * from the previous GOP (one at most is needed), and adjust * out offset accordingly. */ if (!(g.info & GOP_FLAG_CLOSED) && (f.gop - 1 > 0)) { int n = frame_num; frame t = ctx->frames[n]; g = ctx->gops[f.gop - 1]; /* * Find the offset of the last frame in the * previous GOP and add it to our offset. */ while(t.offset) t = ctx->frames[--n]; t = ctx->frames[--n]; /* * Subtract one from the offset to compensate for * libavcodec delay, I think. */ offset += t.offset - 1; } /* * Check if we're decoding linearly, and if the GOP * of the current frame and previous frame are either * the same, or also linear. If so, we can decode * linearly. */ next = (dctx->last_gop == f.gop || dctx->last_gop == f.gop - 1) && dctx->last_frame == frame_num - 1; /* Skip GOP initialization if we're decoding linearly. */ if (!next) { /* Free out format and AVIO contexts from the previous seek. */ if (dctx->fctx) { if (dctx->fctx->pb) av_freep(&dctx->fctx->pb); avformat_close_input(&dctx->fctx); } /* Seek to our GOP offset and stash the info. */ fseeko(dctx->files[g.file], g.pos, SEEK_SET); dctx->orig_file_offset = g.pos; dctx->orig_file = g.file; dctx->cur_file = g.file; /* Allocate format context. */ dctx->fctx = avformat_alloc_context(); if (!dctx->fctx) { err = "Cannot allocate AVFormatContext."; goto dfail; } /* * Find the demuxer for our input type, and also set * the "filename" that we pass to libavformat when * we open the demuxer with our custom AVIO context. */ if (ctx->stream_type == ELEMENTARY) { dctx->fctx->iformat = av_find_input_format("mpegvideo"); *dctx->fakename = "fakevideo.m2v"; } else if (ctx->stream_type == PROGRAM) { dctx->fctx->iformat = av_find_input_format("mpeg"); *dctx->fakename = "fakevideo.vob"; } else if (ctx->stream_type == TRANSPORT) { dctx->fctx->iformat = av_find_input_format("mpegts"); *dctx->fakename = "fakevideo.ts"; } else { err = "Unsupported format."; goto dfail; } /* * Initialize out custom AVIO context that libavformat * will use instead of a file. It uses our custom packet * reading and seeking functions that transparently work * with our indexed GOP offsets and multiple files. */ dctx->fctx->pb = avio_alloc_context(dctx->in, 32 * 1024, 0, dctx, read_packet, NULL, file_seek); /* Open the demuxer. */ av_ret = avformat_open_input(&dctx->fctx, (*dctx->fakename).c_str(), NULL, NULL); if (av_ret < 0) { err = "Cannot open buffer in libavformat."; goto dfail; } /* * Flush the buffers of our codec's context so we * don't need to re-initialize it. */ avcodec_flush_buffers(dctx->avctx); /* * Call the abomination function to find out * how many streams we have. */ avformat_find_stream_info(dctx->fctx, NULL); /* Free and re-initialize any existing packet. */ av_free_packet(&dctx->inpkt); av_init_packet(&dctx->inpkt); } /* Set our stream index if we need to. */ if (dctx->stream_index == -1) { for(i = 0; i < dctx->fctx->nb_streams; i++) { if (dctx->fctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) { dctx->stream_index = (int) i; break; } } } /* * We don't need to read a new packet in if we are decoding * linearly, since it's still there from the previous iteration. */ if (!next) av_read_frame(dctx->fctx, &dctx->inpkt); /* If we're decoding linearly, there is obviously no offset. */ o = next ? 0 : offset; for(j = 0; j <= o; j++) { while(dctx->inpkt.stream_index != dctx->stream_index) { av_free_packet(&dctx->inpkt); av_read_frame(dctx->fctx, &dctx->inpkt); } /* * Loop until we have a whole frame, since there can be * multi-packet frames. */ av_ret = 0; while(!av_ret) { AVPacket orig = dctx->inpkt; /* * Decoding might not consume out whole packet, so * stash the original packet info, loop until it * is all consumed, and then restore it, it so * we can free it properly. */ while(dctx->inpkt.size > 0) { int r = avcodec_decode_video2(dctx->avctx, out, &av_ret, &dctx->inpkt); dctx->inpkt.size -= r; dctx->inpkt.data += r; } dctx->inpkt = orig; do { av_free_packet(&dctx->inpkt); av_read_frame(dctx->fctx, &dctx->inpkt); } while(dctx->inpkt.stream_index != dctx->stream_index); } } /* * Stash the frame number we just decoded, and the GOP it * is a part of so we can check if we're decoding linearly * later on. */ dctx->last_gop = f.gop; dctx->last_frame = frame_num; return 0; dfail: avformat_close_input(&dctx->fctx); return -1; } <|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) #include "test_common.hh" #include <dune/stuff/common/string.hh> #include <dune/stuff/common/logstreams.hh> #include <dune/stuff/common/exceptions.hh> #include <boost/lexical_cast.hpp> #include <bits/functexcept.h> #include <vector> using namespace Dune::Stuff::Common; using namespace std; TEST(StringTest, ConvertTo) { EXPECT_EQ("9",toString(fromString<int>("9"))); EXPECT_EQ("P",toString(fromString<char>("P"))); EXPECT_EQ(double(0.1), fromString<double>(toString<double>(0.1))); EXPECT_EQ("0.100006", toString(fromString<double>("0.1000055511151231257827021181583404541015625"))); EXPECT_EQ("1",toString(fromString<bool>("1"))); EXPECT_EQ("0",toString(fromString<bool>("0"))); EXPECT_EQ("-1",toString(fromString<long>("-1"))); } TEST(StringTest, Hex) { EXPECT_GT(boost::lexical_cast<HexToString<unsigned long> >(cout), 0u); EXPECT_EQ(boost::lexical_cast<HexToString<unsigned long> >("0x00000F"), 15u); } TEST(StringTest, ConvertFrom) { EXPECT_EQ(9,fromString<int>("9")); EXPECT_EQ(0,fromString<int>("0")); EXPECT_EQ('p',fromString<char>(toString('p'))); EXPECT_EQ(-1,fromString<char>(toString<char>(-1))); EXPECT_THROW(fromString<char>("sd"),Dune::Stuff::Exceptions::wrong_input_given); EXPECT_EQ(true,fromString<bool>("1")); EXPECT_EQ(false,fromString<bool>("0")); EXPECT_THROW(fromString<int>(""), std::invalid_argument); } TEST(StringTest, Whitespace) { EXPECT_EQ("---------", whitespaceify("\t\t\t\t\t\t\t\t\t", '-')); } TEST(StringTest, Tokenizer) { const string seps(" \t;"); const string msg("a t\tkk;;g"); const vector<string> tokens_default = {"a", "t", "kk", "", "g"}; const vector<string> tokens_compressed = {"a", "t", "kk", "g"}; EXPECT_EQ(tokens_default, tokenize(msg, seps, boost::algorithm::token_compress_off)); EXPECT_EQ(tokens_compressed, tokenize(msg, seps, boost::algorithm::token_compress_on)); const string num_msg("-1 2;;4"); vector<int> numbers_default = {-1,2,0,4}; vector<int> numbers_compressed = {-1,2,4}; EXPECT_EQ(numbers_default, tokenize<int>(num_msg, seps, boost::algorithm::token_compress_off)); EXPECT_EQ(numbers_compressed, tokenize<int>(num_msg, seps, boost::algorithm::token_compress_on)); } TEST(StringTest, TimeString) { string ts = stringFromTime(-1); } int main(int argc, char** argv) { test_init(argc, argv); return RUN_ALL_TESTS(); } <commit_msg>[test.common_string] add some tests for fromString/toString<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) #include "test_common.hh" #include <dune/stuff/common/string.hh> #include <dune/stuff/common/logstreams.hh> #include <vector> #include <dune/stuff/common/disable_warnings.hh> # include <dune/common/fmatrix.hh> # include <dune/common/densematrix.hh> # include <dune/common/fvector.hh> # include <dune/common/dynmatrix.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/common/dynvector.hh> #include <dune/common/densevector.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/fvector.hh> #include <dune/stuff/common/fmatrix.hh> #include <dune/stuff/la/container/common.hh> #if HAVE_EIGEN # include <dune/stuff/la/container/eigen.hh> #endif #if HAVE_DUNE_ISTL # include <dune/stuff/la/container/istl.hh> #endif using namespace Dune::Stuff::Common; using namespace std; //define types and expected values for the typed tests template< class MatrixType > struct MatrixStringTestDouble : public ::testing::Test { void check() const { EXPECT_EQ("[1.000000 2.000000; 3.000000 4.000000]", toString(fromString<MatrixType>("[1.0 2; 3.0 4]"))); EXPECT_THROW(fromString<MatrixType>("[1 2; 3 4]", 3, 3), Dune::Stuff::Exceptions::configuration_error); } }; template< class MatrixType > struct MatrixStringTestChar : public ::testing::Test { void check() const { EXPECT_EQ("[1 2; 3 4]", toString(fromString<MatrixType>("[1 2; 3 4]"))); EXPECT_THROW(fromString<MatrixType>("[1 2; 3 4]", 3, 3), Dune::Stuff::Exceptions::configuration_error); } }; template< class VectorType > struct VectorStringTestDouble : public ::testing::Test { void check() const { EXPECT_EQ("[1.000000 2.000000 3.000000]", toString(fromString<VectorType>("[1.0 2 3.0]"))); EXPECT_THROW(fromString<VectorType>("[1.0 2 3.0]", 4), Dune::Stuff::Exceptions::configuration_error); } }; template< class VectorType > struct VectorStringTestInt : public ::testing::Test { void check() const { EXPECT_EQ("[1 2 3]", toString(fromString<VectorType>("[1 2 3]"))); EXPECT_THROW(fromString<VectorType>("[1 2 3]", 4), Dune::Stuff::Exceptions::configuration_error); } }; typedef testing::Types< std::vector< double > , Dune::Stuff::LA::CommonDenseVector< double > , Dune::DynamicVector< double > , Dune::FieldVector< double, 3 > , Dune::Stuff::Common::FieldVector< double, 3 > #if HAVE_EIGEN , Dune::Stuff::LA::EigenDenseVector< double > , Dune::Stuff::LA::EigenMappedDenseVector< double > #endif #if HAVE_DUNE_ISTL , Dune::Stuff::LA::IstlDenseVector< double > #endif > VectorTypesDouble; typedef testing::Types< std::vector< int > , Dune::Stuff::LA::CommonDenseVector< int > , Dune::DynamicVector< int > , Dune::FieldVector< int, 3 > , Dune::Stuff::Common::FieldVector< int, 3 > #if HAVE_DUNE_ISTL , Dune::Stuff::LA::IstlDenseVector< int > #endif > VectorTypesInt; typedef testing::Types< Dune::DynamicMatrix< double > , Dune::Stuff::LA::CommonDenseMatrix< double > , Dune::Stuff::Common::FieldMatrix< double, 2, 2 > , Dune::FieldMatrix< double, 2, 2 > #if HAVE_EIGEN , Dune::Stuff::LA::EigenDenseMatrix< double > #endif > MatrixTypesDouble; typedef testing::Types< Dune::DynamicMatrix< char > , Dune::Stuff::LA::CommonDenseMatrix< char > , Dune::Stuff::Common::FieldMatrix< char, 2, 2 > , Dune::FieldMatrix< char, 2, 2 > #if HAVE_EIGEN , Dune::Stuff::LA::EigenDenseMatrix< char > #endif > MatrixTypesChar; // fromString/toString tests for vector and matrix types TYPED_TEST_CASE(MatrixStringTestDouble, MatrixTypesDouble); TYPED_TEST(MatrixStringTestDouble, CheckDouble) { this->check(); } TYPED_TEST_CASE(MatrixStringTestChar, MatrixTypesChar); TYPED_TEST(MatrixStringTestChar, CheckChar) { this->check(); } TYPED_TEST_CASE(VectorStringTestDouble, VectorTypesDouble); TYPED_TEST(VectorStringTestDouble, CheckDouble) { this->check(); } TYPED_TEST_CASE(VectorStringTestInt, VectorTypesInt); TYPED_TEST(VectorStringTestInt, CheckInt) { this->check(); } // Additional fromString/toString tests TEST(StringTest, ConvertTo) { EXPECT_EQ("9",toString(fromString<int>("9"))); EXPECT_EQ("P",toString(fromString<char>("P"))); EXPECT_EQ(double(0.1), fromString<double>(toString<double>(0.1))); EXPECT_EQ("0.100006", toString(fromString<double>("0.1000055511151231257827021181583404541015625"))); EXPECT_EQ("1",toString(fromString<bool>("1"))); EXPECT_EQ("0",toString(fromString<bool>("0"))); EXPECT_EQ("-1",toString(fromString<long>("-1"))); EXPECT_THROW(fromString<std::vector<std::vector<double>>>("[[1 2] [3 4]]"), Dune::Stuff::Exceptions::wrong_input_given); } TEST(StringTest, ConvertFrom) { EXPECT_EQ(9,fromString<int>("9")); EXPECT_EQ(0,fromString<int>("0")); EXPECT_EQ('p',fromString<char>(toString('p'))); EXPECT_EQ(-1,fromString<char>(toString(char(-1)))); EXPECT_THROW(fromString<char>("sd"),Dune::Stuff::Exceptions::wrong_input_given); EXPECT_EQ(true,fromString<bool>("1")); EXPECT_EQ(false,fromString<bool>("0")); EXPECT_THROW(fromString<int>(""), std::invalid_argument); } // Hex, whitespacify, tokenize, stringFromTime tests TEST(StringTest, Hex) { EXPECT_GT(boost::lexical_cast<HexToString<unsigned long> >(cout), 0u); EXPECT_EQ(boost::lexical_cast<HexToString<unsigned long> >("0x00000F"), 15u); } TEST(StringTest, Whitespace) { EXPECT_EQ("---------", whitespaceify("\t\t\t\t\t\t\t\t\t", '-')); } TEST(StringTest, Tokenizer) { const string seps(" \t;"); const string msg("a t\tkk;;g"); const vector<string> tokens_default = {"a", "t", "kk", "", "g"}; const vector<string> tokens_compressed = {"a", "t", "kk", "g"}; EXPECT_EQ(tokens_default, tokenize(msg, seps, boost::algorithm::token_compress_off)); EXPECT_EQ(tokens_compressed, tokenize(msg, seps, boost::algorithm::token_compress_on)); const string num_msg("-1 2;;4"); vector<int> numbers_default = {-1,2,0,4}; vector<int> numbers_compressed = {-1,2,4}; EXPECT_EQ(numbers_default, tokenize<int>(num_msg, seps, boost::algorithm::token_compress_off)); EXPECT_EQ(numbers_compressed, tokenize<int>(num_msg, seps, boost::algorithm::token_compress_on)); } TEST(StringTest, TimeString) { string ts = stringFromTime(-1); } // Run tests int main(int argc, char** argv) { test_init(argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// AddTaskChargedJetsHadronCF.C AliAnalysisTaskChargedJetsHadronCF* AddTaskChargedJetsHadronCF( UInt_t physSel = 0, const char *trackArray = "tracks", const char *jetArray = "jets", const char *rhoObject = "Rho", Double_t jetRadius = 0.2, Double_t minJetEta = 0.7, Double_t minLeadingHadronPt = 0.0, Double_t minJetPt = 0.15, Double_t minTrackPt = 0.15, Double_t minJetAreaPerc = 0.557, const char *suffix = "" ) { cout << " ############ MACRO EXECUTION STARTED: AddTaskChargedJetsHadronCF.C ############\n"; //============================================================================== // Prepare analysis manager, containers, etc. AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskChargedJetsHadronCF", "No analysis manager to connect to."); return NULL; } if (!mgr->GetInputEventHandler()) { ::Error("AddTaskChargedJetsHadronCF", "This task requires an input event handler"); return NULL; } TString name("AliAnalysisTaskChargedJetsHadronCF"); if (strcmp(jetArray,"")) { name += "_"; name += jetArray; } if (strcmp(rhoObject,"")) { name += "_"; name += rhoObject; } if (strcmp(suffix,"")) { name += "_"; name += suffix; } AliAnalysisDataContainer* contHistos = mgr->CreateContainer(Form("%s_histos", name.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:ChargedJetsHadronCF", AliAnalysisManager::GetCommonFileName())); //============================================================================== // Adding and configuring tasks AliAnalysisTaskChargedJetsHadronCF* jetTask = new AliAnalysisTaskChargedJetsHadronCF(name); jetTask->SetNeedEmcalGeom(kFALSE); jetTask->SetVzRange(-10.,10.); jetTask->SetOffTrigger(physSel); AliParticleContainer *trackCont = jetTask->AddParticleContainer(trackArray); trackCont->SetFilterHybridTracks(kTRUE); trackCont->SetParticlePtCut(minTrackPt); AliJetContainer *jetCont = jetTask->AddJetContainer(jetArray,0,jetRadius); if (jetCont) { jetCont->SetRhoName(rhoObject); jetCont->SetPercAreaCut(minJetAreaPerc); jetCont->SetJetPtCut(minJetPt); jetCont->SetLeadingHadronType(0); jetCont->SetPtBiasJetTrack(minLeadingHadronPt); jetCont->SetJetEtaLimits(-minJetEta, +minJetEta); jetCont->ConnectParticleContainer(trackCont); jetCont->SetMaxTrackPt(1000); } mgr->AddTask(jetTask); //============================================================================== // Finalization mgr->ConnectInput (jetTask, 0, mgr->GetCommonInputContainer() ); mgr->ConnectOutput (jetTask, 1, contHistos ); cout << " ############ MACRO EXECUTION DONE: AddTaskChargedJetsHadronCF.C ############\n"; return jetTask; } <commit_msg>Changed default jet cuts<commit_after>// AddTaskChargedJetsHadronCF.C AliAnalysisTaskChargedJetsHadronCF* AddTaskChargedJetsHadronCF( UInt_t physSel = 0, const char *trackArray = "tracks", const char *jetArray = "jets", const char *rhoObject = "Rho", Double_t jetRadius = 0.2, Double_t minJetEta = 0.7, Double_t minLeadingHadronPt = 0.0, Double_t minJetPt = 0.15, Double_t minTrackPt = 0.15, Double_t minJetAreaPerc = 0.557, const char *suffix = "" ) { cout << " ############ MACRO EXECUTION STARTED: AddTaskChargedJetsHadronCF.C ############\n"; //============================================================================== // Prepare analysis manager, containers, etc. AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskChargedJetsHadronCF", "No analysis manager to connect to."); return NULL; } if (!mgr->GetInputEventHandler()) { ::Error("AddTaskChargedJetsHadronCF", "This task requires an input event handler"); return NULL; } TString name("AliAnalysisTaskChargedJetsHadronCF"); if (strcmp(jetArray,"")) { name += "_"; name += jetArray; } if (strcmp(rhoObject,"")) { name += "_"; name += rhoObject; } if (strcmp(suffix,"")) { name += "_"; name += suffix; } AliAnalysisDataContainer* contHistos = mgr->CreateContainer(Form("%s_histos", name.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:ChargedJetsHadronCF", AliAnalysisManager::GetCommonFileName())); //============================================================================== // Adding and configuring tasks AliAnalysisTaskChargedJetsHadronCF* jetTask = new AliAnalysisTaskChargedJetsHadronCF(name); jetTask->SetNeedEmcalGeom(kFALSE); jetTask->SetVzRange(-10.,10.); jetTask->SetOffTrigger(physSel); AliParticleContainer *trackCont = jetTask->AddParticleContainer(trackArray); trackCont->SetFilterHybridTracks(kTRUE); trackCont->SetParticlePtCut(minTrackPt); AliJetContainer *jetCont = jetTask->AddJetContainer(jetArray,6,jetRadius); if (jetCont) { jetCont->SetRhoName(rhoObject); jetCont->SetPercAreaCut(minJetAreaPerc); jetCont->SetJetPtCut(minJetPt); jetCont->SetLeadingHadronType(0); jetCont->SetPtBiasJetTrack(minLeadingHadronPt); jetCont->SetJetEtaLimits(-minJetEta, +minJetEta); jetCont->ConnectParticleContainer(trackCont); jetCont->SetMaxTrackPt(1000); } mgr->AddTask(jetTask); //============================================================================== // Finalization mgr->ConnectInput (jetTask, 0, mgr->GetCommonInputContainer() ); mgr->ConnectOutput (jetTask, 1, contHistos ); cout << " ############ MACRO EXECUTION DONE: AddTaskChargedJetsHadronCF.C ############\n"; return jetTask; } <|endoftext|>
<commit_before>#include <iomanip> #include <cassert> #include "SDShared.hpp" #include "exception/exception.hpp" SDShared::SDShared(const std::vector< std::pair<int, int> >& coords, const CoordConverter& coordConverter, unsigned int index): std::vector< std::pair<int ,int> >(coords), _coordConverter(coordConverter), _id(index) { } void SDShared::execEquation(eqType& eqFunc, const std::map< std::string, Quantity<real>* >& quantityMap) { eqFunc(*this, quantityMap); } void SDShared::addDirichletCell(std::pair < std::pair<int, int>, std::map<std::string, real> > d) { for (auto p : d.second) _dirichletCellMap[p.first][convert(d.first.first, d.first.second)] = p.second; } void SDShared::addTimeVaryingCell(std::pair < std::pair<int, int>, std::map<std::string, real> > d) { for (auto p : d.second) _timeVaryingCellMap[p.first][convert(d.first.first, d.first.second)] = p.second; } void SDShared::addNeumannCell(std::pair< std::pair<int, int>, std::pair< std::pair<int, int>, std::map<std::string, real> > > n) { for (auto p : n.second.second) _neumannCellMap[p.first][convert(n.first.first, n.first.second)] = std::make_pair(convert(n.second.first.first, n.second.first.second), p.second); } size_t SDShared::getOverlapCellNumber(unsigned int sddId) const { if (_sendIndexMap.find(sddId) == _sendIndexMap.end()) return 0; return _sendIndexMap.at(sddId).size(); } void SDShared::addOverlapCell(unsigned int sddId, size_t sendIndex, size_t recvIndex) { _sendIndexMap[sddId].push_back(sendIndex); _recvIndexMap[sddId].push_back(recvIndex); } void SDShared::updateBoundaryCells(Quantity<real>* quantity, const real& t) const { updateDirichletCells(quantity); updateNeumannCells(quantity); updateTimeVaryingCells(quantity, t); } void SDShared::updateDirichletCells(Quantity<real>* quantity) const { auto& qty(*quantity); // No dirichlet values stored for this quantity. std::map<std::string, std::unordered_map< size_t, real >>::const_iterator it = _dirichletCellMap.find(qty.getName()); if (it == _dirichletCellMap.end()) return; const std::unordered_map< size_t, real>& dirichletValue = it->second; // This cannot be. assert(dirichletValue.size() != 0); for (auto it = dirichletValue.begin(); it != dirichletValue.end(); ++it) qty.set0(it->second, it->first); } void SDShared::updateTimeVaryingCells(Quantity<real>* quantity, const real& t) const { auto& qty(*quantity); // No dirichlet values stored for this quantity. std::map<std::string, std::unordered_map< size_t, real >>::const_iterator it = _timeVaryingCellMap.find(qty.getName()); if (it == _timeVaryingCellMap.end()) return; const std::unordered_map< size_t, real>& parameterValue = it->second; // This cannot be. assert(parameterValue.size() != 0); for (auto it = parameterValue.begin(); it != parameterValue.end(); ++it) { real v = 1. - it->second * t; //std::cout << "v: " << std::defaultfloat << std::setprecision(Number::max_digits10) << v << std::endl; qty.set0(v, it->first); } } void SDShared::updateNeumannCells(Quantity<real>* quantity) const { auto& qty(*quantity); // No dirichlet values stored for this quantity. std::map<std::string, std::unordered_map< size_t, std::pair<size_t, real>>>::const_iterator cit = _neumannCellMap.find(qty.getName()); if (cit == _neumannCellMap.end()) return; const std::unordered_map< size_t, std::pair<size_t, real>>& neumannCoeff = cit->second; // This cannot be. assert(neumannCoeff.size() != 0); for (auto it = neumannCoeff.begin(); it != neumannCoeff.end(); ++it) { qty.set0(it->second.second * qty.get0(it->second.first), it->first); } } void SDShared::copyOverlapCellIn(const std::map< std::string, Quantity<real>* >& quantityMap, const std::unordered_map<unsigned int, real* >& buffer) const { const size_t plus(quantityMap.size()); for (auto const& it: _sendIndexMap) { size_t startPos(_bufferStartPos.at(it.first) * quantityMap.size()); real* sddBuffer(buffer.at(it.first)); for (const auto p: quantityMap) { auto& qty(*p.second); size_t index(startPos++); for (const unsigned int i : it.second) { sddBuffer[index] = qty.get0(i); index += plus; } } } } void SDShared::copyOverlapCellFrom(const std::map< std::string, Quantity<real>* >& quantityMap, const std::unordered_map<unsigned int, real* >& buffer) const { const size_t plus(quantityMap.size()); for (auto const& it: _recvIndexMap) { real* sddBuffer(buffer.at(it.first)); size_t startPos(_bufferStartPos.at(it.first) * plus); for (const auto p: quantityMap) { auto& qty(*p.second); size_t index(startPos++); for (const unsigned int i : it.second) { qty.set0(sddBuffer[index], i); index += plus; } } } } <commit_msg>sign correction<commit_after>#include <iomanip> #include <cassert> #include "SDShared.hpp" #include "exception/exception.hpp" SDShared::SDShared(const std::vector< std::pair<int, int> >& coords, const CoordConverter& coordConverter, unsigned int index): std::vector< std::pair<int ,int> >(coords), _coordConverter(coordConverter), _id(index) { } void SDShared::execEquation(eqType& eqFunc, const std::map< std::string, Quantity<real>* >& quantityMap) { eqFunc(*this, quantityMap); } void SDShared::addDirichletCell(std::pair < std::pair<int, int>, std::map<std::string, real> > d) { for (auto p : d.second) _dirichletCellMap[p.first][convert(d.first.first, d.first.second)] = p.second; } void SDShared::addTimeVaryingCell(std::pair < std::pair<int, int>, std::map<std::string, real> > d) { for (auto p : d.second) _timeVaryingCellMap[p.first][convert(d.first.first, d.first.second)] = p.second; } void SDShared::addNeumannCell(std::pair< std::pair<int, int>, std::pair< std::pair<int, int>, std::map<std::string, real> > > n) { for (auto p : n.second.second) _neumannCellMap[p.first][convert(n.first.first, n.first.second)] = std::make_pair(convert(n.second.first.first, n.second.first.second), p.second); } size_t SDShared::getOverlapCellNumber(unsigned int sddId) const { if (_sendIndexMap.find(sddId) == _sendIndexMap.end()) return 0; return _sendIndexMap.at(sddId).size(); } void SDShared::addOverlapCell(unsigned int sddId, size_t sendIndex, size_t recvIndex) { _sendIndexMap[sddId].push_back(sendIndex); _recvIndexMap[sddId].push_back(recvIndex); } void SDShared::updateBoundaryCells(Quantity<real>* quantity, const real& t) const { updateDirichletCells(quantity); updateNeumannCells(quantity); updateTimeVaryingCells(quantity, t); } void SDShared::updateDirichletCells(Quantity<real>* quantity) const { auto& qty(*quantity); // No dirichlet values stored for this quantity. std::map<std::string, std::unordered_map< size_t, real >>::const_iterator it = _dirichletCellMap.find(qty.getName()); if (it == _dirichletCellMap.end()) return; const std::unordered_map< size_t, real>& dirichletValue = it->second; // This cannot be. assert(dirichletValue.size() != 0); for (auto it = dirichletValue.begin(); it != dirichletValue.end(); ++it) qty.set0(it->second, it->first); } void SDShared::updateTimeVaryingCells(Quantity<real>* quantity, const real& t) const { auto& qty(*quantity); // No dirichlet values stored for this quantity. std::map<std::string, std::unordered_map< size_t, real >>::const_iterator it = _timeVaryingCellMap.find(qty.getName()); if (it == _timeVaryingCellMap.end()) return; const std::unordered_map< size_t, real>& parameterValue = it->second; // This cannot be. assert(parameterValue.size() != 0); for (auto it = parameterValue.begin(); it != parameterValue.end(); ++it) { real v = 1. + it->second * t; //std::cout << "v: " << std::defaultfloat << std::setprecision(Number::max_digits10) << v << std::endl; qty.set0(v, it->first); } } void SDShared::updateNeumannCells(Quantity<real>* quantity) const { auto& qty(*quantity); // No dirichlet values stored for this quantity. std::map<std::string, std::unordered_map< size_t, std::pair<size_t, real>>>::const_iterator cit = _neumannCellMap.find(qty.getName()); if (cit == _neumannCellMap.end()) return; const std::unordered_map< size_t, std::pair<size_t, real>>& neumannCoeff = cit->second; // This cannot be. assert(neumannCoeff.size() != 0); for (auto it = neumannCoeff.begin(); it != neumannCoeff.end(); ++it) { qty.set0(it->second.second * qty.get0(it->second.first), it->first); } } void SDShared::copyOverlapCellIn(const std::map< std::string, Quantity<real>* >& quantityMap, const std::unordered_map<unsigned int, real* >& buffer) const { const size_t plus(quantityMap.size()); for (auto const& it: _sendIndexMap) { size_t startPos(_bufferStartPos.at(it.first) * quantityMap.size()); real* sddBuffer(buffer.at(it.first)); for (const auto p: quantityMap) { auto& qty(*p.second); size_t index(startPos++); for (const unsigned int i : it.second) { sddBuffer[index] = qty.get0(i); index += plus; } } } } void SDShared::copyOverlapCellFrom(const std::map< std::string, Quantity<real>* >& quantityMap, const std::unordered_map<unsigned int, real* >& buffer) const { const size_t plus(quantityMap.size()); for (auto const& it: _recvIndexMap) { real* sddBuffer(buffer.at(it.first)); size_t startPos(_bufferStartPos.at(it.first) * plus); for (const auto p: quantityMap) { auto& qty(*p.second); size_t index(startPos++); for (const unsigned int i : it.second) { qty.set0(sddBuffer[index], i); index += plus; } } } } <|endoftext|>
<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__) #include <Rtypes.h> #include <TString.h> #include "AliAnalysisTaskHypertriton3.h" #include "AliAnalysisManager.h" #include "AliAnalysisDataContainer.h" #include "AliMCEventHandler.h" #include "AliPID.h" #endif AliAnalysisTaskHypertriton3 *AddTaskHypertriton3(Bool_t readMC=kFALSE, Bool_t fillTree=kFALSE, TString suffix = ""){ // Creates, configures and attaches to the train the task for pi, K , p spectra // with ITS standalone tracks // Get the pointer to the existing analysis manager via the static access method. //============================================================================== ::Info("AddTaskHypertriton3","Adding a new task with this settings readMC = %i",readMC); AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskHypertriton3", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskHypertriton3", "This task requires an input event handler"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" if(type.Contains("AOD")){ ::Error("AddTaskHypertriton3", "This task requires to run on ESD"); return NULL; } // Add MC handler (for kinematics) if(readMC){ AliMCEventHandler* handler = new AliMCEventHandler; handler->SetReadTR(kFALSE); mgr->SetMCtruthEventHandler(handler); } // Create and configure the task TString tskname = "hypertriton"; tskname.Append(Form("%s",suffix.Data())); AliAnalysisTaskHypertriton3 *taskhyp = new AliAnalysisTaskHypertriton3(); taskhyp->SetReadMC(readMC); taskhyp->SetFillTree(fillTree); mgr->AddTask(taskhyp); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== TString outputFileName = AliAnalysisManager::GetCommonFileName(); outputFileName += ":ESDHypertriton"; AliAnalysisDataContainer *coutput =0x0; coutput = mgr->CreateContainer(Form("strogolo_%s",tskname.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, AliAnalysisManager::GetCommonFileName()); mgr->ConnectInput(taskhyp, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskhyp, 1, coutput); if(fillTree){ AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("trogolo_HyperTree", TTree::Class(), AliAnalysisManager::kOutputContainer, "trogolo_Hyper3.root"); coutput2->SetSpecialOutput(); mgr->ConnectOutput(taskhyp, 2, coutput2); } return taskhyp; } <commit_msg>Change output name<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__) #include <Rtypes.h> #include <TString.h> #include "AliAnalysisTaskHypertriton3.h" #include "AliAnalysisManager.h" #include "AliAnalysisDataContainer.h" #include "AliMCEventHandler.h" #include "AliPID.h" #endif AliAnalysisTaskHypertriton3 *AddTaskHypertriton3(Bool_t readMC=kFALSE, Bool_t fillTree=kFALSE, TString suffix = ""){ // Creates, configures and attaches to the train the task for pi, K , p spectra // with ITS standalone tracks // Get the pointer to the existing analysis manager via the static access method. //============================================================================== ::Info("AddTaskHypertriton3","Adding a new task with this settings readMC = %i",readMC); AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskHypertriton3", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskHypertriton3", "This task requires an input event handler"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" if(type.Contains("AOD")){ ::Error("AddTaskHypertriton3", "This task requires to run on ESD"); return NULL; } // Add MC handler (for kinematics) if(readMC){ AliMCEventHandler* handler = new AliMCEventHandler; handler->SetReadTR(kFALSE); mgr->SetMCtruthEventHandler(handler); } // Create and configure the task TString tskname = "hypertriton"; tskname.Append(Form("%s",suffix.Data())); AliAnalysisTaskHypertriton3 *taskhyp = new AliAnalysisTaskHypertriton3(); taskhyp->SetReadMC(readMC); taskhyp->SetFillTree(fillTree); mgr->AddTask(taskhyp); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== TString outputFileName = AliAnalysisManager::GetCommonFileName(); outputFileName += ":ESDHypertriton"; AliAnalysisDataContainer *coutput =0x0; coutput = mgr->CreateContainer(Form("strogolo_%s",tskname.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, AliAnalysisManager::GetCommonFileName()); mgr->ConnectInput(taskhyp, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskhyp, 1, coutput); if(fillTree){ AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("trogolo_HyperTree", TTree::Class(), AliAnalysisManager::kOutputContainer, AliAnalysisManager::GetCommonFileName()); coutput2->SetSpecialOutput(); mgr->ConnectOutput(taskhyp, 2, coutput2); } return taskhyp; } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: hldoctp.cxx,v $ * $Revision: 1.28 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_cui.hxx" #include "cuihyperdlg.hxx" #include <unotools/localfilehelper.hxx> #include <sfx2/filedlghelper.hxx> #include "com/sun/star/ui/dialogs/TemplateDescription.hpp" #include "hldoctp.hxx" #include "hyperdlg.hrc" #include "hlmarkwn_def.hxx" //ADD CHINA001 sal_Char __READONLY_DATA sHash[] = "#"; sal_Char __READONLY_DATA sFileScheme[] = INET_FILE_SCHEME; sal_Char __READONLY_DATA sPortalFileScheme[] = "vnd.sun.star.wfs://"; sal_Char __READONLY_DATA sNewsSRVScheme[] = "news://"; // TODO news:// is nonsense sal_Char __READONLY_DATA sHTTPScheme[] = INET_HTTP_SCHEME; /************************************************************************* |* |* Contructor / Destructor |* |************************************************************************/ SvxHyperlinkDocTp::SvxHyperlinkDocTp ( Window *pParent, const SfxItemSet& rItemSet) : SvxHyperlinkTabPageBase ( pParent, CUI_RES( RID_SVXPAGE_HYPERLINK_DOCUMENT ), rItemSet ), maGrpDocument ( this, CUI_RES (GRP_DOCUMENT) ), maFtPath ( this, CUI_RES (FT_PATH_DOC) ), maCbbPath ( this, INET_PROT_FILE ), maBtFileopen ( this, CUI_RES (BTN_FILEOPEN) ), maGrpTarget ( this, CUI_RES (GRP_TARGET) ), maFtTarget ( this, CUI_RES (FT_TARGET_DOC) ), maEdTarget ( this, CUI_RES (ED_TARGET_DOC) ), maFtURL ( this, CUI_RES (FT_URL) ), maFtFullURL ( this, CUI_RES (FT_FULL_URL) ), maBtBrowse ( this, CUI_RES (BTN_BROWSE) ), mbMarkWndOpen ( FALSE ) { // Set HC bitmaps and disable display of bitmap names. maBtBrowse.SetModeImage( Image( CUI_RES( IMG_BROWSE_HC ) ), BMP_COLOR_HIGHCONTRAST ); maBtBrowse.EnableTextDisplay (FALSE); maBtFileopen.SetModeImage( Image( CUI_RES( IMG_FILEOPEN_HC ) ), BMP_COLOR_HIGHCONTRAST ); maBtFileopen.EnableTextDisplay (FALSE); InitStdControls(); FreeResource(); // Init URL-Box (pos&size, Open-Handler) maCbbPath.SetPosSizePixel ( LogicToPixel( Point( COL_2, 15 ), MAP_APPFONT ), LogicToPixel( Size ( 176 - COL_DIFF, 60), MAP_APPFONT ) ); maCbbPath.Show(); String aFileScheme( INET_FILE_SCHEME, RTL_TEXTENCODING_ASCII_US ); maCbbPath.SetBaseURL(aFileScheme); maCbbPath.SetHelpId( HID_HYPERDLG_DOC_PATH ); SetExchangeSupport (); // overload handlers maBtFileopen.SetClickHdl ( LINK ( this, SvxHyperlinkDocTp, ClickFileopenHdl_Impl ) ); maBtBrowse.SetClickHdl ( LINK ( this, SvxHyperlinkDocTp, ClickTargetHdl_Impl ) ); maCbbPath.SetModifyHdl ( LINK ( this, SvxHyperlinkDocTp, ModifiedPathHdl_Impl ) ); maEdTarget.SetModifyHdl ( LINK ( this, SvxHyperlinkDocTp, ModifiedTargetHdl_Impl ) ); maCbbPath.SetLoseFocusHdl( LINK ( this, SvxHyperlinkDocTp, LostFocusPathHdl_Impl ) ); maTimer.SetTimeoutHdl ( LINK ( this, SvxHyperlinkDocTp, TimeoutHdl_Impl ) ); } SvxHyperlinkDocTp::~SvxHyperlinkDocTp () { } /************************************************************************* |* |* Fill all dialog-controls except controls in groupbox "more..." |* |************************************************************************/ void SvxHyperlinkDocTp::FillDlgFields ( String& aStrURL ) { INetURLObject aURL ( aStrURL ); String aStrMark; xub_StrLen nPos = aStrURL.SearchAscii( sHash ); // path maCbbPath.SetText ( aStrURL.Copy( 0, ( nPos == STRING_NOTFOUND ? aStrURL.Len() : nPos ) ) ); // set target in document at editfield if ( nPos != STRING_NOTFOUND && nPos<aStrURL.Len()-1 ) aStrMark = aStrURL.Copy( nPos+1, aStrURL.Len() ); maEdTarget.SetText ( aStrMark ); ModifiedPathHdl_Impl ( NULL ); } /************************************************************************* |* |* retrieve current url-string |* |************************************************************************/ String SvxHyperlinkDocTp::GetCurrentURL () { // get data from dialog-controls String aStrURL; String aStrPath ( maCbbPath.GetText() ); const String aBaseURL ( maCbbPath.GetBaseURL() ); String aStrMark( maEdTarget.GetText() ); if ( aStrPath != aEmptyStr ) { INetURLObject aURL( aStrPath ); if ( aURL.GetProtocol() != INET_PROT_NOT_VALID ) // maybe the path is already a valid aStrURL = aStrPath; // hyperlink, then we can use this path directly else utl::LocalFileHelper::ConvertSystemPathToURL( aStrPath, aBaseURL, aStrURL ); //#105788# always create a URL even if it is not valid if( aStrURL == aEmptyStr ) aStrURL = aStrPath; } if( aStrMark != aEmptyStr ) { aStrURL.AppendAscii( sHash ); aStrURL += aStrMark; } return aStrURL; } /************************************************************************* |* |* retrieve and prepare data from dialog-fields |* |************************************************************************/ void SvxHyperlinkDocTp::GetCurentItemData ( String& aStrURL, String& aStrName, String& aStrIntName, String& aStrFrame, SvxLinkInsertMode& eMode ) { // get data from standard-fields aStrURL = GetCurrentURL(); if( aStrURL.EqualsIgnoreCaseAscii( sFileScheme ) || aStrURL.EqualsIgnoreCaseAscii( sPortalFileScheme ) ) aStrURL=aEmptyStr; GetDataFromCommonFields( aStrName, aStrIntName, aStrFrame, eMode ); } /************************************************************************* |* |* static method to create Tabpage |* |************************************************************************/ IconChoicePage* SvxHyperlinkDocTp::Create( Window* pWindow, const SfxItemSet& rItemSet ) { return( new SvxHyperlinkDocTp( pWindow, rItemSet ) ); } /************************************************************************* |* |* Set initial focus |* |************************************************************************/ void SvxHyperlinkDocTp::SetInitFocus() { maCbbPath.GrabFocus(); } /************************************************************************* |* |* Click on imagebutton : fileopen |* |************************************************************************/ IMPL_LINK ( SvxHyperlinkDocTp, ClickFileopenHdl_Impl, void *, EMPTYARG ) { // Open Fileopen-Dialog ::sfx2::FileDialogHelper aDlg( com::sun::star::ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE, 0, GetParent() ); String aOldURL( GetCurrentURL() ); if( aOldURL.EqualsIgnoreCaseAscii( sFileScheme, 0, sizeof( sFileScheme ) - 1 ) || aOldURL.EqualsIgnoreCaseAscii( sPortalFileScheme, 0, sizeof( sFileScheme ) - 1 ) ) { aDlg.SetDisplayDirectory( aOldURL ); } DisableClose( sal_True ); ErrCode nError = aDlg.Execute(); DisableClose( sal_False ); if ( ERRCODE_NONE == nError ) { String aURL( aDlg.GetPath() ); String aPath; utl::LocalFileHelper::ConvertURLToSystemPath( aURL, aPath ); maCbbPath.SetBaseURL( aURL ); maCbbPath.SetText( aPath ); if ( aOldURL != GetCurrentURL() ) ModifiedPathHdl_Impl (NULL); } return( 0L ); } /************************************************************************* |* |* Click on imagebutton : target |* |************************************************************************/ IMPL_LINK ( SvxHyperlinkDocTp, ClickTargetHdl_Impl, void *, EMPTYARG ) { if ( GetPathType ( maStrURL ) == Type_ExistsFile || maStrURL == aEmptyStr || maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) || maStrURL.EqualsIgnoreCaseAscii( sPortalFileScheme ) || maStrURL.SearchAscii( sHash ) == 0 ) { mpMarkWnd->SetError( LERR_NOERROR ); EnterWait(); if ( maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) || maStrURL.EqualsIgnoreCaseAscii( sPortalFileScheme ) ) mpMarkWnd->RefreshTree ( aEmptyStr ); else mpMarkWnd->RefreshTree ( maStrURL ); LeaveWait(); } else mpMarkWnd->SetError( LERR_DOCNOTOPEN ); ShowMarkWnd (); return( 0L ); } /************************************************************************* |* |* Contens of combobox "Path" modified |* |************************************************************************/ IMPL_LINK ( SvxHyperlinkDocTp, ModifiedPathHdl_Impl, void *, EMPTYARG ) { maStrURL = GetCurrentURL(); maTimer.SetTimeout( 2500 ); maTimer.Start(); maFtFullURL.SetText( maStrURL ); return( 0L ); } /************************************************************************* |* |* If path-field was modify, to browse the new doc after timeout |* |************************************************************************/ IMPL_LINK ( SvxHyperlinkDocTp, TimeoutHdl_Impl, Timer *, EMPTYARG ) { if ( IsMarkWndVisible() && ( GetPathType( maStrURL )==Type_ExistsFile || maStrURL == aEmptyStr || maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ) ) { EnterWait(); if ( maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) || maStrURL.EqualsIgnoreCaseAscii( sPortalFileScheme ) ) mpMarkWnd->RefreshTree ( aEmptyStr ); else mpMarkWnd->RefreshTree ( maStrURL ); LeaveWait(); } return( 0L ); } /************************************************************************* |* |* Contens of editfield "Target" modified |* |************************************************************************/ IMPL_LINK ( SvxHyperlinkDocTp, ModifiedTargetHdl_Impl, void *, EMPTYARG ) { maStrURL = GetCurrentURL(); if ( IsMarkWndVisible() ) mpMarkWnd->SelectEntry ( maEdTarget.GetText() ); maFtFullURL.SetText( maStrURL ); return( 0L ); } /************************************************************************* |* |* editfield "Target" lost focus |* |************************************************************************/ IMPL_LINK ( SvxHyperlinkDocTp, LostFocusPathHdl_Impl, void *, EMPTYARG ) { maStrURL = GetCurrentURL(); maFtFullURL.SetText( maStrURL ); return (0L); } /************************************************************************* |* |* Get String from Bookmark-Wnd |* |************************************************************************/ void SvxHyperlinkDocTp::SetMarkStr ( String& aStrMark ) { maEdTarget.SetText ( aStrMark ); ModifiedTargetHdl_Impl ( NULL ); } /************************************************************************* |* |* retrieve kind of pathstr |* |************************************************************************/ SvxHyperlinkDocTp::EPathType SvxHyperlinkDocTp::GetPathType ( String& aStrPath ) { INetURLObject aURL( aStrPath, INET_PROT_FILE ); if( aURL.HasError() ) return Type_Invalid; else return Type_ExistsFile; } <commit_msg>#161490# removed scheme vnd.sun.star.wfs<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: hldoctp.cxx,v $ * $Revision: 1.28 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_cui.hxx" #include "cuihyperdlg.hxx" #include <unotools/localfilehelper.hxx> #include <sfx2/filedlghelper.hxx> #include "com/sun/star/ui/dialogs/TemplateDescription.hpp" #include "hldoctp.hxx" #include "hyperdlg.hrc" #include "hlmarkwn_def.hxx" //ADD CHINA001 sal_Char __READONLY_DATA sHash[] = "#"; sal_Char __READONLY_DATA sFileScheme[] = INET_FILE_SCHEME; sal_Char __READONLY_DATA sNewsSRVScheme[] = "news://"; // TODO news:// is nonsense sal_Char __READONLY_DATA sHTTPScheme[] = INET_HTTP_SCHEME; /************************************************************************* |* |* Contructor / Destructor |* |************************************************************************/ SvxHyperlinkDocTp::SvxHyperlinkDocTp ( Window *pParent, const SfxItemSet& rItemSet) : SvxHyperlinkTabPageBase ( pParent, CUI_RES( RID_SVXPAGE_HYPERLINK_DOCUMENT ), rItemSet ), maGrpDocument ( this, CUI_RES (GRP_DOCUMENT) ), maFtPath ( this, CUI_RES (FT_PATH_DOC) ), maCbbPath ( this, INET_PROT_FILE ), maBtFileopen ( this, CUI_RES (BTN_FILEOPEN) ), maGrpTarget ( this, CUI_RES (GRP_TARGET) ), maFtTarget ( this, CUI_RES (FT_TARGET_DOC) ), maEdTarget ( this, CUI_RES (ED_TARGET_DOC) ), maFtURL ( this, CUI_RES (FT_URL) ), maFtFullURL ( this, CUI_RES (FT_FULL_URL) ), maBtBrowse ( this, CUI_RES (BTN_BROWSE) ), mbMarkWndOpen ( FALSE ) { // Set HC bitmaps and disable display of bitmap names. maBtBrowse.SetModeImage( Image( CUI_RES( IMG_BROWSE_HC ) ), BMP_COLOR_HIGHCONTRAST ); maBtBrowse.EnableTextDisplay (FALSE); maBtFileopen.SetModeImage( Image( CUI_RES( IMG_FILEOPEN_HC ) ), BMP_COLOR_HIGHCONTRAST ); maBtFileopen.EnableTextDisplay (FALSE); InitStdControls(); FreeResource(); // Init URL-Box (pos&size, Open-Handler) maCbbPath.SetPosSizePixel ( LogicToPixel( Point( COL_2, 15 ), MAP_APPFONT ), LogicToPixel( Size ( 176 - COL_DIFF, 60), MAP_APPFONT ) ); maCbbPath.Show(); String aFileScheme( INET_FILE_SCHEME, RTL_TEXTENCODING_ASCII_US ); maCbbPath.SetBaseURL(aFileScheme); maCbbPath.SetHelpId( HID_HYPERDLG_DOC_PATH ); SetExchangeSupport (); // overload handlers maBtFileopen.SetClickHdl ( LINK ( this, SvxHyperlinkDocTp, ClickFileopenHdl_Impl ) ); maBtBrowse.SetClickHdl ( LINK ( this, SvxHyperlinkDocTp, ClickTargetHdl_Impl ) ); maCbbPath.SetModifyHdl ( LINK ( this, SvxHyperlinkDocTp, ModifiedPathHdl_Impl ) ); maEdTarget.SetModifyHdl ( LINK ( this, SvxHyperlinkDocTp, ModifiedTargetHdl_Impl ) ); maCbbPath.SetLoseFocusHdl( LINK ( this, SvxHyperlinkDocTp, LostFocusPathHdl_Impl ) ); maTimer.SetTimeoutHdl ( LINK ( this, SvxHyperlinkDocTp, TimeoutHdl_Impl ) ); } SvxHyperlinkDocTp::~SvxHyperlinkDocTp () { } /************************************************************************* |* |* Fill all dialog-controls except controls in groupbox "more..." |* |************************************************************************/ void SvxHyperlinkDocTp::FillDlgFields ( String& aStrURL ) { INetURLObject aURL ( aStrURL ); String aStrMark; xub_StrLen nPos = aStrURL.SearchAscii( sHash ); // path maCbbPath.SetText ( aStrURL.Copy( 0, ( nPos == STRING_NOTFOUND ? aStrURL.Len() : nPos ) ) ); // set target in document at editfield if ( nPos != STRING_NOTFOUND && nPos<aStrURL.Len()-1 ) aStrMark = aStrURL.Copy( nPos+1, aStrURL.Len() ); maEdTarget.SetText ( aStrMark ); ModifiedPathHdl_Impl ( NULL ); } /************************************************************************* |* |* retrieve current url-string |* |************************************************************************/ String SvxHyperlinkDocTp::GetCurrentURL () { // get data from dialog-controls String aStrURL; String aStrPath ( maCbbPath.GetText() ); const String aBaseURL ( maCbbPath.GetBaseURL() ); String aStrMark( maEdTarget.GetText() ); if ( aStrPath != aEmptyStr ) { INetURLObject aURL( aStrPath ); if ( aURL.GetProtocol() != INET_PROT_NOT_VALID ) // maybe the path is already a valid aStrURL = aStrPath; // hyperlink, then we can use this path directly else utl::LocalFileHelper::ConvertSystemPathToURL( aStrPath, aBaseURL, aStrURL ); //#105788# always create a URL even if it is not valid if( aStrURL == aEmptyStr ) aStrURL = aStrPath; } if( aStrMark != aEmptyStr ) { aStrURL.AppendAscii( sHash ); aStrURL += aStrMark; } return aStrURL; } /************************************************************************* |* |* retrieve and prepare data from dialog-fields |* |************************************************************************/ void SvxHyperlinkDocTp::GetCurentItemData ( String& aStrURL, String& aStrName, String& aStrIntName, String& aStrFrame, SvxLinkInsertMode& eMode ) { // get data from standard-fields aStrURL = GetCurrentURL(); if( aStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ) aStrURL=aEmptyStr; GetDataFromCommonFields( aStrName, aStrIntName, aStrFrame, eMode ); } /************************************************************************* |* |* static method to create Tabpage |* |************************************************************************/ IconChoicePage* SvxHyperlinkDocTp::Create( Window* pWindow, const SfxItemSet& rItemSet ) { return( new SvxHyperlinkDocTp( pWindow, rItemSet ) ); } /************************************************************************* |* |* Set initial focus |* |************************************************************************/ void SvxHyperlinkDocTp::SetInitFocus() { maCbbPath.GrabFocus(); } /************************************************************************* |* |* Click on imagebutton : fileopen |* |************************************************************************/ IMPL_LINK ( SvxHyperlinkDocTp, ClickFileopenHdl_Impl, void *, EMPTYARG ) { // Open Fileopen-Dialog ::sfx2::FileDialogHelper aDlg( com::sun::star::ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE, 0, GetParent() ); String aOldURL( GetCurrentURL() ); if( aOldURL.EqualsIgnoreCaseAscii( sFileScheme, 0, sizeof( sFileScheme ) - 1 ) ) { aDlg.SetDisplayDirectory( aOldURL ); } DisableClose( sal_True ); ErrCode nError = aDlg.Execute(); DisableClose( sal_False ); if ( ERRCODE_NONE == nError ) { String aURL( aDlg.GetPath() ); String aPath; utl::LocalFileHelper::ConvertURLToSystemPath( aURL, aPath ); maCbbPath.SetBaseURL( aURL ); maCbbPath.SetText( aPath ); if ( aOldURL != GetCurrentURL() ) ModifiedPathHdl_Impl (NULL); } return( 0L ); } /************************************************************************* |* |* Click on imagebutton : target |* |************************************************************************/ IMPL_LINK ( SvxHyperlinkDocTp, ClickTargetHdl_Impl, void *, EMPTYARG ) { if ( GetPathType ( maStrURL ) == Type_ExistsFile || maStrURL == aEmptyStr || maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) || maStrURL.SearchAscii( sHash ) == 0 ) { mpMarkWnd->SetError( LERR_NOERROR ); EnterWait(); if ( maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ) mpMarkWnd->RefreshTree ( aEmptyStr ); else mpMarkWnd->RefreshTree ( maStrURL ); LeaveWait(); } else mpMarkWnd->SetError( LERR_DOCNOTOPEN ); ShowMarkWnd (); return( 0L ); } /************************************************************************* |* |* Contens of combobox "Path" modified |* |************************************************************************/ IMPL_LINK ( SvxHyperlinkDocTp, ModifiedPathHdl_Impl, void *, EMPTYARG ) { maStrURL = GetCurrentURL(); maTimer.SetTimeout( 2500 ); maTimer.Start(); maFtFullURL.SetText( maStrURL ); return( 0L ); } /************************************************************************* |* |* If path-field was modify, to browse the new doc after timeout |* |************************************************************************/ IMPL_LINK ( SvxHyperlinkDocTp, TimeoutHdl_Impl, Timer *, EMPTYARG ) { if ( IsMarkWndVisible() && ( GetPathType( maStrURL )==Type_ExistsFile || maStrURL == aEmptyStr || maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ) ) { EnterWait(); if ( maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ) mpMarkWnd->RefreshTree ( aEmptyStr ); else mpMarkWnd->RefreshTree ( maStrURL ); LeaveWait(); } return( 0L ); } /************************************************************************* |* |* Contens of editfield "Target" modified |* |************************************************************************/ IMPL_LINK ( SvxHyperlinkDocTp, ModifiedTargetHdl_Impl, void *, EMPTYARG ) { maStrURL = GetCurrentURL(); if ( IsMarkWndVisible() ) mpMarkWnd->SelectEntry ( maEdTarget.GetText() ); maFtFullURL.SetText( maStrURL ); return( 0L ); } /************************************************************************* |* |* editfield "Target" lost focus |* |************************************************************************/ IMPL_LINK ( SvxHyperlinkDocTp, LostFocusPathHdl_Impl, void *, EMPTYARG ) { maStrURL = GetCurrentURL(); maFtFullURL.SetText( maStrURL ); return (0L); } /************************************************************************* |* |* Get String from Bookmark-Wnd |* |************************************************************************/ void SvxHyperlinkDocTp::SetMarkStr ( String& aStrMark ) { maEdTarget.SetText ( aStrMark ); ModifiedTargetHdl_Impl ( NULL ); } /************************************************************************* |* |* retrieve kind of pathstr |* |************************************************************************/ SvxHyperlinkDocTp::EPathType SvxHyperlinkDocTp::GetPathType ( String& aStrPath ) { INetURLObject aURL( aStrPath, INET_PROT_FILE ); if( aURL.HasError() ) return Type_Invalid; else return Type_ExistsFile; } <|endoftext|>
<commit_before>#include <algorithm> #include "ParamRenderArea.h" #include <QPainter> #include <QKeyEvent> #include <iostream> ParamRenderArea::ParamRenderArea(const QPainterPath &path, QWidget *parent) : QWidget(parent), path(path) { penWidth = 0.1f; rotationAngle = 0; offset.setX(50); offset.setY(50); triangulation = std::vector<ParameterTriangle *>(); setBackgroundRole(QPalette::Base); std::random_shuffle(colors.begin(), colors.end()); } QSize ParamRenderArea::minimumSizeHint() const { return QSize(50, 50); } QSize ParamRenderArea::sizeHint() const { return QSize(100, 100); } void ParamRenderArea::setPenWidth(float width) { penWidth = width; update(); } void ParamRenderArea::setPenColor(const QColor &color) { penColor = color; update(); } void ParamRenderArea::paintEvent(QPaintEvent *) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); painter.scale(width() / 100.0, height() / 100.0); painter.translate(offset); painter.rotate(-rotationAngle); painter.translate(-offset); painter.setPen(QPen(penColor, penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); int colorID = 0; // draw all outer shapes for (QPainterPath p : outerShapes) { QLinearGradient g(0, 0, 0, 100); g.setColorAt(0.0, colors.at(colorID)); g.setColorAt(1.0, colors.at(colorID)); painter.setBrush(g); painter.drawPath(p); colorID = (colorID + 1) % colors.size(); } // draw all inner shapes for (QPainterPath p : innerShapes) { QLinearGradient g(0, 0, 0, 100); g.setColorAt(0.0, colors.at(colorID)); g.setColorAt(1.0, colors.at(colorID)); painter.setBrush(g); painter.drawPath(p); colorID = (colorID + 1) % colors.size(); } // draw current path QLinearGradient gradient(0, 0, 0, 100); gradient.setColorAt(0.0, colors.at(colorID)); gradient.setColorAt(1.0, colors.at(colorID)); painter.setBrush(gradient); painter.drawPath(path); // draw parameter triangulation QPainter trip(this); trip.setRenderHint(QPainter::Antialiasing); trip.scale(width() / 100.0, height() / 100.0); trip.translate(offset); trip.rotate(-rotationAngle); trip.translate(-offset); trip.setPen(QPen(Qt::black, 1.0f * penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); for (ParameterTriangle *t : triangulation) { QPainterPath tP; tP.moveTo(denormalize(t->getPoint(0))); tP.lineTo(denormalize(t->getPoint(1))); tP.lineTo(denormalize(t->getPoint(2))); tP.lineTo(denormalize(t->getPoint(0))); trip.drawPath(tP); } } void ParamRenderArea::mousePressEvent(QMouseEvent *event) { QPointF pos = convertPos(event); if (event->button() == Qt::RightButton) { QList<QPointF> shape; std::copy(waypoints.begin(), waypoints.end(), std::back_inserter(shape)); path = QPainterPath(); waypoints.clear(); } else { waypoints.push_back(pos); path = QPainterPath(); path.moveTo(waypoints[0]); for (int i = 1; i < waypoints.size(); ++i) { path.lineTo(waypoints[i]); } path.closeSubpath(); } update(); } QPointF ParamRenderArea::convertPos(QMouseEvent *e) { return QPointF(100 * e->x() / width(), 100 * e->y() / height()); } QList<QList<QPointF> > ParamRenderArea::getShapes() { return shapeList; } void ParamRenderArea::setShapeType(ShapeType type) { currentType = type; } void ParamRenderArea::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Backspace: removeLastWaypoint(); break; case Qt::Key_Return: saveCurrentShape(); break; default: break; } } void ParamRenderArea::removeLastWaypoint() { if (!waypoints.empty()) { waypoints.pop_back(); } if (!waypoints.empty()) { path = QPainterPath(); path.moveTo(waypoints[0]); for (int i = 1; i < waypoints.size(); ++i) { path.lineTo(waypoints[i]); } path.closeSubpath(); } update(); } void ParamRenderArea::saveCurrentShape() { QPainterPath p; if (!waypoints.empty()) { p.moveTo(waypoints[0]); for (int i = 1; i < waypoints.size(); ++i) { p.lineTo(waypoints[i]); } p.closeSubpath(); } QList<QPointF> wp; for (QPointF po : waypoints) { wp.push_back(po); } shapeList.append(wp); waypoints.clear(); switch (currentType) { case ShapeType::INNER: innerShapes.append(p); break; case ShapeType::OUTER: outerShapes.append(p); break; default: break; } } void ParamRenderArea::clearShapes() { innerShapes.clear(); outerShapes.clear(); waypoints.clear(); update(); } void ParamRenderArea::mouseDoubleClickEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { removeLastWaypoint(); // undo first click removeLastWaypoint(); // undo second click } } void ParamRenderArea::drawTriangulation(std::vector<ParameterTriangle *> triangulation_) { triangulation = triangulation_; update(); } QPointF ParamRenderArea::denormalize(QVector2D v) { return QPointF(100.0f * v.x(), 100.0f - 100.f * v.y()); } <commit_msg>Removing double clicking things.<commit_after>#include <algorithm> #include "ParamRenderArea.h" #include <QPainter> #include <QKeyEvent> #include <iostream> ParamRenderArea::ParamRenderArea(const QPainterPath &path, QWidget *parent) : QWidget(parent), path(path) { penWidth = 0.1f; rotationAngle = 0; offset.setX(50); offset.setY(50); triangulation = std::vector<ParameterTriangle *>(); setBackgroundRole(QPalette::Base); std::random_shuffle(colors.begin(), colors.end()); } QSize ParamRenderArea::minimumSizeHint() const { return QSize(50, 50); } QSize ParamRenderArea::sizeHint() const { return QSize(100, 100); } void ParamRenderArea::setPenWidth(float width) { penWidth = width; update(); } void ParamRenderArea::setPenColor(const QColor &color) { penColor = color; update(); } void ParamRenderArea::paintEvent(QPaintEvent *) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); painter.scale(width() / 100.0, height() / 100.0); painter.translate(offset); painter.rotate(-rotationAngle); painter.translate(-offset); painter.setPen(QPen(penColor, penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); int colorID = 0; // draw all outer shapes for (QPainterPath p : outerShapes) { QLinearGradient g(0, 0, 0, 100); g.setColorAt(0.0, colors.at(colorID)); g.setColorAt(1.0, colors.at(colorID)); painter.setBrush(g); painter.drawPath(p); colorID = (colorID + 1) % colors.size(); } // draw all inner shapes for (QPainterPath p : innerShapes) { QLinearGradient g(0, 0, 0, 100); g.setColorAt(0.0, colors.at(colorID)); g.setColorAt(1.0, colors.at(colorID)); painter.setBrush(g); painter.drawPath(p); colorID = (colorID + 1) % colors.size(); } // draw current path QLinearGradient gradient(0, 0, 0, 100); gradient.setColorAt(0.0, colors.at(colorID)); gradient.setColorAt(1.0, colors.at(colorID)); painter.setBrush(gradient); painter.drawPath(path); // draw parameter triangulation QPainter trip(this); trip.setRenderHint(QPainter::Antialiasing); trip.scale(width() / 100.0, height() / 100.0); trip.translate(offset); trip.rotate(-rotationAngle); trip.translate(-offset); trip.setPen(QPen(Qt::black, 1.0f * penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); for (ParameterTriangle *t : triangulation) { QPainterPath tP; tP.moveTo(denormalize(t->getPoint(0))); tP.lineTo(denormalize(t->getPoint(1))); tP.lineTo(denormalize(t->getPoint(2))); tP.lineTo(denormalize(t->getPoint(0))); trip.drawPath(tP); } } void ParamRenderArea::mousePressEvent(QMouseEvent *event) { QPointF pos = convertPos(event); if (event->button() == Qt::RightButton) { QList<QPointF> shape; std::copy(waypoints.begin(), waypoints.end(), std::back_inserter(shape)); path = QPainterPath(); waypoints.clear(); } else { waypoints.push_back(pos); path = QPainterPath(); path.moveTo(waypoints[0]); for (int i = 1; i < waypoints.size(); ++i) { path.lineTo(waypoints[i]); } path.closeSubpath(); } update(); } QPointF ParamRenderArea::convertPos(QMouseEvent *e) { return QPointF(100 * e->x() / width(), 100 * e->y() / height()); } QList<QList<QPointF> > ParamRenderArea::getShapes() { return shapeList; } void ParamRenderArea::setShapeType(ShapeType type) { currentType = type; } void ParamRenderArea::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Backspace: removeLastWaypoint(); break; case Qt::Key_Return: saveCurrentShape(); break; default: break; } } void ParamRenderArea::removeLastWaypoint() { if (!waypoints.empty()) { waypoints.pop_back(); } if (!waypoints.empty()) { path = QPainterPath(); path.moveTo(waypoints[0]); for (int i = 1; i < waypoints.size(); ++i) { path.lineTo(waypoints[i]); } path.closeSubpath(); } update(); } void ParamRenderArea::saveCurrentShape() { QPainterPath p; if (!waypoints.empty()) { p.moveTo(waypoints[0]); for (int i = 1; i < waypoints.size(); ++i) { p.lineTo(waypoints[i]); } p.closeSubpath(); } QList<QPointF> wp; for (QPointF po : waypoints) { wp.push_back(po); } shapeList.append(wp); waypoints.clear(); switch (currentType) { case ShapeType::INNER: innerShapes.append(p); break; case ShapeType::OUTER: outerShapes.append(p); break; default: break; } } void ParamRenderArea::clearShapes() { innerShapes.clear(); outerShapes.clear(); waypoints.clear(); update(); } void ParamRenderArea::mouseDoubleClickEvent(QMouseEvent *event) { // if (event->button() == Qt::LeftButton) { // removeLastWaypoint(); // undo first click // removeLastWaypoint(); // undo second click // } } void ParamRenderArea::drawTriangulation(std::vector<ParameterTriangle *> triangulation_) { triangulation = triangulation_; update(); } QPointF ParamRenderArea::denormalize(QVector2D v) { return QPointF(100.0f * v.x(), 100.0f - 100.f * v.y()); } <|endoftext|>
<commit_before>/* * Copyright 2015 - 2018 gtalent2@gmail.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #ifdef OX_USE_STDLIB #include <cstddef> #else #define offsetof(type, member) __builtin_offsetof(type, member) #endif #ifdef _MSC_VER #define OX_PACKED #else #define OX_PACKED __attribute__((packed)) #endif <commit_msg>[ox/std] Add OX_ALIGN4<commit_after>/* * Copyright 2015 - 2018 gtalent2@gmail.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #ifdef OX_USE_STDLIB #include <cstddef> #else #define offsetof(type, member) __builtin_offsetof(type, member) #endif #ifdef _MSC_VER #define OX_PACKED #else #define OX_PACKED __attribute__((packed)) #endif #ifdef _MSC_VER #define OX_ALIGN4 #else #define OX_ALIGN4 __attribute__((aligned(4))) #endif <|endoftext|>
<commit_before>#include "ghost/timing.h" #include "ghost/util.h" #include <map> #include <vector> #include <sstream> #include <iostream> #include <iomanip> #include <numeric> #include <algorithm> using namespace std; /** * @brief Region timing accumulator */ typedef struct { /** * @brief The runtimes of this region. */ vector<double> times; /** * @brief The last start time of this region. */ double start; } ghost_timing_region_accu_t; static map<string,ghost_timing_region_accu_t> timings; void ghost_timing_tick(char *tag) { double start; ghost_timing_wc(&start); timings[tag].start = start; } void ghost_timing_tock(char *tag) { double end; ghost_timing_wc(&end); ghost_timing_region_accu_t *ti = &timings[string(tag)]; ti->times.push_back(end-ti->start); } ghost_error_t ghost_timing_region_create(ghost_timing_region_t ** ri, char *tag) { ghost_timing_region_accu_t ti; if (!timings.count(string(tag))) { ERROR_LOG("The region %s does not exist!",tag); return GHOST_ERR_INVALID_ARG; } ti = timings[string(tag)]; ghost_error_t ret = GHOST_SUCCESS; GHOST_CALL_GOTO(ghost_malloc((void **)ri,sizeof(ghost_timing_region_t)),err,ret); (*ri)->nCalls = ti.times.size(); (*ri)->minTime = *min_element(ti.times.begin(),ti.times.end()); (*ri)->maxTime = *max_element(ti.times.begin(),ti.times.end()); (*ri)->avgTime = accumulate(ti.times.begin(),ti.times.end(),0.)/(*ri)->nCalls; GHOST_CALL_GOTO(ghost_malloc((void **)(&((*ri)->times)),sizeof(double)*(*ri)->nCalls),err,ret); memcpy((*ri)->times,&ti.times[0],(*ri)->nCalls*sizeof(double)); goto out; err: ERROR_LOG("Freeing region info"); if (*ri) { free((*ri)->times); (*ri)->times = NULL; } free(*ri); (*ri) = NULL; out: return ret; } void ghost_timing_region_destroy(ghost_timing_region_t * ri) { if (ri) { free(ri->times); ri->times = NULL; } free(ri); } ghost_error_t ghost_timing_summarystring(char **str) { stringstream buffer; map<string,ghost_timing_region_accu_t>::iterator iter; size_t maxRegionLen = 0; size_t maxCallsLen = 0; stringstream tmp; for (iter = timings.begin(); iter != timings.end(); ++iter) { tmp << iter->first.length(); maxRegionLen = max(iter->first.length(),maxRegionLen); tmp.str(""); tmp << iter->second.times.size(); maxCallsLen = max(maxCallsLen,tmp.str().length()); tmp.str(""); } if (maxCallsLen < 5) { maxCallsLen = 5; } buffer << left << setw(maxRegionLen) << "Region" << right << " | "; buffer << setw(maxCallsLen+3) << "Calls | "; buffer << " t_min | "; buffer << " t_max | "; buffer << " t_avg" << endl; buffer << string(maxRegionLen+maxCallsLen+3+3*11,'-') << endl; buffer.precision(2); for (iter = timings.begin(); iter != timings.end(); ++iter) { buffer << scientific << left << setw(maxRegionLen) << iter->first << " | " << right << setw(maxCallsLen) << iter->second.times.size() << " | " << *min_element(iter->second.times.begin(),iter->second.times.end()) << " | " << *max_element(iter->second.times.begin(),iter->second.times.end()) << " | " << accumulate(iter->second.times.begin(),iter->second.times.end(),0.)/iter->second.times.size() << endl; } GHOST_CALL_RETURN(ghost_malloc((void **)str,buffer.str().length()+1)); strcpy(*str,buffer.str().c_str()); return GHOST_SUCCESS; } <commit_msg>print total time in timing summary<commit_after>#include "ghost/timing.h" #include "ghost/util.h" #include <map> #include <vector> #include <sstream> #include <iostream> #include <iomanip> #include <numeric> #include <algorithm> using namespace std; /** * @brief Region timing accumulator */ typedef struct { /** * @brief The runtimes of this region. */ vector<double> times; /** * @brief The last start time of this region. */ double start; } ghost_timing_region_accu_t; static map<string,ghost_timing_region_accu_t> timings; void ghost_timing_tick(char *tag) { double start; ghost_timing_wc(&start); timings[tag].start = start; } void ghost_timing_tock(char *tag) { double end; ghost_timing_wc(&end); ghost_timing_region_accu_t *ti = &timings[string(tag)]; ti->times.push_back(end-ti->start); } ghost_error_t ghost_timing_region_create(ghost_timing_region_t ** ri, char *tag) { ghost_timing_region_accu_t ti; if (!timings.count(string(tag))) { ERROR_LOG("The region %s does not exist!",tag); return GHOST_ERR_INVALID_ARG; } ti = timings[string(tag)]; ghost_error_t ret = GHOST_SUCCESS; GHOST_CALL_GOTO(ghost_malloc((void **)ri,sizeof(ghost_timing_region_t)),err,ret); (*ri)->nCalls = ti.times.size(); (*ri)->minTime = *min_element(ti.times.begin(),ti.times.end()); (*ri)->maxTime = *max_element(ti.times.begin(),ti.times.end()); (*ri)->avgTime = accumulate(ti.times.begin(),ti.times.end(),0.)/(*ri)->nCalls; GHOST_CALL_GOTO(ghost_malloc((void **)(&((*ri)->times)),sizeof(double)*(*ri)->nCalls),err,ret); memcpy((*ri)->times,&ti.times[0],(*ri)->nCalls*sizeof(double)); goto out; err: ERROR_LOG("Freeing region info"); if (*ri) { free((*ri)->times); (*ri)->times = NULL; } free(*ri); (*ri) = NULL; out: return ret; } void ghost_timing_region_destroy(ghost_timing_region_t * ri) { if (ri) { free(ri->times); ri->times = NULL; } free(ri); } ghost_error_t ghost_timing_summarystring(char **str) { stringstream buffer; map<string,ghost_timing_region_accu_t>::iterator iter; size_t maxRegionLen = 0; size_t maxCallsLen = 0; stringstream tmp; for (iter = timings.begin(); iter != timings.end(); ++iter) { tmp << iter->first.length(); maxRegionLen = max(iter->first.length(),maxRegionLen); tmp.str(""); tmp << iter->second.times.size(); maxCallsLen = max(maxCallsLen,tmp.str().length()); tmp.str(""); } if (maxCallsLen < 5) { maxCallsLen = 5; } buffer << left << setw(maxRegionLen) << "Region" << right << " | "; buffer << setw(maxCallsLen+3) << "Calls | "; buffer << " t_min | "; buffer << " t_max | "; buffer << " t_avg | "; buffer << " t_tot" << endl; buffer << string(maxRegionLen+maxCallsLen+3+4*11,'-') << endl; buffer.precision(2); for (iter = timings.begin(); iter != timings.end(); ++iter) { buffer << scientific << left << setw(maxRegionLen) << iter->first << " | " << right << setw(maxCallsLen) << iter->second.times.size() << " | " << *min_element(iter->second.times.begin(),iter->second.times.end()) << " | " << *max_element(iter->second.times.begin(),iter->second.times.end()) << " | " << accumulate(iter->second.times.begin(),iter->second.times.end(),0.)/iter->second.times.size() << " | " << accumulate(iter->second.times.begin(),iter->second.times.end(),0.) << endl; } GHOST_CALL_RETURN(ghost_malloc((void **)str,buffer.str().length()+1)); strcpy(*str,buffer.str().c_str()); return GHOST_SUCCESS; } <|endoftext|>
<commit_before>#include "musicvideotablewidget.h" #include "musicdatadownloadthread.h" #include "musicmessagebox.h" #include <time.h> MusicVideoTableWidget::MusicVideoTableWidget(QWidget *parent) : MusicQueryTableWidget(parent) { setColumnCount(8); QHeaderView *headerview = horizontalHeader(); headerview->resizeSection(0,30); headerview->resizeSection(1,175); headerview->resizeSection(2,151); headerview->resizeSection(3,30); headerview->resizeSection(4,55); headerview->resizeSection(5,24); headerview->resizeSection(6,24); headerview->resizeSection(7,24); setTransparent(255); qsrand(time(NULL)); } MusicVideoTableWidget::~MusicVideoTableWidget() { clearAllItems(); } void MusicVideoTableWidget::startSearchQuery(const QString &text) { m_downLoadManager->startSearchSong(MVQuery, text); } void MusicVideoTableWidget::clearAllItems() { MusicAbstractTableWidget::clear(); setColumnCount(8); } QString MusicVideoTableWidget::randToGetStrength() const { switch(qrand()%5) { case 0: return QString::fromUtf8(":/video/video_1"); case 1: return QString::fromUtf8(":/video/video_2"); case 2: return QString::fromUtf8(":/video/video_3"); case 3: return QString::fromUtf8(":/video/video_4"); case 4: return QString::fromUtf8(":/video/video_5"); } return QString::fromUtf8(":/video/video_5"); } void MusicVideoTableWidget::creatSearchedItems(const QString &songname, const QString &artistname, const QString &time) { int count; setRowCount(count = m_downLoadManager->getSongIdIndex()); setStyleSheet(MusicUIObject::MTableWidgetStyle01 + \ MusicUIObject::MScrollBarStyle01); QTableWidgetItem *item = new QTableWidgetItem; item->setData(Qt::DisplayRole, false); setItem(count - 1, 0, item); item = new QTableWidgetItem(songname); item->setTextColor(QColor(50,50,50)); item->setTextAlignment(Qt::AlignCenter); item->setToolTip(songname); setItem(count - 1, 1, item); item = new QTableWidgetItem(artistname); item->setTextColor(QColor(50,50,50)); item->setTextAlignment(Qt::AlignCenter); item->setToolTip(artistname); setItem(count - 1, 2, item); item = new QTableWidgetItem(QIcon( randToGetStrength() ),""); item->setTextAlignment(Qt::AlignCenter); setItem(count - 1, 3, item); item = new QTableWidgetItem(time); item->setTextColor(QColor(50,50,50)); item->setTextAlignment(Qt::AlignCenter); setItem(count - 1, 4, item); item = new QTableWidgetItem(QIcon(QString::fromUtf8(":/share/showMV")),""); item->setTextAlignment(Qt::AlignCenter); setItem(count - 1, 5, item); item = new QTableWidgetItem(QIcon(QString::fromUtf8(":/share/autionplay")),""); item->setTextColor(QColor(50,50,50)); item->setTextAlignment(Qt::AlignCenter); setItem(count - 1, 6, item); item = new QTableWidgetItem(QIcon(QString::fromUtf8(":/share/musicdownload")),""); item->setTextColor(QColor(50,50,50)); item->setTextAlignment(Qt::AlignCenter); setItem(count - 1, 7, item); } void MusicVideoTableWidget::listCellClicked(int row,int col) { MusicQueryTableWidget::listCellClicked(row, col); switch(col) { case 5: case 6: itemDoubleClicked(row, -1);break; case 7: musicDownloadLocal(row);break; default:break; } } void MusicVideoTableWidget::musicDownloadLocal(int row) { if(row < 0) { MusicMessageBox message; message.setText(tr("Please Select One Item First!")); message.exec(); return; } MStringLists musicSongInfo(m_downLoadManager->getMusicSongInfo()); MusicDataDownloadThread* download = new MusicDataDownloadThread(musicSongInfo[row][2], QString("%1 - %2.%3") .arg(musicSongInfo[row][0]).arg(musicSongInfo[row][1]).arg(musicSongInfo[row][3]), Download_Video, this); download->startToDownload(); } void MusicVideoTableWidget::itemDoubleClicked(int row, int column) { if(column <= 0 || row < 0) { return; } MStringLists musicSongInfo(m_downLoadManager->getMusicSongInfo()); emit mvURLChanged(musicSongInfo[row][2]); } void MusicVideoTableWidget::contextMenuEvent(QContextMenuEvent *event) { MusicQueryTableWidget::contextMenuEvent(event); QMenu rightClickMenu(this); createContextMenu(rightClickMenu); rightClickMenu.exec(QCursor::pos()); } <commit_msg>fix column index incorrect when insert into -1, now set to 999[015452]<commit_after>#include "musicvideotablewidget.h" #include "musicdatadownloadthread.h" #include "musicmessagebox.h" #include <time.h> MusicVideoTableWidget::MusicVideoTableWidget(QWidget *parent) : MusicQueryTableWidget(parent) { setColumnCount(8); QHeaderView *headerview = horizontalHeader(); headerview->resizeSection(0,30); headerview->resizeSection(1,175); headerview->resizeSection(2,151); headerview->resizeSection(3,30); headerview->resizeSection(4,55); headerview->resizeSection(5,24); headerview->resizeSection(6,24); headerview->resizeSection(7,24); setTransparent(255); qsrand(time(NULL)); } MusicVideoTableWidget::~MusicVideoTableWidget() { clearAllItems(); } void MusicVideoTableWidget::startSearchQuery(const QString &text) { m_downLoadManager->startSearchSong(MVQuery, text); } void MusicVideoTableWidget::clearAllItems() { MusicAbstractTableWidget::clear(); setColumnCount(8); } QString MusicVideoTableWidget::randToGetStrength() const { switch(qrand()%5) { case 0: return QString::fromUtf8(":/video/video_1"); case 1: return QString::fromUtf8(":/video/video_2"); case 2: return QString::fromUtf8(":/video/video_3"); case 3: return QString::fromUtf8(":/video/video_4"); case 4: return QString::fromUtf8(":/video/video_5"); } return QString::fromUtf8(":/video/video_5"); } void MusicVideoTableWidget::creatSearchedItems(const QString &songname, const QString &artistname, const QString &time) { int count; setRowCount(count = m_downLoadManager->getSongIdIndex()); setStyleSheet(MusicUIObject::MTableWidgetStyle01 + \ MusicUIObject::MScrollBarStyle01); QTableWidgetItem *item = new QTableWidgetItem; item->setData(Qt::DisplayRole, false); setItem(count - 1, 0, item); item = new QTableWidgetItem(songname); item->setTextColor(QColor(50,50,50)); item->setTextAlignment(Qt::AlignCenter); item->setToolTip(songname); setItem(count - 1, 1, item); item = new QTableWidgetItem(artistname); item->setTextColor(QColor(50,50,50)); item->setTextAlignment(Qt::AlignCenter); item->setToolTip(artistname); setItem(count - 1, 2, item); item = new QTableWidgetItem(QIcon( randToGetStrength() ),""); item->setTextAlignment(Qt::AlignCenter); setItem(count - 1, 3, item); item = new QTableWidgetItem(time); item->setTextColor(QColor(50,50,50)); item->setTextAlignment(Qt::AlignCenter); setItem(count - 1, 4, item); item = new QTableWidgetItem(QIcon(QString::fromUtf8(":/share/showMV")),""); item->setTextAlignment(Qt::AlignCenter); setItem(count - 1, 5, item); item = new QTableWidgetItem(QIcon(QString::fromUtf8(":/share/autionplay")),""); item->setTextColor(QColor(50,50,50)); item->setTextAlignment(Qt::AlignCenter); setItem(count - 1, 6, item); item = new QTableWidgetItem(QIcon(QString::fromUtf8(":/share/musicdownload")),""); item->setTextColor(QColor(50,50,50)); item->setTextAlignment(Qt::AlignCenter); setItem(count - 1, 7, item); } void MusicVideoTableWidget::listCellClicked(int row,int col) { MusicQueryTableWidget::listCellClicked(row, col); switch(col) { case 5: case 6: itemDoubleClicked(row, 999);break; case 7: musicDownloadLocal(row);break; default:break; } } void MusicVideoTableWidget::musicDownloadLocal(int row) { if(row < 0) { MusicMessageBox message; message.setText(tr("Please Select One Item First!")); message.exec(); return; } MStringLists musicSongInfo(m_downLoadManager->getMusicSongInfo()); MusicDataDownloadThread* download = new MusicDataDownloadThread(musicSongInfo[row][2], QString("%1 - %2.%3") .arg(musicSongInfo[row][0]).arg(musicSongInfo[row][1]).arg(musicSongInfo[row][3]), Download_Video, this); download->startToDownload(); } void MusicVideoTableWidget::itemDoubleClicked(int row, int column) { if(column <= 0 || row < 0) { return; } MStringLists musicSongInfo(m_downLoadManager->getMusicSongInfo()); emit mvURLChanged(musicSongInfo[row][2]); } void MusicVideoTableWidget::contextMenuEvent(QContextMenuEvent *event) { MusicQueryTableWidget::contextMenuEvent(event); QMenu rightClickMenu(this); createContextMenu(rightClickMenu); rightClickMenu.exec(QCursor::pos()); } <|endoftext|>
<commit_before>// BotRobot, ATaco // PPCG: http://codegolf.stackexchange.com/a/104910/11933 // BotRobot // ONE HUNDRED THOUSAND GENERATIONS TO MAKE THE ULTIMATE LIFEFORM! #ifndef __BOT_ROBOT_PLAYER_HPP__ #define __BOT_ROBOT_PLAYER_HPP__ #include "Player.hpp" class BotRobotPlayer final : public Player { public: BotRobotPlayer(size_t opponent = -1) : Player(opponent) {} public: virtual Action fight() { std::string action = ""; action += std::to_string(getAmmo()); action += ":"; action += std::to_string(getAmmoOpponent()); int toDo = 3; for (int i = 0; i < sizeof(options); i++) { if (options[i].compare(action) == 0) { toDo = outputs[i]; break; } } switch (toDo) { case 0: return load(); case 1: return bullet(); case 2: return plasma(); case 3: return metal(); default: return thermal(); } } private: std::string options[29] = { "0:9", "1:12", "1:10", "0:10", "1:11", "0:11", "0:6", "2:2", "0:2", "2:6", "3:6", "0:7", "1:3", "2:3", "0:3", "2:0", "1:0", "0:4", "1:4", "2:4", "0:0", "3:0", "1:1", "2:1", "2:9", "0:5", "0:8", "3:1", "0:1" }; int outputs[29] = { 0, 1, 1, 4, 1, 0, 0, 4, 4, 0, 0, 3, 0, 1, 3, 0, 1, 4, 0, 1, 0, 1, 0, 3, 4, 3, 0, 1, 0 }; }; #endif // !__BOT_ROBOT_PLAYER_HPP__<commit_msg>Get correct array length.<commit_after>// BotRobot, ATaco // PPCG: http://codegolf.stackexchange.com/a/104910/11933 // BotRobot // ONE HUNDRED THOUSAND GENERATIONS TO MAKE THE ULTIMATE LIFEFORM! #ifndef __BOT_ROBOT_PLAYER_HPP__ #define __BOT_ROBOT_PLAYER_HPP__ #include "Player.hpp" class BotRobotPlayer final : public Player { public: BotRobotPlayer(size_t opponent = -1) : Player(opponent) {} public: virtual Action fight() { std::string action = ""; action += std::to_string(getAmmo()); action += ":"; action += std::to_string(getAmmoOpponent()); int toDo = 3; for (int i = 0; i < sizeof(options)/sizeof(std::string); i++) { if (options[i].compare(action) == 0) { toDo = outputs[i]; break; } } switch (toDo) { case 0: return load(); case 1: return bullet(); case 2: return plasma(); case 3: return metal(); default: return thermal(); } } private: std::string options[29] = { "0:9", "1:12", "1:10", "0:10", "1:11", "0:11", "0:6", "2:2", "0:2", "2:6", "3:6", "0:7", "1:3", "2:3", "0:3", "2:0", "1:0", "0:4", "1:4", "2:4", "0:0", "3:0", "1:1", "2:1", "2:9", "0:5", "0:8", "3:1", "0:1" }; int outputs[29] = { 0, 1, 1, 4, 1, 0, 0, 4, 4, 0, 0, 3, 0, 1, 3, 0, 1, 4, 0, 1, 0, 1, 0, 3, 4, 3, 0, 1, 0 }; }; #endif // !__BOT_ROBOT_PLAYER_HPP__<|endoftext|>
<commit_before>#ifndef ALEPH_PERSISTENCE_DIAGRAM_HH__ #define ALEPH_PERSISTENCE_DIAGRAM_HH__ #include <algorithm> #include <iosfwd> #include <limits> #include <utility> #include <vector> namespace aleph { template <class T> class PersistenceDiagram { public: // Exporting the data type of the underlying persistence diagrams // makes it easier for client code to specify the desired type in // advanced. Else, I would require `decltype` or related concepts // that make the code harder to read. using DataType = T; class Point { public: explicit Point( DataType x ) : _x( x ) , _y( std::numeric_limits<DataType>::max() ) { if( std::numeric_limits<DataType>::has_infinity ) _y = std::numeric_limits<DataType>::infinity(); } Point( DataType x, DataType y ) : _x( x ) , _y( y ) { } DataType x() const { return _x; } DataType y() const { return _y; } DataType persistence() const { return _y - _x; } bool operator==( const Point& other ) const { return _x == other._x && _y == other._y; } bool isUnpaired() const { return ( std::numeric_limits<DataType>::has_infinity && _y == std::numeric_limits<DataType>::infinity() ) || ( !std::numeric_limits<DataType>::has_infinity && _y == std::numeric_limits<DataType>::max() ); } private: DataType _x; DataType _y; }; // Typedefs & aliases ------------------------------------------------ using ValueType = Point; using ContainerType = std::vector<ValueType>; using ConstIterator = typename ContainerType::const_iterator; using Iterator = typename ContainerType::iterator; using value_type = ValueType; // Iterators --------------------------------------------------------- ConstIterator begin() const { return _points.begin(); } Iterator begin() { return _points.begin(); } ConstIterator end() const { return _points.end(); } Iterator end() { return _points.end(); } // Modification ------------------------------------------------------ void add( DataType x ) { _points.push_back( Point( x ) ); } void add( DataType x, DataType y ) { _points.push_back( Point( x, y ) ); } Iterator erase( Iterator position ) { return _points.erase( position ); } Iterator erase( Iterator begin, Iterator end ) { return _points.erase( begin, end ); } /** Removes all points that appear on the diagonal of a persistence diagram */ void removeDiagonal() noexcept { _points.erase( std::remove_if( _points.begin(), _points.end(), [] ( const Point& p ) { return p.x() == p.y(); } ), _points.end() ); } /** Removes all unpaired points, i.e. points with infinite persistence */ void removeUnpaired() noexcept { _points.erase( std::remove_if( _points.begin(), _points.end(), [] ( const Point& p ) { return p.isUnpaired(); } ), _points.end() ); } // Attributes -------------------------------------------------------- void setDimension( std::size_t dimension ) { _dimension = dimension; } std::size_t dimension() const { return _dimension; } // Comparison operators ---------------------------------------------- bool operator==( const PersistenceDiagram<DataType>& other ) const { return _points == other._points; } bool operator!=( const PersistenceDiagram<DataType>& other ) const { return !( this->operator==( other ) ); } // Queries ----------------------------------------------------------- /** @returns Betti number of the persistence diagram, i.e. the number of unpaired points */ std::size_t betti() const { auto numUnpairedPoints = std::count_if( _points.begin(), _points.end(), [] ( const Point& p ) { return p.isUnpaired(); } ); return static_cast<std::size_t>( numUnpairedPoints ); } std::size_t size() const { return _points.size(); } bool empty() const { return _points.empty(); } private: /** Dimension of the persistence pairs stored in the diagram */ std::size_t _dimension = 0; /** Container of persistence pairs */ ContainerType _points; }; template <class DataType> std::ostream& operator<<( std::ostream& o, const PersistenceDiagram<DataType>& D ) { for( auto&& p : D ) o << p.x() << "\t" << p.y() << "\n"; return o; } } #endif <commit_msg>Extended interface of subordinate `Point` class<commit_after>#ifndef ALEPH_PERSISTENCE_DIAGRAM_HH__ #define ALEPH_PERSISTENCE_DIAGRAM_HH__ #include <algorithm> #include <iosfwd> #include <limits> #include <utility> #include <vector> namespace aleph { template <class T> class PersistenceDiagram { public: // Exporting the data type of the underlying persistence diagrams // makes it easier for client code to specify the desired type in // advanced. Else, I would require `decltype` or related concepts // that make the code harder to read. using DataType = T; class Point { public: explicit Point( DataType x ) : _x( x ) , _y( std::numeric_limits<DataType>::max() ) { if( std::numeric_limits<DataType>::has_infinity ) _y = std::numeric_limits<DataType>::infinity(); } Point( DataType x, DataType y ) : _x( x ) , _y( y ) { } DataType x() const noexcept { return _x; } DataType y() const noexcept { return _y; } DataType persistence() const noexcept { return _y - _x; } bool operator==( const Point& other ) const noexcept { return _x == other._x && _y == other._y; } bool operator!=( const Point& other ) const noexcept { return !this->operator==( other ); } bool isUnpaired() const noexcept { return ( std::numeric_limits<DataType>::has_infinity && _y == std::numeric_limits<DataType>::infinity() ) || ( !std::numeric_limits<DataType>::has_infinity && _y == std::numeric_limits<DataType>::max() ); } private: DataType _x; DataType _y; }; // Typedefs & aliases ------------------------------------------------ using ValueType = Point; using ContainerType = std::vector<ValueType>; using ConstIterator = typename ContainerType::const_iterator; using Iterator = typename ContainerType::iterator; using value_type = ValueType; // Iterators --------------------------------------------------------- ConstIterator begin() const { return _points.begin(); } Iterator begin() { return _points.begin(); } ConstIterator end() const { return _points.end(); } Iterator end() { return _points.end(); } // Modification ------------------------------------------------------ void add( DataType x ) { _points.push_back( Point( x ) ); } void add( DataType x, DataType y ) { _points.push_back( Point( x, y ) ); } Iterator erase( Iterator position ) { return _points.erase( position ); } Iterator erase( Iterator begin, Iterator end ) { return _points.erase( begin, end ); } /** Removes all points that appear on the diagonal of a persistence diagram */ void removeDiagonal() noexcept { _points.erase( std::remove_if( _points.begin(), _points.end(), [] ( const Point& p ) { return p.x() == p.y(); } ), _points.end() ); } /** Removes all unpaired points, i.e. points with infinite persistence */ void removeUnpaired() noexcept { _points.erase( std::remove_if( _points.begin(), _points.end(), [] ( const Point& p ) { return p.isUnpaired(); } ), _points.end() ); } // Attributes -------------------------------------------------------- void setDimension( std::size_t dimension ) { _dimension = dimension; } std::size_t dimension() const { return _dimension; } // Comparison operators ---------------------------------------------- bool operator==( const PersistenceDiagram<DataType>& other ) const { return _points == other._points; } bool operator!=( const PersistenceDiagram<DataType>& other ) const { return !( this->operator==( other ) ); } // Queries ----------------------------------------------------------- /** @returns Betti number of the persistence diagram, i.e. the number of unpaired points */ std::size_t betti() const { auto numUnpairedPoints = std::count_if( _points.begin(), _points.end(), [] ( const Point& p ) { return p.isUnpaired(); } ); return static_cast<std::size_t>( numUnpairedPoints ); } std::size_t size() const { return _points.size(); } bool empty() const { return _points.empty(); } private: /** Dimension of the persistence pairs stored in the diagram */ std::size_t _dimension = 0; /** Container of persistence pairs */ ContainerType _points; }; template <class DataType> std::ostream& operator<<( std::ostream& o, const PersistenceDiagram<DataType>& D ) { for( auto&& p : D ) o << p.x() << "\t" << p.y() << "\n"; return o; } } #endif <|endoftext|>
<commit_before>#include "visualization.h" #include <opencv2/highgui.hpp> using namespace std; namespace mo { //----------------------------------------------------------------- std::ostream& operator<<(std::ostream& os, const Color& col){ return os << "{r,g,b}={" << static_cast<unsigned>(col.red) << ',' << static_cast<unsigned>(col.green) << ',' << static_cast<unsigned>(col.blue) << "}"; } //----------------------------------------------------------------- void show(const std::string& winname, const Image& img, const int waitms){ cv::imshow(winname, img); cv::waitKey(waitms); } //----------------------------------------------------------------- void line(const Point& pt_sta, const Point& pt_end, Image& img, const Color& color){ cv::line(img, pt_sta, pt_end, color.pixval()); } //----------------------------------------------------------------- void arrow(const Point& pt_sta, const Point& pt_end, Image& img, const Color& color){ cv::arrowedLine(img, pt_sta, pt_end, color.pixval()); } //----------------------------------------------------------------- void point(const Point& pt, Image& img, const Color& color, const int radius){ cv::circle(img, pt, radius, color.pixval(), -1); //-1 means filled color. } //----------------------------------------------------------------- void text(const std::string& text, Image& img, const Point& org, const double& scale, const Color& color){ cv::putText(img, text, org, cv::FONT_HERSHEY_SIMPLEX, scale, color.pixval()); } //----------------------------------------------------------------- void colorbar(Image& img, const ColormapTypes colormaptype){ for(int u=0; u<img.rows; ++u){ unsigned char* Mu = img.ptr(u); for(int v=0; v<img.cols*3; v+=3){ for(int c=0; c<3; ++c){ //color channel Mu[v+c] = u*255/img.rows; } } } cv::applyColorMap(img, img, cv::COLORMAP_HOT); } } //namespace mo <commit_msg>change colorbar<commit_after>#include "visualization.h" #include <opencv2/highgui.hpp> using namespace std; namespace mo { //----------------------------------------------------------------- std::ostream& operator<<(std::ostream& os, const Color& col){ return os << "{r,g,b}={" << static_cast<unsigned>(col.red) << ',' << static_cast<unsigned>(col.green) << ',' << static_cast<unsigned>(col.blue) << "}"; } //----------------------------------------------------------------- void show(const std::string& winname, const Image& img, const int waitms){ cv::imshow(winname, img); cv::waitKey(waitms); } //----------------------------------------------------------------- void line(const Point& pt_sta, const Point& pt_end, Image& img, const Color& color){ cv::line(img, pt_sta, pt_end, color.pixval()); } //----------------------------------------------------------------- void arrow(const Point& pt_sta, const Point& pt_end, Image& img, const Color& color){ cv::arrowedLine(img, pt_sta, pt_end, color.pixval()); } //----------------------------------------------------------------- void point(const Point& pt, Image& img, const Color& color, const int radius){ cv::circle(img, pt, radius, color.pixval(), -1); //-1 means filled color. } //----------------------------------------------------------------- void text(const std::string& text, Image& img, const Point& org, const double& scale, const Color& color){ cv::putText(img, text, org, cv::FONT_HERSHEY_SIMPLEX, scale, color.pixval()); } //----------------------------------------------------------------- void colorbar(Image& img, const ColormapTypes colormaptype){ for(int u=0; u<img.rows; ++u){ unsigned char* Mu = img.ptr(u); for(int v=0; v<img.cols*3; v+=3){ for(int c=0; c<3; ++c){ //color channel Mu[v+c] = 255 - u*255/img.rows; } } } cv::applyColorMap(img, img, cv::COLORMAP_HOT); } } //namespace mo <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_OOX_DRAWINGML_CHART_SERIESCONTEXT_HXX #define INCLUDED_OOX_DRAWINGML_CHART_SERIESCONTEXT_HXX #include <drawingml/chart/chartcontextbase.hxx> namespace oox { namespace drawingml { namespace chart { struct DataLabelModel; /** Handler for a chart data point label context (c:dLbl element). */ class DataLabelContext : public ContextBase< DataLabelModel > { public: explicit DataLabelContext( ::oox::core::ContextHandler2Helper& rParent, DataLabelModel& rModel ); virtual ~DataLabelContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; virtual void onCharacters( const OUString& rChars ) SAL_OVERRIDE; }; struct DataLabelsModel; /** Handler for a chart data point label context (c:dLbl element). */ class DataLabelsContext : public ContextBase< DataLabelsModel > { public: explicit DataLabelsContext( ::oox::core::ContextHandler2Helper& rParent, DataLabelsModel& rModel ); virtual ~DataLabelsContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; virtual void onCharacters( const OUString& rChars ) SAL_OVERRIDE; }; struct PictureOptionsModel; /** Handler for fill bitmap settings (c:pictureOptions element). */ class PictureOptionsContext : public ContextBase< PictureOptionsModel > { public: explicit PictureOptionsContext( ::oox::core::ContextHandler2Helper& rParent, PictureOptionsModel& rModel ); virtual ~PictureOptionsContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; struct ErrorBarModel; /** Handler for a series error bar context (c:errBars element). */ class ErrorBarContext : public ContextBase< ErrorBarModel > { public: explicit ErrorBarContext( ::oox::core::ContextHandler2Helper& rParent, ErrorBarModel& rModel ); virtual ~ErrorBarContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; struct TrendlineLabelModel; /** Handler for a series trendline label context (c:trendlineLbl element). */ class TrendlineLabelContext : public ContextBase< TrendlineLabelModel > { public: explicit TrendlineLabelContext( ::oox::core::ContextHandler2Helper& rParent, TrendlineLabelModel& rModel ); virtual ~TrendlineLabelContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; struct TrendlineModel; /** Handler for a series trendline context (c:trendline element). */ class TrendlineContext : public ContextBase< TrendlineModel > { public: explicit TrendlineContext( ::oox::core::ContextHandler2Helper& rParent, TrendlineModel& rModel ); virtual ~TrendlineContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; virtual void onCharacters( const OUString& rChars ) SAL_OVERRIDE; }; struct DataPointModel; /** Handler for a chart data point context (c:dPt element). */ class DataPointContext : public ContextBase< DataPointModel > { public: explicit DataPointContext( ::oox::core::ContextHandler2Helper& rParent, DataPointModel& rModel ); virtual ~DataPointContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; struct SeriesModel; /** Handler base class for chart data series contexts (c:ser element). */ class SeriesContextBase : public ContextBase< SeriesModel > { public: explicit SeriesContextBase( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~SeriesContextBase(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; /** Handler for a data series context for area chart types (c:ser element). */ class AreaSeriesContext : public SeriesContextBase { public: explicit AreaSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~AreaSeriesContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; /** Handler for a data series context for bar chart types (c:ser element). */ class BarSeriesContext : public SeriesContextBase { public: explicit BarSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~BarSeriesContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; /** Handler for a data series context for bubble chart types (c:ser element). */ class BubbleSeriesContext : public SeriesContextBase { public: explicit BubbleSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~BubbleSeriesContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; /** Handler for a data series context for line and stock chart types (c:ser element). */ class LineSeriesContext : public SeriesContextBase { public: explicit LineSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~LineSeriesContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; /** Handler for a data series context for pie and doughnut chart types (c:ser element). */ class PieSeriesContext : public SeriesContextBase { public: explicit PieSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~PieSeriesContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; /** Handler for a data series context for radar chart types (c:ser element). */ class RadarSeriesContext : public SeriesContextBase { public: explicit RadarSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~RadarSeriesContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; /** Handler for a data series context for scatter chart types (c:ser element). */ class ScatterSeriesContext : public SeriesContextBase { public: explicit ScatterSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~ScatterSeriesContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; /** Handler for a data series context for scatter chart types (c:ser element). */ class SurfaceSeriesContext : public SeriesContextBase { public: explicit SurfaceSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~SurfaceSeriesContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; } // namespace chart } // namespace drawingml } // namespace oox #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Most certainly meant to be plural.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_OOX_DRAWINGML_CHART_SERIESCONTEXT_HXX #define INCLUDED_OOX_DRAWINGML_CHART_SERIESCONTEXT_HXX #include <drawingml/chart/chartcontextbase.hxx> namespace oox { namespace drawingml { namespace chart { struct DataLabelModel; /** Handler for a chart data point label context (c:dLbl element). */ class DataLabelContext : public ContextBase< DataLabelModel > { public: explicit DataLabelContext( ::oox::core::ContextHandler2Helper& rParent, DataLabelModel& rModel ); virtual ~DataLabelContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; virtual void onCharacters( const OUString& rChars ) SAL_OVERRIDE; }; struct DataLabelsModel; /** Handler for a chart data point label context (c:dLbls element). */ class DataLabelsContext : public ContextBase< DataLabelsModel > { public: explicit DataLabelsContext( ::oox::core::ContextHandler2Helper& rParent, DataLabelsModel& rModel ); virtual ~DataLabelsContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; virtual void onCharacters( const OUString& rChars ) SAL_OVERRIDE; }; struct PictureOptionsModel; /** Handler for fill bitmap settings (c:pictureOptions element). */ class PictureOptionsContext : public ContextBase< PictureOptionsModel > { public: explicit PictureOptionsContext( ::oox::core::ContextHandler2Helper& rParent, PictureOptionsModel& rModel ); virtual ~PictureOptionsContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; struct ErrorBarModel; /** Handler for a series error bar context (c:errBars element). */ class ErrorBarContext : public ContextBase< ErrorBarModel > { public: explicit ErrorBarContext( ::oox::core::ContextHandler2Helper& rParent, ErrorBarModel& rModel ); virtual ~ErrorBarContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; struct TrendlineLabelModel; /** Handler for a series trendline label context (c:trendlineLbl element). */ class TrendlineLabelContext : public ContextBase< TrendlineLabelModel > { public: explicit TrendlineLabelContext( ::oox::core::ContextHandler2Helper& rParent, TrendlineLabelModel& rModel ); virtual ~TrendlineLabelContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; struct TrendlineModel; /** Handler for a series trendline context (c:trendline element). */ class TrendlineContext : public ContextBase< TrendlineModel > { public: explicit TrendlineContext( ::oox::core::ContextHandler2Helper& rParent, TrendlineModel& rModel ); virtual ~TrendlineContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; virtual void onCharacters( const OUString& rChars ) SAL_OVERRIDE; }; struct DataPointModel; /** Handler for a chart data point context (c:dPt element). */ class DataPointContext : public ContextBase< DataPointModel > { public: explicit DataPointContext( ::oox::core::ContextHandler2Helper& rParent, DataPointModel& rModel ); virtual ~DataPointContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; struct SeriesModel; /** Handler base class for chart data series contexts (c:ser element). */ class SeriesContextBase : public ContextBase< SeriesModel > { public: explicit SeriesContextBase( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~SeriesContextBase(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; /** Handler for a data series context for area chart types (c:ser element). */ class AreaSeriesContext : public SeriesContextBase { public: explicit AreaSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~AreaSeriesContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; /** Handler for a data series context for bar chart types (c:ser element). */ class BarSeriesContext : public SeriesContextBase { public: explicit BarSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~BarSeriesContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; /** Handler for a data series context for bubble chart types (c:ser element). */ class BubbleSeriesContext : public SeriesContextBase { public: explicit BubbleSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~BubbleSeriesContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; /** Handler for a data series context for line and stock chart types (c:ser element). */ class LineSeriesContext : public SeriesContextBase { public: explicit LineSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~LineSeriesContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; /** Handler for a data series context for pie and doughnut chart types (c:ser element). */ class PieSeriesContext : public SeriesContextBase { public: explicit PieSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~PieSeriesContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; /** Handler for a data series context for radar chart types (c:ser element). */ class RadarSeriesContext : public SeriesContextBase { public: explicit RadarSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~RadarSeriesContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; /** Handler for a data series context for scatter chart types (c:ser element). */ class ScatterSeriesContext : public SeriesContextBase { public: explicit ScatterSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~ScatterSeriesContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; /** Handler for a data series context for scatter chart types (c:ser element). */ class SurfaceSeriesContext : public SeriesContextBase { public: explicit SurfaceSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel ); virtual ~SurfaceSeriesContext(); virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE; }; } // namespace chart } // namespace drawingml } // namespace oox #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* * reactor.cc * * Created on: Aug 1, 2014 * Author: avi */ #include "reactor.hh" #include <cassert> #include <unistd.h> #include <fcntl.h> #include <sys/eventfd.h> timespec to_timespec(clock_type::time_point t) { using ns = std::chrono::nanoseconds; auto n = std::chrono::duration_cast<ns>(t.time_since_epoch()).count(); return { n / 1'000'000'000, n % 1'000'000'000 }; } template <typename T> struct syscall_result { T result; int error; void throw_if_error() { if (long(result) == -1) { throw std::system_error(error, std::system_category()); } } }; template <typename T> syscall_result<T> wrap_syscall(T result) { syscall_result<T> sr; sr.result = result; sr.error = errno; return sr; } reactor::reactor() : _epollfd(file_desc::epoll_create(EPOLL_CLOEXEC)) , _io_eventfd() , _io_context(0) , _io_context_available(max_aio) { auto r = ::io_setup(max_aio, &_io_context); assert(r >= 0); _io_eventfd.wait().then([this] (size_t count) { process_io(count); }); } future<> reactor::get_epoll_future(pollable_fd_state& pfd, promise<> pollable_fd_state::*pr, int event) { if (pfd.events_known & event) { pfd.events_known &= ~event; return make_ready_future(); } pfd.events_requested |= event; if (!(pfd.events_epoll & event)) { auto ctl = pfd.events_epoll ? EPOLL_CTL_MOD : EPOLL_CTL_ADD; pfd.events_epoll |= event; ::epoll_event eevt; eevt.events = pfd.events_epoll; eevt.data.ptr = &pfd; int r = ::epoll_ctl(_epollfd.get(), ctl, pfd.fd.get(), &eevt); assert(r == 0); } pfd.*pr = promise<>(); return (pfd.*pr).get_future(); } future<> reactor::readable(pollable_fd_state& fd) { return get_epoll_future(fd, &pollable_fd_state::pollin, EPOLLIN); } future<> reactor::writeable(pollable_fd_state& fd) { return get_epoll_future(fd, &pollable_fd_state::pollout, EPOLLOUT); } void reactor::forget(pollable_fd_state& fd) { if (fd.events_epoll) { ::epoll_ctl(_epollfd.get(), EPOLL_CTL_DEL, fd.fd.get(), nullptr); } } pollable_fd reactor::listen(socket_address sa, listen_options opts) { file_desc fd = file_desc::socket(sa.u.sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if (opts.reuse_address) { int opt = 1; fd.setsockopt(SOL_SOCKET, SO_REUSEADDR, opt); } fd.bind(sa.u.sa, sizeof(sa.u.sas)); fd.listen(100); return pollable_fd(std::move(fd)); } void reactor::complete_epoll_event(pollable_fd_state& pfd, promise<> pollable_fd_state::*pr, int events, int event) { if (pfd.events_requested & events & event) { pfd.events_requested &= ~EPOLLIN; pfd.events_known &= ~EPOLLIN; (pfd.*pr).set_value(); pfd.*pr = promise<>(); } } template <typename Func> future<io_event> reactor::submit_io(Func prepare_io) { return _io_context_available.wait(1).then([this, prepare_io = std::move(prepare_io)] () mutable { auto pr = std::make_unique<promise<io_event>>(); iocb io; prepare_io(io); io.data = pr.get(); io_set_eventfd(&io, _io_eventfd.get_write_fd()); iocb* p = &io; auto r = ::io_submit(_io_context, 1, &p); throw_kernel_error(r); return pr.release()->get_future(); }); } void reactor::process_io(size_t count) { io_event ev[max_aio]; auto n = ::io_getevents(_io_context, count, count, ev, NULL); assert(n >= 0 && size_t(n) == count); for (size_t i = 0; i < size_t(n); ++i) { auto pr = reinterpret_cast<promise<io_event>*>(ev[i].data); pr->set_value(ev[i]); delete pr; } _io_context_available.signal(n); _io_eventfd.wait().then([this] (size_t count) { process_io(count); }); } future<size_t> reactor::write_dma(file& f, uint64_t pos, const void* buffer, size_t len) { return submit_io([&f, pos, buffer, len] (iocb& io) { io_prep_pwrite(&io, f._fd, const_cast<void*>(buffer), len, pos); }).then([] (io_event ev) { throw_kernel_error(long(ev.res)); return make_ready_future<size_t>(size_t(ev.res)); }); } future<size_t> reactor::write_dma(file& f, uint64_t pos, std::vector<iovec> iov) { return submit_io([&f, pos, iov = std::move(iov)] (iocb& io) { io_prep_pwritev(&io, f._fd, iov.data(), iov.size(), pos); }).then([] (io_event ev) { throw_kernel_error(long(ev.res)); return make_ready_future<size_t>(size_t(ev.res)); }); } future<size_t> reactor::read_dma(file& f, uint64_t pos, void* buffer, size_t len) { return submit_io([&f, pos, buffer, len] (iocb& io) { io_prep_pread(&io, f._fd, buffer, len, pos); }).then([] (io_event ev) { throw_kernel_error(long(ev.res)); return make_ready_future<size_t>(size_t(ev.res)); }); } future<size_t> reactor::read_dma(file& f, uint64_t pos, std::vector<iovec> iov) { return submit_io([&f, pos, iov = std::move(iov)] (iocb& io) { io_prep_preadv(&io, f._fd, iov.data(), iov.size(), pos); }).then([] (io_event ev) { throw_kernel_error(long(ev.res)); return make_ready_future<size_t>(size_t(ev.res)); }); } future<file> reactor::open_file_dma(sstring name) { return _thread_pool.submit<syscall_result<int>>([name] { return wrap_syscall<int>(::open(name.c_str(), O_DIRECT | O_CLOEXEC | O_CREAT | O_RDWR, S_IRWXU)); }).then([] (syscall_result<int> sr) { sr.throw_if_error(); return make_ready_future<file>(file(sr.result)); }); } future<> reactor::flush(file& f) { return _thread_pool.submit<syscall_result<int>>([&f] { return wrap_syscall<int>(::fsync(f._fd)); }).then([] (syscall_result<int> sr) { sr.throw_if_error(); return make_ready_future<>(); }); } void reactor::add_timer(timer* tmr) { if (_timers.insert(*tmr) && tmr->get_timeout() < _next_timeout) { itimerspec its; its.it_interval = {}; its.it_value = to_timespec(_timers.get_next_timeout()); _timerfd.get_file_desc().timerfd_settime(TFD_TIMER_ABSTIME, its); } } void reactor::del_timer(timer* tmr) { _timers.remove(*tmr); } void reactor::complete_timers() { _timerfd.read_some(reinterpret_cast<char*>(&_timers_completed), sizeof(_timers_completed)).then( [this] (size_t n) { _timers.expire(clock_type::now()); while (auto t = _timers.pop_expired()) { t->_pr.set_value(); t->_pr = promise<>(); } if (!_timers.empty()) { _next_timeout = _timers.get_next_timeout(); itimerspec its; its.it_interval = {}; its.it_value = to_timespec(_next_timeout); _timerfd.get_file_desc().timerfd_settime(TFD_TIMER_ABSTIME, its); } complete_timers(); }); } void reactor::run() { std::vector<std::unique_ptr<task>> current_tasks; _start_promise.set_value(); complete_timers(); while (true) { while (!_pending_tasks.empty()) { std::swap(_pending_tasks, current_tasks); for (auto&& tsk : current_tasks) { tsk->run(); tsk.reset(); } current_tasks.clear(); } std::array<epoll_event, 128> eevt; int nr = ::epoll_wait(_epollfd.get(), eevt.data(), eevt.size(), -1); assert(nr != -1); for (int i = 0; i < nr; ++i) { auto& evt = eevt[i]; auto pfd = reinterpret_cast<pollable_fd_state*>(evt.data.ptr); auto events = evt.events & (EPOLLIN | EPOLLOUT); std::unique_ptr<task> t_in, t_out; pfd->events_known |= events; auto events_to_remove = events & ~pfd->events_requested; complete_epoll_event(*pfd, &pollable_fd_state::pollin, events, EPOLLIN); complete_epoll_event(*pfd, &pollable_fd_state::pollout, events, EPOLLOUT); if (events_to_remove) { pfd->events_epoll &= ~events_to_remove; evt.events = pfd->events_epoll; auto op = evt.events ? EPOLL_CTL_MOD : EPOLL_CTL_DEL; ::epoll_ctl(_epollfd.get(), op, pfd->fd.get(), &evt); } } } } thread_pool::thread_pool() : _pending(queue_length) , _completed(queue_length) , _start_eventfd(0) , _complete_eventfd(0) , _worker_thread([this] { work(); }) { _worker_thread.detach(); complete(); } void thread_pool::work() { while (true) { uint64_t count; auto r = ::read(_start_eventfd.get_read_fd(), &count, sizeof(count)); assert(r == sizeof(count)); auto nr = _pending.consume_all([this] (work_item* wi) { wi->process(); _completed.push(wi); }); count = nr; r = ::write(_complete_eventfd.get_write_fd(), &count, sizeof(count)); assert(r == sizeof(count)); } } void thread_pool::submit_item(thread_pool::work_item* item) { _queue_has_room.wait().then([this, item] { _pending.push(item); _start_eventfd.signal(1); }); } void thread_pool::complete() { _complete_eventfd.wait().then([this] (size_t count) { auto nr = _completed.consume_all([this] (work_item* wi) { wi->complete(); delete wi; }); _queue_has_room.signal(nr); complete(); }); } file_desc writeable_eventfd::try_create_eventfd(size_t initial) { assert(size_t(int(initial)) == initial); return file_desc::eventfd(initial, EFD_CLOEXEC); } void writeable_eventfd::signal(size_t count) { uint64_t c = count; auto r = _fd.write(&c, sizeof(c)); assert(r == sizeof(c)); } file_desc readable_eventfd::try_create_eventfd(size_t initial) { assert(size_t(int(initial)) == initial); return file_desc::eventfd(initial, EFD_CLOEXEC | EFD_NONBLOCK); } future<size_t> readable_eventfd::wait() { return the_reactor.readable(*_fd._s).then([this] { uint64_t count; int r = ::read(_fd.get_fd(), &count, sizeof(count)); assert(r == sizeof(count)); return make_ready_future<size_t>(count); }); } socket_address make_ipv4_address(ipv4_addr addr) { socket_address sa; sa.u.in.sin_family = AF_INET; sa.u.in.sin_port = htons(addr.port); std::memcpy(&sa.u.in.sin_addr, addr.host, 4); return sa; } reactor the_reactor; <commit_msg>core: be more friendly to debuggers<commit_after>/* * reactor.cc * * Created on: Aug 1, 2014 * Author: avi */ #include "reactor.hh" #include <cassert> #include <unistd.h> #include <fcntl.h> #include <sys/eventfd.h> timespec to_timespec(clock_type::time_point t) { using ns = std::chrono::nanoseconds; auto n = std::chrono::duration_cast<ns>(t.time_since_epoch()).count(); return { n / 1'000'000'000, n % 1'000'000'000 }; } template <typename T> struct syscall_result { T result; int error; void throw_if_error() { if (long(result) == -1) { throw std::system_error(error, std::system_category()); } } }; template <typename T> syscall_result<T> wrap_syscall(T result) { syscall_result<T> sr; sr.result = result; sr.error = errno; return sr; } reactor::reactor() : _epollfd(file_desc::epoll_create(EPOLL_CLOEXEC)) , _io_eventfd() , _io_context(0) , _io_context_available(max_aio) { auto r = ::io_setup(max_aio, &_io_context); assert(r >= 0); _io_eventfd.wait().then([this] (size_t count) { process_io(count); }); } future<> reactor::get_epoll_future(pollable_fd_state& pfd, promise<> pollable_fd_state::*pr, int event) { if (pfd.events_known & event) { pfd.events_known &= ~event; return make_ready_future(); } pfd.events_requested |= event; if (!(pfd.events_epoll & event)) { auto ctl = pfd.events_epoll ? EPOLL_CTL_MOD : EPOLL_CTL_ADD; pfd.events_epoll |= event; ::epoll_event eevt; eevt.events = pfd.events_epoll; eevt.data.ptr = &pfd; int r = ::epoll_ctl(_epollfd.get(), ctl, pfd.fd.get(), &eevt); assert(r == 0); } pfd.*pr = promise<>(); return (pfd.*pr).get_future(); } future<> reactor::readable(pollable_fd_state& fd) { return get_epoll_future(fd, &pollable_fd_state::pollin, EPOLLIN); } future<> reactor::writeable(pollable_fd_state& fd) { return get_epoll_future(fd, &pollable_fd_state::pollout, EPOLLOUT); } void reactor::forget(pollable_fd_state& fd) { if (fd.events_epoll) { ::epoll_ctl(_epollfd.get(), EPOLL_CTL_DEL, fd.fd.get(), nullptr); } } pollable_fd reactor::listen(socket_address sa, listen_options opts) { file_desc fd = file_desc::socket(sa.u.sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if (opts.reuse_address) { int opt = 1; fd.setsockopt(SOL_SOCKET, SO_REUSEADDR, opt); } fd.bind(sa.u.sa, sizeof(sa.u.sas)); fd.listen(100); return pollable_fd(std::move(fd)); } void reactor::complete_epoll_event(pollable_fd_state& pfd, promise<> pollable_fd_state::*pr, int events, int event) { if (pfd.events_requested & events & event) { pfd.events_requested &= ~EPOLLIN; pfd.events_known &= ~EPOLLIN; (pfd.*pr).set_value(); pfd.*pr = promise<>(); } } template <typename Func> future<io_event> reactor::submit_io(Func prepare_io) { return _io_context_available.wait(1).then([this, prepare_io = std::move(prepare_io)] () mutable { auto pr = std::make_unique<promise<io_event>>(); iocb io; prepare_io(io); io.data = pr.get(); io_set_eventfd(&io, _io_eventfd.get_write_fd()); iocb* p = &io; auto r = ::io_submit(_io_context, 1, &p); throw_kernel_error(r); return pr.release()->get_future(); }); } void reactor::process_io(size_t count) { io_event ev[max_aio]; auto n = ::io_getevents(_io_context, count, count, ev, NULL); assert(n >= 0 && size_t(n) == count); for (size_t i = 0; i < size_t(n); ++i) { auto pr = reinterpret_cast<promise<io_event>*>(ev[i].data); pr->set_value(ev[i]); delete pr; } _io_context_available.signal(n); _io_eventfd.wait().then([this] (size_t count) { process_io(count); }); } future<size_t> reactor::write_dma(file& f, uint64_t pos, const void* buffer, size_t len) { return submit_io([&f, pos, buffer, len] (iocb& io) { io_prep_pwrite(&io, f._fd, const_cast<void*>(buffer), len, pos); }).then([] (io_event ev) { throw_kernel_error(long(ev.res)); return make_ready_future<size_t>(size_t(ev.res)); }); } future<size_t> reactor::write_dma(file& f, uint64_t pos, std::vector<iovec> iov) { return submit_io([&f, pos, iov = std::move(iov)] (iocb& io) { io_prep_pwritev(&io, f._fd, iov.data(), iov.size(), pos); }).then([] (io_event ev) { throw_kernel_error(long(ev.res)); return make_ready_future<size_t>(size_t(ev.res)); }); } future<size_t> reactor::read_dma(file& f, uint64_t pos, void* buffer, size_t len) { return submit_io([&f, pos, buffer, len] (iocb& io) { io_prep_pread(&io, f._fd, buffer, len, pos); }).then([] (io_event ev) { throw_kernel_error(long(ev.res)); return make_ready_future<size_t>(size_t(ev.res)); }); } future<size_t> reactor::read_dma(file& f, uint64_t pos, std::vector<iovec> iov) { return submit_io([&f, pos, iov = std::move(iov)] (iocb& io) { io_prep_preadv(&io, f._fd, iov.data(), iov.size(), pos); }).then([] (io_event ev) { throw_kernel_error(long(ev.res)); return make_ready_future<size_t>(size_t(ev.res)); }); } future<file> reactor::open_file_dma(sstring name) { return _thread_pool.submit<syscall_result<int>>([name] { return wrap_syscall<int>(::open(name.c_str(), O_DIRECT | O_CLOEXEC | O_CREAT | O_RDWR, S_IRWXU)); }).then([] (syscall_result<int> sr) { sr.throw_if_error(); return make_ready_future<file>(file(sr.result)); }); } future<> reactor::flush(file& f) { return _thread_pool.submit<syscall_result<int>>([&f] { return wrap_syscall<int>(::fsync(f._fd)); }).then([] (syscall_result<int> sr) { sr.throw_if_error(); return make_ready_future<>(); }); } void reactor::add_timer(timer* tmr) { if (_timers.insert(*tmr) && tmr->get_timeout() < _next_timeout) { itimerspec its; its.it_interval = {}; its.it_value = to_timespec(_timers.get_next_timeout()); _timerfd.get_file_desc().timerfd_settime(TFD_TIMER_ABSTIME, its); } } void reactor::del_timer(timer* tmr) { _timers.remove(*tmr); } void reactor::complete_timers() { _timerfd.read_some(reinterpret_cast<char*>(&_timers_completed), sizeof(_timers_completed)).then( [this] (size_t n) { _timers.expire(clock_type::now()); while (auto t = _timers.pop_expired()) { t->_pr.set_value(); t->_pr = promise<>(); } if (!_timers.empty()) { _next_timeout = _timers.get_next_timeout(); itimerspec its; its.it_interval = {}; its.it_value = to_timespec(_next_timeout); _timerfd.get_file_desc().timerfd_settime(TFD_TIMER_ABSTIME, its); } complete_timers(); }); } void reactor::run() { std::vector<std::unique_ptr<task>> current_tasks; _start_promise.set_value(); complete_timers(); while (true) { while (!_pending_tasks.empty()) { std::swap(_pending_tasks, current_tasks); for (auto&& tsk : current_tasks) { tsk->run(); tsk.reset(); } current_tasks.clear(); } std::array<epoll_event, 128> eevt; int nr = ::epoll_wait(_epollfd.get(), eevt.data(), eevt.size(), -1); if (nr == -1 && errno == EINTR) { continue; // gdb can cause this } assert(nr != -1); for (int i = 0; i < nr; ++i) { auto& evt = eevt[i]; auto pfd = reinterpret_cast<pollable_fd_state*>(evt.data.ptr); auto events = evt.events & (EPOLLIN | EPOLLOUT); std::unique_ptr<task> t_in, t_out; pfd->events_known |= events; auto events_to_remove = events & ~pfd->events_requested; complete_epoll_event(*pfd, &pollable_fd_state::pollin, events, EPOLLIN); complete_epoll_event(*pfd, &pollable_fd_state::pollout, events, EPOLLOUT); if (events_to_remove) { pfd->events_epoll &= ~events_to_remove; evt.events = pfd->events_epoll; auto op = evt.events ? EPOLL_CTL_MOD : EPOLL_CTL_DEL; ::epoll_ctl(_epollfd.get(), op, pfd->fd.get(), &evt); } } } } thread_pool::thread_pool() : _pending(queue_length) , _completed(queue_length) , _start_eventfd(0) , _complete_eventfd(0) , _worker_thread([this] { work(); }) { _worker_thread.detach(); complete(); } void thread_pool::work() { while (true) { uint64_t count; auto r = ::read(_start_eventfd.get_read_fd(), &count, sizeof(count)); assert(r == sizeof(count)); auto nr = _pending.consume_all([this] (work_item* wi) { wi->process(); _completed.push(wi); }); count = nr; r = ::write(_complete_eventfd.get_write_fd(), &count, sizeof(count)); assert(r == sizeof(count)); } } void thread_pool::submit_item(thread_pool::work_item* item) { _queue_has_room.wait().then([this, item] { _pending.push(item); _start_eventfd.signal(1); }); } void thread_pool::complete() { _complete_eventfd.wait().then([this] (size_t count) { auto nr = _completed.consume_all([this] (work_item* wi) { wi->complete(); delete wi; }); _queue_has_room.signal(nr); complete(); }); } file_desc writeable_eventfd::try_create_eventfd(size_t initial) { assert(size_t(int(initial)) == initial); return file_desc::eventfd(initial, EFD_CLOEXEC); } void writeable_eventfd::signal(size_t count) { uint64_t c = count; auto r = _fd.write(&c, sizeof(c)); assert(r == sizeof(c)); } file_desc readable_eventfd::try_create_eventfd(size_t initial) { assert(size_t(int(initial)) == initial); return file_desc::eventfd(initial, EFD_CLOEXEC | EFD_NONBLOCK); } future<size_t> readable_eventfd::wait() { return the_reactor.readable(*_fd._s).then([this] { uint64_t count; int r = ::read(_fd.get_fd(), &count, sizeof(count)); assert(r == sizeof(count)); return make_ready_future<size_t>(count); }); } socket_address make_ipv4_address(ipv4_addr addr) { socket_address sa; sa.u.in.sin_family = AF_INET; sa.u.in.sin_port = htons(addr.port); std::memcpy(&sa.u.in.sin_addr, addr.host, 4); return sa; } reactor the_reactor; <|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. ===================================================================*/ #include "mitkTrackingDeviceSourceConfigurator.h" #include <mitkClaronTrackingDevice.h> #include <mitkNDITrackingDevice.h> #include <mitkNavigationTool.h> #include <mitkTestingMacros.h> #include <mitkIGTConfig.h> static void TestInstantiation() { // let's create an object of our class mitk::TrackingDeviceSourceConfigurator::Pointer testInstance; mitk::NavigationToolStorage::Pointer emptyStorage = mitk::NavigationToolStorage::New(); mitk::TrackingDevice::Pointer dummyDevice = dynamic_cast<mitk::TrackingDevice*>(mitk::ClaronTrackingDevice::New().GetPointer()); testInstance = mitk::TrackingDeviceSourceConfigurator::New(emptyStorage,dummyDevice); MITK_TEST_CONDITION_REQUIRED(testInstance.IsNotNull(),"Testing instantiation:"); } static void TestInvalidClaronTrackingDevice() { MITK_TEST_OUTPUT(<<"Testing simple claron tracking device with 2 invalid tools"); mitk::TrackingDeviceSourceConfigurator::Pointer testInstance; mitk::NavigationToolStorage::Pointer claronStorage = mitk::NavigationToolStorage::New(); //create invalid tool 1 mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New(); firstTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer firstNode = mitk::DataNode::New(); firstNode->SetName("Tool1"); firstTool->SetDataNode(firstNode); claronStorage->AddTool(firstTool); //create invalid tool 2 mitk::NavigationTool::Pointer secondTool = mitk::NavigationTool::New(); secondTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer secondNode = mitk::DataNode::New(); secondNode->SetName("Tool2"); secondTool->SetDataNode(secondNode); claronStorage->AddTool(secondTool); mitk::TrackingDevice::Pointer testDevice = dynamic_cast<mitk::TrackingDevice*>(mitk::ClaronTrackingDevice::New().GetPointer()); testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice); mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource(); MITK_TEST_CONDITION_REQUIRED(testSource.IsNull(),"..testing return value"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetErrorMessage().size()>1,"..testing if there is an error message"); MITK_TEST_OUTPUT(<<"Testing simple claron tracking device with another 2 invalid tools"); secondTool->SetTrackingDeviceType(mitk::NDIAurora); claronStorage = mitk::NavigationToolStorage::New(); claronStorage->AddTool(secondTool); testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice); MITK_TEST_CONDITION_REQUIRED(!testInstance->IsCreateTrackingDeviceSourcePossible(),"..testing if factory class detects the invalid data"); testSource = testInstance->CreateTrackingDeviceSource(); MITK_TEST_CONDITION_REQUIRED(testSource.IsNull(),"..testing return value"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetErrorMessage().size()>1,"..testing if there is an error message"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetUpdatedNavigationToolStorage()->GetToolCount()==1,"..testing if navigation tool storage is still there"); MITK_TEST_OUTPUT(<<"Testing other invalid test cases"); testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,NULL); MITK_TEST_CONDITION_REQUIRED(!testInstance->IsCreateTrackingDeviceSourcePossible(),"..(1) testing if factory class detects the invalid data"); testInstance = mitk::TrackingDeviceSourceConfigurator::New(NULL,testDevice); MITK_TEST_CONDITION_REQUIRED(!testInstance->IsCreateTrackingDeviceSourcePossible(),"..(2) testing if factory class detects the invalid data"); } static void TestValidClaronTrackingDevice() { MITK_TEST_OUTPUT(<<"Testing simple claron tracking device with 2 valid tools"); std::string toolFileName(MITK_IGT_DATA_DIR); toolFileName.append("/ClaronTool"); mitk::TrackingDeviceSourceConfigurator::Pointer testInstance; mitk::NavigationToolStorage::Pointer claronStorage = mitk::NavigationToolStorage::New(); //create valid tool 1 mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New(); firstTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer firstNode = mitk::DataNode::New(); firstNode->SetName("Tool1"); firstTool->SetDataNode(firstNode); firstTool->SetCalibrationFile(toolFileName); firstTool->SetIdentifier("Tool#1"); claronStorage->AddTool(firstTool); //create valid tool 2 mitk::NavigationTool::Pointer secondTool = mitk::NavigationTool::New(); secondTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer secondNode = mitk::DataNode::New(); secondNode->SetName("Tool2"); secondTool->SetDataNode(secondNode); secondTool->SetCalibrationFile(toolFileName); secondTool->SetIdentifier("Tool#2"); claronStorage->AddTool(secondTool); mitk::TrackingDevice::Pointer testDevice = dynamic_cast<mitk::TrackingDevice*>(mitk::ClaronTrackingDevice::New().GetPointer()); testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice); mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource(); MITK_TEST_CONDITION_REQUIRED(testSource->GetNumberOfOutputs()==2,"testing number of outputs"); MITK_TEST_CONDITION_REQUIRED(testSource->GetTrackingDevice()->GetToolCount()==2,"testing tracking device"); } /* static void TestNDIAuroraTrackingDevice() { } */ /* static void TestNDIPolarisTrackingDevice() { MITK_TEST_OUTPUT(<<"Testing simple NDI Polaris tracking device with 1 valid tool"); std::string toolFileName(MITK_IGT_DATA_DIR); toolFileName.append("/SROMFile.rom"); mitk::TrackingDeviceSourceConfigurator::Pointer testInstance; mitk::NavigationToolStorage::Pointer polarisStorage = mitk::NavigationToolStorage::New(); //create valid tool 1 mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New(); firstTool->SetTrackingDeviceType(mitk::NDIPolaris); mitk::DataNode::Pointer firstNode = mitk::DataNode::New(); firstNode->SetName("Tool1"); firstTool->SetDataNode(firstNode); firstTool->SetCalibrationFile(toolFileName); firstTool->SetIdentifier("Tool#1"); polarisStorage->AddTool(firstTool); mitk::NDITrackingDevice::Pointer ndiDevice = mitk::NDITrackingDevice::New(); ndiDevice->SetType(mitk::NDIPolaris); mitk::TrackingDevice::Pointer testDevice = dynamic_cast<mitk::TrackingDevice*>(ndiDevice.GetPointer()); testInstance = mitk::TrackingDeviceSourceConfigurator::New(polarisStorage,testDevice); mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource(); MITK_TEST_CONDITION_REQUIRED(testSource->GetNumberOfOutputs()==1,"..testing number of outputs"); MITK_TEST_CONDITION_REQUIRED(testSource->GetTrackingDevice()->GetToolCount()==1,"..testing tracking device"); } */ static void TestAdditionalMethods() { MITK_TEST_OUTPUT(<<"Testing additional methods of TrackingDeviceSourceCOnfigurator"); MITK_TEST_OUTPUT(<<"..using claron tracking device for testing"); std::string toolFileName(MITK_IGT_DATA_DIR); toolFileName.append("/ClaronTool"); mitk::TrackingDeviceSourceConfigurator::Pointer testInstance; mitk::NavigationToolStorage::Pointer claronStorage = mitk::NavigationToolStorage::New(); //create valid tool 1 mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New(); firstTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer firstNode = mitk::DataNode::New(); firstNode->SetName("Tool1"); firstTool->SetDataNode(firstNode); firstTool->SetCalibrationFile(toolFileName); firstTool->SetIdentifier("Tool#1"); claronStorage->AddTool(firstTool); //create valid tool 2 mitk::NavigationTool::Pointer secondTool = mitk::NavigationTool::New(); secondTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer secondNode = mitk::DataNode::New(); secondNode->SetName("Tool2"); secondTool->SetDataNode(secondNode); secondTool->SetCalibrationFile(toolFileName); secondTool->SetIdentifier("Tool#2"); claronStorage->AddTool(secondTool); mitk::TrackingDevice::Pointer testDevice = dynamic_cast<mitk::TrackingDevice*>(mitk::ClaronTrackingDevice::New().GetPointer()); testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice); mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource(); //numbers must be the same in case of MicronTracker MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolNumberInToolStorage(0)==0,"..testing method GetToolNumberInToolStorage()"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolIdentifierInToolStorage(0)=="Tool#1","..testing method GetToolIdentifierInToolStorage()"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolNumbersInToolStorage().at(0)==0,"..testing method GetToolNumbersInToolStorage()"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolIdentifiersInToolStorage().at(0)=="Tool#1","..testing method GetToolIdentifiersInToolStorage()"); } int mitkTrackingDeviceSourceConfiguratorTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("TrackingDeviceConfigurator"); TestInstantiation(); TestInvalidClaronTrackingDevice(); TestValidClaronTrackingDevice(); TestAdditionalMethods(); MITK_TEST_END(); } <commit_msg>Removed two out-commented tests which were not belonging in that file. Created feature request 16919 to re-include these tests in a real hardware test.<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. ===================================================================*/ #include "mitkTrackingDeviceSourceConfigurator.h" #include <mitkClaronTrackingDevice.h> #include <mitkNDITrackingDevice.h> #include <mitkNavigationTool.h> #include <mitkTestingMacros.h> #include <mitkIGTConfig.h> static void TestInstantiation() { // let's create an object of our class mitk::TrackingDeviceSourceConfigurator::Pointer testInstance; mitk::NavigationToolStorage::Pointer emptyStorage = mitk::NavigationToolStorage::New(); mitk::TrackingDevice::Pointer dummyDevice = dynamic_cast<mitk::TrackingDevice*>(mitk::ClaronTrackingDevice::New().GetPointer()); testInstance = mitk::TrackingDeviceSourceConfigurator::New(emptyStorage,dummyDevice); MITK_TEST_CONDITION_REQUIRED(testInstance.IsNotNull(),"Testing instantiation:"); } static void TestInvalidClaronTrackingDevice() { MITK_TEST_OUTPUT(<<"Testing simple claron tracking device with 2 invalid tools"); mitk::TrackingDeviceSourceConfigurator::Pointer testInstance; mitk::NavigationToolStorage::Pointer claronStorage = mitk::NavigationToolStorage::New(); //create invalid tool 1 mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New(); firstTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer firstNode = mitk::DataNode::New(); firstNode->SetName("Tool1"); firstTool->SetDataNode(firstNode); claronStorage->AddTool(firstTool); //create invalid tool 2 mitk::NavigationTool::Pointer secondTool = mitk::NavigationTool::New(); secondTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer secondNode = mitk::DataNode::New(); secondNode->SetName("Tool2"); secondTool->SetDataNode(secondNode); claronStorage->AddTool(secondTool); mitk::TrackingDevice::Pointer testDevice = dynamic_cast<mitk::TrackingDevice*>(mitk::ClaronTrackingDevice::New().GetPointer()); testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice); mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource(); MITK_TEST_CONDITION_REQUIRED(testSource.IsNull(),"..testing return value"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetErrorMessage().size()>1,"..testing if there is an error message"); MITK_TEST_OUTPUT(<<"Testing simple claron tracking device with another 2 invalid tools"); secondTool->SetTrackingDeviceType(mitk::NDIAurora); claronStorage = mitk::NavigationToolStorage::New(); claronStorage->AddTool(secondTool); testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice); MITK_TEST_CONDITION_REQUIRED(!testInstance->IsCreateTrackingDeviceSourcePossible(),"..testing if factory class detects the invalid data"); testSource = testInstance->CreateTrackingDeviceSource(); MITK_TEST_CONDITION_REQUIRED(testSource.IsNull(),"..testing return value"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetErrorMessage().size()>1,"..testing if there is an error message"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetUpdatedNavigationToolStorage()->GetToolCount()==1,"..testing if navigation tool storage is still there"); MITK_TEST_OUTPUT(<<"Testing other invalid test cases"); testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,NULL); MITK_TEST_CONDITION_REQUIRED(!testInstance->IsCreateTrackingDeviceSourcePossible(),"..(1) testing if factory class detects the invalid data"); testInstance = mitk::TrackingDeviceSourceConfigurator::New(NULL,testDevice); MITK_TEST_CONDITION_REQUIRED(!testInstance->IsCreateTrackingDeviceSourcePossible(),"..(2) testing if factory class detects the invalid data"); } static void TestValidClaronTrackingDevice() { MITK_TEST_OUTPUT(<<"Testing simple claron tracking device with 2 valid tools"); std::string toolFileName(MITK_IGT_DATA_DIR); toolFileName.append("/ClaronTool"); mitk::TrackingDeviceSourceConfigurator::Pointer testInstance; mitk::NavigationToolStorage::Pointer claronStorage = mitk::NavigationToolStorage::New(); //create valid tool 1 mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New(); firstTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer firstNode = mitk::DataNode::New(); firstNode->SetName("Tool1"); firstTool->SetDataNode(firstNode); firstTool->SetCalibrationFile(toolFileName); firstTool->SetIdentifier("Tool#1"); claronStorage->AddTool(firstTool); //create valid tool 2 mitk::NavigationTool::Pointer secondTool = mitk::NavigationTool::New(); secondTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer secondNode = mitk::DataNode::New(); secondNode->SetName("Tool2"); secondTool->SetDataNode(secondNode); secondTool->SetCalibrationFile(toolFileName); secondTool->SetIdentifier("Tool#2"); claronStorage->AddTool(secondTool); mitk::TrackingDevice::Pointer testDevice = dynamic_cast<mitk::TrackingDevice*>(mitk::ClaronTrackingDevice::New().GetPointer()); testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice); mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource(); MITK_TEST_CONDITION_REQUIRED(testSource->GetNumberOfOutputs()==2,"testing number of outputs"); MITK_TEST_CONDITION_REQUIRED(testSource->GetTrackingDevice()->GetToolCount()==2,"testing tracking device"); } static void TestAdditionalMethods() { MITK_TEST_OUTPUT(<<"Testing additional methods of TrackingDeviceSourceCOnfigurator"); MITK_TEST_OUTPUT(<<"..using claron tracking device for testing"); std::string toolFileName(MITK_IGT_DATA_DIR); toolFileName.append("/ClaronTool"); mitk::TrackingDeviceSourceConfigurator::Pointer testInstance; mitk::NavigationToolStorage::Pointer claronStorage = mitk::NavigationToolStorage::New(); //create valid tool 1 mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New(); firstTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer firstNode = mitk::DataNode::New(); firstNode->SetName("Tool1"); firstTool->SetDataNode(firstNode); firstTool->SetCalibrationFile(toolFileName); firstTool->SetIdentifier("Tool#1"); claronStorage->AddTool(firstTool); //create valid tool 2 mitk::NavigationTool::Pointer secondTool = mitk::NavigationTool::New(); secondTool->SetTrackingDeviceType(mitk::ClaronMicron); mitk::DataNode::Pointer secondNode = mitk::DataNode::New(); secondNode->SetName("Tool2"); secondTool->SetDataNode(secondNode); secondTool->SetCalibrationFile(toolFileName); secondTool->SetIdentifier("Tool#2"); claronStorage->AddTool(secondTool); mitk::TrackingDevice::Pointer testDevice = dynamic_cast<mitk::TrackingDevice*>(mitk::ClaronTrackingDevice::New().GetPointer()); testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice); mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource(); //numbers must be the same in case of MicronTracker MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolNumberInToolStorage(0)==0,"..testing method GetToolNumberInToolStorage()"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolIdentifierInToolStorage(0)=="Tool#1","..testing method GetToolIdentifierInToolStorage()"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolNumbersInToolStorage().at(0)==0,"..testing method GetToolNumbersInToolStorage()"); MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolIdentifiersInToolStorage().at(0)=="Tool#1","..testing method GetToolIdentifiersInToolStorage()"); } int mitkTrackingDeviceSourceConfiguratorTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("TrackingDeviceConfigurator"); TestInstantiation(); TestInvalidClaronTrackingDevice(); TestValidClaronTrackingDevice(); TestAdditionalMethods(); MITK_TEST_END(); } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2013 - 2018) // René Fritze (2014, 2016, 2018) // René Milk (2017) // Tobias Leibner (2014, 2016) #ifndef DUNE_GDT_PROLONGATIONS_HH #define DUNE_GDT_PROLONGATIONS_HH #include <vector> #include <dune/common/dynvector.hh> #include <dune/xt/la/container/vector-interface.hh> #include <dune/gdt/discretefunction/bochner.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/discretefunction/reinterpret.hh> #include <dune/gdt/interpolations.hh> #include <dune/gdt/spaces/bochner.hh> #include <dune/gdt/spaces/interface.hh> namespace Dune { namespace GDT { // ## Variants for a DiscreteFunction ## /** * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [most general * variant]. * * \note This does not clear target.dofs().vector(). Thus, if prolongation_grid_view only covers a part of the domain of * target.space().grid_view(), other contributions in target remain (which is on purpose). * * \sa interpolate * \sa reinterpret */ template <class SV, class SGV, size_t r, size_t rC, class SR, class TV, class TGV, class TR, class PGV> std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value, void> prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, DiscreteFunction<TV, TGV, r, rC, TR>& target, const GridView<PGV>& prolongation_grid_view) { interpolate(reinterpret(source, prolongation_grid_view), target, prolongation_grid_view); } /** * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [uses * target.space().grid_view() as prolongation_grid_view]. */ template <class SV, class SGV, size_t r, size_t rC, class SR, class TV, class TGV, class TR> void prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, DiscreteFunction<TV, TGV, r, rC, TR>& target) { prolong(source, target, target.space().grid_view()); } /** * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates * suitable target_function, TargetVectorType has to be provided]. * * Use as in \code auto target_function = prolong<TargetVectorType>(source, target_space, prolongation_grid_view); \endcode */ template <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class SR, class TGV, class TR, class PGV> std::enable_if_t< XT::LA::is_vector<TargetVectorType>::value && std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value, DiscreteFunction<TargetVectorType, TGV, r, rC, TR>> prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, const SpaceInterface<TGV, r, rC, TR>& target_space, const GridView<PGV>& prolongation_grid_view) { auto target_function = make_discrete_function<TargetVectorType>(target_space); prolong(source, target_function, prolongation_grid_view); return target_function; } /** * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates * suitable target_function, TargetVectorType has to be provided, uses target.space().grid_view() as * prolongation_grid_view]. * * Use as in \code auto target_function = prolong<TargetVectorType>(source, target_space); \endcode */ template <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class SR, class TGV, class TR> std::enable_if_t<XT::LA::is_vector<TargetVectorType>::value, DiscreteFunction<TargetVectorType, TGV, r, rC, TR>> prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, const SpaceInterface<TGV, r, rC, TR>& target_space) { auto target_function = make_discrete_function<TargetVectorType>(target_space); prolong(source, target_function); return target_function; } /** * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates * suitable target_function with same VectorType as source]. */ template <class V, class SGV, size_t r, size_t rC, class SR, class TGV, class TR, class PGV> std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value, DiscreteFunction<V, TGV, r, rC, TR>> prolong(const DiscreteFunction<V, SGV, r, rC, SR>& source, const SpaceInterface<TGV, r, rC, TR>& target_space, const GridView<PGV>& prolongation_grid_view) { auto target_function = make_discrete_function<V>(target_space); prolong(source, target_function, prolongation_grid_view); return target_function; } /** * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates * suitable target_function with same VectorType as source, uses target.space().grid_view() as * prolongation_grid_view]. */ template <class V, class SGV, size_t r, size_t rC, class SR, class TGV, class TR> DiscreteFunction<V, TGV, r, rC, TR> prolong(const DiscreteFunction<V, SGV, r, rC, SR>& source, const SpaceInterface<TGV, r, rC, TR>& target_space) { auto target_function = make_discrete_function<V>(target_space); prolong(source, target_function); return target_function; } // ## Variants for a DiscreteBochnerFunction ## /** * \brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one [most * general variant]. * * \note Uses prolong() in space. * * \sa prolong * \sa interpolate * \sa reinterpret */ template <class SV, class SGV, size_t r, size_t rC, class R, class TV, class TGV, class PGV> void prolong(const DiscreteBochnerFunction<SV, SGV, r, rC, R>& source, DiscreteBochnerFunction<TV, TGV, r, rC, R>& target, const GridView<PGV>& spatial_prolongation_grid_view) { // prepare const auto& temporal_space = target.space().temporal_space(); DynamicVector<size_t> local_dof_indices(temporal_space.mapper().max_local_size()); std::vector<bool> dof_has_been_handled(temporal_space.mapper().size(), false); // walk the time intervals for (auto&& time_interval : elements(temporal_space.grid_view())) { temporal_space.mapper().global_indices(time_interval, local_dof_indices); const auto& lagrange_points_in_time = temporal_space.finite_element(time_interval.geometry().type()).lagrange_points(); for (size_t ii = 0; ii < lagrange_points_in_time.size(); ++ii) { const size_t global_dof_index = local_dof_indices[ii]; if (!dof_has_been_handled[global_dof_index]) { const auto& point_in_time = time_interval.geometry().global(lagrange_points_in_time[ii]); // evaluate in time const auto coarse_spatial_function = source.evaluate(point_in_time); // prolong in space auto fine_spatial_function = make_discrete_function(target.space().spatial_space(), target.dof_vectors()[global_dof_index].vector()); prolong(coarse_spatial_function, fine_spatial_function, spatial_prolongation_grid_view); dof_has_been_handled[global_dof_index] = true; } } } } // ... prolong(...) /** * \brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one [uses * target.space().spatial_space().grid_view() as spatial_prolongation_grid_view]. * * \note Uses prolong() in space. * * \sa prolong * \sa interpolate * \sa reinterpret */ template <class SV, class SGV, size_t r, size_t rC, class R, class TV, class TGV> void prolong(const DiscreteBochnerFunction<SV, SGV, r, rC, R>& source, DiscreteBochnerFunction<TV, TGV, r, rC, R>& target) { prolong(source, target, target.space().spatial_space().grid_view()); } /** * \brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one * [creates suitable target_function, TargetVectorType has to be provided]. * * Use as in \code auto target_function = prolong<TargetVectorType>(source, target_space, spatial_prolongation_grid_view); \endcode */ template <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class R, class TGV, class PGV> std::enable_if_t< XT::LA::is_vector<TargetVectorType>::value && std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value, DiscreteBochnerFunction<TargetVectorType, TGV, r, rC, R>> prolong(const DiscreteBochnerFunction<SV, SGV, r, rC, R>& source, const BochnerSpace<TGV, r, rC, R>& target_space, const GridView<PGV>& spatial_prolongation_grid_view) { auto target_function = make_discrete_bochner_function<TargetVectorType>(target_space); prolong(source, target_function, spatial_prolongation_grid_view); return target_function; } template <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class R, class TGV> std::enable_if_t<XT::LA::is_vector<TargetVectorType>::value, DiscreteBochnerFunction<TargetVectorType, TGV, r, rC, R>> prolong(const DiscreteBochnerFunction<SV, SGV, r, rC, R>& source, const BochnerSpace<TGV, r, rC, R>& target_space) { return prolong<TargetVectorType>(source, target_space, target_space.spatial_space().grid_view()); } } // namespace GDT } // namespace Dune #endif // DUNE_GDT_PROLONGATIONS_HH <commit_msg>[prolongations] fix ambiguouity<commit_after>// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2013 - 2018) // René Fritze (2014, 2016, 2018) // René Milk (2017) // Tobias Leibner (2014, 2016) #ifndef DUNE_GDT_PROLONGATIONS_HH #define DUNE_GDT_PROLONGATIONS_HH #include <vector> #include <dune/common/dynvector.hh> #include <dune/xt/la/container/vector-interface.hh> #include <dune/gdt/discretefunction/bochner.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/discretefunction/reinterpret.hh> #include <dune/gdt/interpolations.hh> #include <dune/gdt/spaces/bochner.hh> #include <dune/gdt/spaces/interface.hh> namespace Dune { namespace GDT { // ## Variants for a DiscreteFunction ## /** * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [most general * variant]. * * \note This does not clear target.dofs().vector(). Thus, if prolongation_grid_view only covers a part of the domain of * target.space().grid_view(), other contributions in target remain (which is on purpose). * * \sa interpolate * \sa reinterpret */ template <class SV, class SGV, size_t r, size_t rC, class SR, class TV, class TGV, class TR, class PGV> std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value, void> prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, DiscreteFunction<TV, TGV, r, rC, TR>& target, const GridView<PGV>& prolongation_grid_view) { interpolate(reinterpret(source, prolongation_grid_view), target, prolongation_grid_view); } /** * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [uses * target.space().grid_view() as prolongation_grid_view]. */ template <class SV, class SGV, size_t r, size_t rC, class SR, class TV, class TGV, class TR> void prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, DiscreteFunction<TV, TGV, r, rC, TR>& target) { prolong(source, target, target.space().grid_view()); } /** * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates * suitable target_function, TargetVectorType has to be provided]. * * Use as in \code auto target_function = prolong<TargetVectorType>(source, target_space, prolongation_grid_view); \endcode */ template <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class SR, class TGV, class TR, class PGV> std::enable_if_t< XT::LA::is_vector<TargetVectorType>::value && std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value, DiscreteFunction<TargetVectorType, TGV, r, rC, TR>> prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, const SpaceInterface<TGV, r, rC, TR>& target_space, const GridView<PGV>& prolongation_grid_view) { auto target_function = make_discrete_function<TargetVectorType>(target_space); prolong(source, target_function, prolongation_grid_view); return target_function; } /** * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates * suitable target_function, TargetVectorType has to be provided, uses target.space().grid_view() as * prolongation_grid_view]. * * Use as in \code auto target_function = prolong<TargetVectorType>(source, target_space); \endcode */ template <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class SR, class TGV, class TR> std::enable_if_t<XT::LA::is_vector<TargetVectorType>::value, DiscreteFunction<TargetVectorType, TGV, r, rC, TR>> prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, const SpaceInterface<TGV, r, rC, TR>& target_space) { auto target_function = make_discrete_function<TargetVectorType>(target_space); prolong(source, target_function); return target_function; } /** * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates * suitable target_function with same VectorType as source]. */ template <class V, class SGV, size_t r, size_t rC, class SR, class TGV, class TR, class PGV> std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value, DiscreteFunction<V, TGV, r, rC, TR>> prolong(const DiscreteFunction<V, SGV, r, rC, SR>& source, const SpaceInterface<TGV, r, rC, TR>& target_space, const GridView<PGV>& prolongation_grid_view) { auto target_function = make_discrete_function<V>(target_space); prolong(source, target_function, prolongation_grid_view); return target_function; } /** * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates * suitable target_function with same VectorType as source, uses target.space().grid_view() as * prolongation_grid_view]. */ // we require the enable_if for disambigouation with a variant above template <class SGV, class V, size_t r, size_t rC, class SR, class TGV, class TR> std::enable_if_t<!XT::LA::is_vector<SGV>::value, DiscreteFunction<V, TGV, r, rC, TR>> prolong(const DiscreteFunction<V, SGV, r, rC, SR>& source, const SpaceInterface<TGV, r, rC, TR>& target_space) { auto target_function = make_discrete_function<V>(target_space); prolong(source, target_function); return target_function; } // ## Variants for a DiscreteBochnerFunction ## /** * \brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one [most * general variant]. * * \note Uses prolong() in space. * * \sa prolong * \sa interpolate * \sa reinterpret */ template <class SV, class SGV, size_t r, size_t rC, class R, class TV, class TGV, class PGV> void prolong(const DiscreteBochnerFunction<SV, SGV, r, rC, R>& source, DiscreteBochnerFunction<TV, TGV, r, rC, R>& target, const GridView<PGV>& spatial_prolongation_grid_view) { // prepare const auto& temporal_space = target.space().temporal_space(); DynamicVector<size_t> local_dof_indices(temporal_space.mapper().max_local_size()); std::vector<bool> dof_has_been_handled(temporal_space.mapper().size(), false); // walk the time intervals for (auto&& time_interval : elements(temporal_space.grid_view())) { temporal_space.mapper().global_indices(time_interval, local_dof_indices); const auto& lagrange_points_in_time = temporal_space.finite_element(time_interval.geometry().type()).lagrange_points(); for (size_t ii = 0; ii < lagrange_points_in_time.size(); ++ii) { const size_t global_dof_index = local_dof_indices[ii]; if (!dof_has_been_handled[global_dof_index]) { const auto& point_in_time = time_interval.geometry().global(lagrange_points_in_time[ii]); // evaluate in time const auto coarse_spatial_function = source.evaluate(point_in_time); // prolong in space auto fine_spatial_function = make_discrete_function(target.space().spatial_space(), target.dof_vectors()[global_dof_index].vector()); prolong(coarse_spatial_function, fine_spatial_function, spatial_prolongation_grid_view); dof_has_been_handled[global_dof_index] = true; } } } } // ... prolong(...) /** * \brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one [uses * target.space().spatial_space().grid_view() as spatial_prolongation_grid_view]. * * \note Uses prolong() in space. * * \sa prolong * \sa interpolate * \sa reinterpret */ template <class SV, class SGV, size_t r, size_t rC, class R, class TV, class TGV> void prolong(const DiscreteBochnerFunction<SV, SGV, r, rC, R>& source, DiscreteBochnerFunction<TV, TGV, r, rC, R>& target) { prolong(source, target, target.space().spatial_space().grid_view()); } /** * \brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one * [creates suitable target_function, TargetVectorType has to be provided]. * * Use as in \code auto target_function = prolong<TargetVectorType>(source, target_space, spatial_prolongation_grid_view); \endcode */ template <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class R, class TGV, class PGV> std::enable_if_t< XT::LA::is_vector<TargetVectorType>::value && std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value, DiscreteBochnerFunction<TargetVectorType, TGV, r, rC, R>> prolong(const DiscreteBochnerFunction<SV, SGV, r, rC, R>& source, const BochnerSpace<TGV, r, rC, R>& target_space, const GridView<PGV>& spatial_prolongation_grid_view) { auto target_function = make_discrete_bochner_function<TargetVectorType>(target_space); prolong(source, target_function, spatial_prolongation_grid_view); return target_function; } template <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class R, class TGV> std::enable_if_t<XT::LA::is_vector<TargetVectorType>::value, DiscreteBochnerFunction<TargetVectorType, TGV, r, rC, R>> prolong(const DiscreteBochnerFunction<SV, SGV, r, rC, R>& source, const BochnerSpace<TGV, r, rC, R>& target_space) { return prolong<TargetVectorType>(source, target_space, target_space.spatial_space().grid_view()); } } // namespace GDT } // namespace Dune #endif // DUNE_GDT_PROLONGATIONS_HH <|endoftext|>
<commit_before>#include "vtkVuzixARScene.h" #include "vtkObjectFactory.h" vtkStandardNewMacro(vtkVuzixARScene); vtkVuzixARScene::vtkVuzixARScene(){ //allocates the piece of the compilation leftEyeRenderer = vtkRenderer::New(); rightEyeRenderer = vtkRenderer::New(); leftEyeCamera = vtkVuzixARCamera::New(); leftEyeRenderer->SetActiveCamera(leftEyeCamera); rightEyeCamera = vtkVuzixARCamera::New(); rightEyeRenderer->SetActiveCamera(rightEyeCamera); //allocate the texture bases for the renderers and link them together leftEyePhysicalWorld = 0; leftEyeTexture = vtkTexture::New(); leftEyeRenderer->SetBackgroundTexture( leftEyeTexture ); leftEyeRenderer->SetTexturedBackground( true ); rightEyePhysicalWorld = 0; rightEyeTexture = vtkTexture::New(); rightEyeRenderer->SetBackgroundTexture( rightEyeTexture ); rightEyeRenderer->SetTexturedBackground( true ); //set some defaults for the poses trackedDevice = vtkTransform::New(); trackedDevice->Identity(); deviceToLeftEye = vtkTransform::New(); deviceToLeftEye->Identity(); deviceToRightEye = vtkTransform::New(); deviceToRightEye->Identity(); //allocate space for the temporary variables leftFocalPoint = vtkTransform::New(); leftFocalPoint->PostMultiply(); rightFocalPoint = vtkTransform::New(); rightFocalPoint->PostMultiply(); IdealLeftFocus = 1.0; IdealRightFocus = 1.0; } vtkVuzixARScene::~vtkVuzixARScene(){ leftEyeTexture->Delete(); rightEyeTexture->Delete(); leftEyeRenderer->Delete(); rightEyeRenderer->Delete(); leftEyeCamera->Delete(); rightEyeCamera->Delete(); leftFocalPoint->Delete(); rightFocalPoint->Delete(); deviceToLeftEye->Delete(); deviceToRightEye->Delete(); } void vtkVuzixARScene::Update(){ //update the frame sizes UpdateFrameSizes(); //tell the cameras that they have been modified leftEyeCamera->Modified(); rightEyeCamera->Modified(); } //update the frame sizes on the cameras (used for determining the projection matrix) void vtkVuzixARScene::UpdateFrameSizes(){ if( leftEyePhysicalWorld ){ int extent[6]; this->leftEyePhysicalWorld->GetExtent( extent ); this->leftEyeCamera->SetFrameSize( (double) (extent[1] - extent[0]+1), (double) (extent[3] - extent[2]+1) ); } if( rightEyePhysicalWorld ){ int extent[6]; this->rightEyePhysicalWorld->GetExtent( extent ); this->rightEyeCamera->SetFrameSize( (double) (extent[1] - extent[0]+1), (double) (extent[3] - extent[2]+1) ); } } vtkRenderer* vtkVuzixARScene::GetLeftEyeView(){ return leftEyeRenderer; } vtkRenderer* vtkVuzixARScene::GetRightEyeView(){ return rightEyeRenderer; } void vtkVuzixARScene::SetLeftEyeSource( vtkImageData* eye ){ this->leftEyeTexture->SetInput( (vtkDataObject*) eye ); leftEyePhysicalWorld = eye; } void vtkVuzixARScene::SetRightEyeSource( vtkImageData* eye ){ this->rightEyeTexture->SetInput( (vtkDataObject*) eye ); rightEyePhysicalWorld = eye; } void vtkVuzixARScene::SetTrackedTransform( vtkTransform* t){ trackedDevice = t; leftEyeCamera->SetUserTransform(t); rightEyeCamera->SetUserTransform(t); } void vtkVuzixARScene::SetLeftEyeTransform( vtkTransform* t){ deviceToLeftEye = t; deviceToLeftEye->Inverse(); //find the focal point of the left camera leftFocalPoint->Identity(); leftFocalPoint->Translate( 0, 0, IdealLeftFocus ); leftFocalPoint->Concatenate( deviceToLeftEye ); //apply the poses to the camera leftEyeCamera->SetPosition( deviceToLeftEye->GetPosition() ); leftEyeCamera->SetFocalPoint( leftFocalPoint->GetPosition() ); leftEyeCamera->OrthogonalizeViewUp(); } void vtkVuzixARScene::SetRightEyeTransform( vtkTransform* t){ deviceToRightEye = t; deviceToRightEye->Inverse(); //find the focal point of the right camera rightFocalPoint->Identity(); rightFocalPoint->Translate( 0, 0, IdealRightFocus ); rightFocalPoint->Concatenate( deviceToRightEye ); //apply the poses to the camera rightEyeCamera->SetPosition( deviceToRightEye->GetPosition() ); rightEyeCamera->SetFocalPoint( rightFocalPoint->GetPosition() ); rightEyeCamera->OrthogonalizeViewUp(); } void vtkVuzixARScene::SetLeftEyePixelwiseIntrinsicParameters( double fx, double fy, double cx, double cy ){ this->leftEyeCamera->SetPixelwiseIntrinsicParameters(fx,fy,cx,cy); IdealLeftFocus = 0.5 * (fx + fy); //find the focal point of the left camera leftFocalPoint->Identity(); leftFocalPoint->Translate( 0, 0, IdealLeftFocus ); leftFocalPoint->Concatenate( deviceToLeftEye ); //apply the poses to the camera leftEyeCamera->SetPosition( deviceToLeftEye->GetPosition() ); leftEyeCamera->SetFocalPoint( leftFocalPoint->GetPosition() ); leftEyeCamera->OrthogonalizeViewUp(); } void vtkVuzixARScene::SetRightEyePixelwiseIntrinsicParameters( double fx, double fy, double cx, double cy ){ this->rightEyeCamera->SetPixelwiseIntrinsicParameters(fx,fy,cx,cy); IdealRightFocus = 0.5 * (fx + fy); //find the focal point of the right camera rightFocalPoint->Identity(); rightFocalPoint->Translate( 0, 0, IdealRightFocus ); rightFocalPoint->Concatenate( deviceToRightEye ); //apply the poses to the camera rightEyeCamera->SetPosition( deviceToRightEye->GetPosition() ); rightEyeCamera->SetFocalPoint( rightFocalPoint->GetPosition() ); rightEyeCamera->OrthogonalizeViewUp(); }<commit_msg>Fixed bad view-up vector. Can't use OrthogonalizeViewUp because it gives faulty vector.<commit_after>#include "vtkVuzixARScene.h" #include "vtkObjectFactory.h" vtkStandardNewMacro(vtkVuzixARScene); vtkVuzixARScene::vtkVuzixARScene(){ //allocates the piece of the compilation leftEyeRenderer = vtkRenderer::New(); rightEyeRenderer = vtkRenderer::New(); leftEyeCamera = vtkVuzixARCamera::New(); leftEyeRenderer->SetActiveCamera(leftEyeCamera); rightEyeCamera = vtkVuzixARCamera::New(); rightEyeRenderer->SetActiveCamera(rightEyeCamera); //allocate the texture bases for the renderers and link them together leftEyePhysicalWorld = 0; leftEyeTexture = vtkTexture::New(); leftEyeRenderer->SetBackgroundTexture( leftEyeTexture ); leftEyeRenderer->SetTexturedBackground( true ); rightEyePhysicalWorld = 0; rightEyeTexture = vtkTexture::New(); rightEyeRenderer->SetBackgroundTexture( rightEyeTexture ); rightEyeRenderer->SetTexturedBackground( true ); //set some defaults for the poses trackedDevice = vtkTransform::New(); trackedDevice->Identity(); deviceToLeftEye = vtkTransform::New(); deviceToLeftEye->Identity(); deviceToRightEye = vtkTransform::New(); deviceToRightEye->Identity(); //allocate space for the temporary variables leftFocalPoint = vtkTransform::New(); leftFocalPoint->PostMultiply(); rightFocalPoint = vtkTransform::New(); rightFocalPoint->PostMultiply(); //give default values to the focal parameters IdealLeftFocus = 1.0; IdealRightFocus = 1.0; } vtkVuzixARScene::~vtkVuzixARScene(){ leftEyeTexture->Delete(); rightEyeTexture->Delete(); leftEyeRenderer->Delete(); rightEyeRenderer->Delete(); leftEyeCamera->Delete(); rightEyeCamera->Delete(); leftFocalPoint->Delete(); rightFocalPoint->Delete(); deviceToLeftEye->Delete(); deviceToRightEye->Delete(); } void vtkVuzixARScene::Update(){ //update the frame sizes UpdateFrameSizes(); //tell the cameras that they have been modified leftEyeCamera->Modified(); rightEyeCamera->Modified(); } //update the frame sizes on the cameras (used for determining the projection matrix) void vtkVuzixARScene::UpdateFrameSizes(){ if( leftEyePhysicalWorld ){ int extent[6]; this->leftEyePhysicalWorld->GetExtent( extent ); this->leftEyeCamera->SetFrameSize( (double) (extent[1] - extent[0]+1), (double) (extent[3] - extent[2]+1) ); } if( rightEyePhysicalWorld ){ int extent[6]; this->rightEyePhysicalWorld->GetExtent( extent ); this->rightEyeCamera->SetFrameSize( (double) (extent[1] - extent[0]+1), (double) (extent[3] - extent[2]+1) ); } } vtkRenderer* vtkVuzixARScene::GetLeftEyeView(){ return leftEyeRenderer; } vtkRenderer* vtkVuzixARScene::GetRightEyeView(){ return rightEyeRenderer; } void vtkVuzixARScene::SetLeftEyeSource( vtkImageData* eye ){ this->leftEyeTexture->SetInput( (vtkDataObject*) eye ); leftEyePhysicalWorld = eye; } void vtkVuzixARScene::SetRightEyeSource( vtkImageData* eye ){ this->rightEyeTexture->SetInput( (vtkDataObject*) eye ); rightEyePhysicalWorld = eye; } void vtkVuzixARScene::SetTrackedTransform( vtkTransform* t){ trackedDevice = t; leftEyeCamera->SetUserTransform(t); rightEyeCamera->SetUserTransform(t); } void vtkVuzixARScene::SetLeftEyeTransform( vtkTransform* t){ deviceToLeftEye = t; deviceToLeftEye->Inverse(); //find the focal point of the left camera leftFocalPoint->Identity(); leftFocalPoint->Translate( 0, 0, IdealLeftFocus ); leftFocalPoint->Concatenate( deviceToLeftEye ); //find the viewUp vector and position of the left camera double* leftViewUp = deviceToLeftEye->TransformDoublePoint(0,-1,0); double leftPosition[3]; deviceToLeftEye->GetPosition(leftPosition); leftViewUp[0] -= leftPosition[0]; leftViewUp[1] -= leftPosition[1]; leftViewUp[2] -= leftPosition[2]; //apply the poses to the camera leftEyeCamera->SetPosition( leftPosition ); leftEyeCamera->SetViewUp( leftViewUp ); leftEyeCamera->SetFocalPoint( leftFocalPoint->GetPosition() ); } void vtkVuzixARScene::SetRightEyeTransform( vtkTransform* t){ deviceToRightEye = t; deviceToRightEye->Inverse(); //find the focal point of the right camera rightFocalPoint->Identity(); rightFocalPoint->Translate( 0, 0, IdealRightFocus ); rightFocalPoint->Concatenate( deviceToRightEye ); //find the viewUp vector and position of the right camera double* rightViewUp = deviceToRightEye->TransformDoublePoint(0,-1,0); double rightPosition[3]; deviceToRightEye->GetPosition(rightPosition); rightViewUp[0] -= rightPosition[0]; rightViewUp[1] -= rightPosition[1]; rightViewUp[2] -= rightPosition[2]; //apply the poses to the camera rightEyeCamera->SetPosition( rightPosition ); rightEyeCamera->SetViewUp( rightViewUp ); rightEyeCamera->SetFocalPoint( rightFocalPoint->GetPosition() ); } void vtkVuzixARScene::SetLeftEyePixelwiseIntrinsicParameters( double fx, double fy, double cx, double cy ){ this->leftEyeCamera->SetPixelwiseIntrinsicParameters(fx,fy,cx,cy); IdealLeftFocus = 0.5 * (fx+fy); //find the focal point of the left camera leftFocalPoint->Identity(); leftFocalPoint->Translate( 0, 0, IdealLeftFocus ); leftFocalPoint->Concatenate( deviceToLeftEye ); //find the viewUp vector and position of the left camera double* leftViewUp = deviceToLeftEye->TransformDoublePoint(0,-1,0); double leftPosition[3]; deviceToLeftEye->GetPosition(leftPosition); leftViewUp[0] -= leftPosition[0]; leftViewUp[1] -= leftPosition[1]; leftViewUp[2] -= leftPosition[2]; //apply the poses to the camera leftEyeCamera->SetPosition( leftPosition ); leftEyeCamera->SetViewUp( leftViewUp ); leftEyeCamera->SetFocalPoint( leftFocalPoint->GetPosition() ); } void vtkVuzixARScene::SetRightEyePixelwiseIntrinsicParameters( double fx, double fy, double cx, double cy ){ this->rightEyeCamera->SetPixelwiseIntrinsicParameters(fx,fy,cx,cy); IdealRightFocus = 0.5 * (fx+fy); //find the focal point of the right camera rightFocalPoint->Identity(); rightFocalPoint->Translate( 0, 0, IdealRightFocus ); rightFocalPoint->Concatenate( deviceToRightEye ); //find the viewUp vector and position of the right camera double* rightViewUp = deviceToRightEye->TransformDoublePoint(0,-1,0); double rightPosition[3]; deviceToRightEye->GetPosition(rightPosition); rightViewUp[0] -= rightPosition[0]; rightViewUp[1] -= rightPosition[1]; rightViewUp[2] -= rightPosition[2]; //apply the poses to the camera rightEyeCamera->SetPosition( rightPosition ); rightEyeCamera->SetViewUp( rightViewUp ); rightEyeCamera->SetFocalPoint( rightFocalPoint->GetPosition() ); }<|endoftext|>
<commit_before>/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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 "request_handler.h" #include <vector> #include <sstream> namespace wireless_android_play_analytics { void RequestHandler::GetLastRefreshed(const Pistache::Rest::Request& request, Pistache::Http::ResponseWriter response) { // Information within the request is unnecessary. UNUSED(request); response.send(Pistache::Http::Code::Ok, "Wed May 19 15:46:11 2020"); } void RequestHandler::GetDashboard(const Pistache::Rest::Request& request, Pistache::Http::ResponseWriter response) { // TODO(alexanderlin): Use real data once I get access to them. std::vector<std::string> dataSources {"SPAM", "PLAY_COUNTRY", "APP_COUNTRY_PUBLISH_TIME", "QUERY_CATEGORY_SOURCE", "UNIFIED_USER_DATA_SOURCE"}; std::vector<std::string> dates {"5/19/2020", "5/18/2020", "5/17/2020", "5/16/2020", "5/15/2020", "5/14/2020", "5/13/2020"}; std::string system_in = request.param(":system").as<std::string>(); std::string status = "111010111110001011100100111000100110001010000010100111010"; auto stream = response.stream(Pistache::Http::Code::Ok); const char* system = system_in.c_str(); // track the online or offline bits int i = 0; // Since the html file may be large, stream the data as we write it for // more efficiency stream << "<table id=\"" << system << "%TEXT\">\n"; stream << "\t<br/>\n\t<p>" << system << "</p>\n"; for(const std::string &data : dataSources) { stream << "\t<tr>\n"; stream << "\t\t<td>" << data.c_str() << "&nbsp&nbsp</td>\n"; for(const std::string& date : dates) { stream << "\t\t<td class="; if (status[i++] == '1') { stream << "\"online\""; } else { stream << "\"offline\""; } stream << " title=\"" << date.c_str() << "\" id=\"" << data.c_str() << "%" << date.c_str() << "%" << system << "\"></td>\n"; } stream << "\t</tr>\n\n"; } stream << "</table>\n"; stream.ends(); } void RequestHandler::PopulateBackfillCommand (const Pistache::Rest::Request& request, Pistache::Http::ResponseWriter response) { std::string date = request.param(":date").as<std::string>(); std::string system = request.param(":system").as<std::string>(); std::string source = request.param(":source").as<std::string>(); std::string command = "sample command to run backfill for " + source + " on " + system + " for " + date; response.send(Pistache::Http::Code::Ok, command); } } // namespace wireless_android_play_analytics<commit_msg>changed what the server sends<commit_after>/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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 "request_handler.h" #include <vector> #include <sstream> namespace wireless_android_play_analytics { void RequestHandler::GetLastRefreshed(const Pistache::Rest::Request& request, Pistache::Http::ResponseWriter response) { // Information within the request is unnecessary. UNUSED(request); response.send(Pistache::Http::Code::Ok, "Wed May 19 15:46:11 2020"); } void RequestHandler::GetDashboard(const Pistache::Rest::Request& request, Pistache::Http::ResponseWriter response) { // TODO(alexanderlin): Use real data once I get access to them. std::vector<std::string> dataSources {"SPAM", "PLAY_COUNTRY", "APP_COUNTRY_PUBLISH_TIME", "QUERY_CATEGORY_SOURCE", "UNIFIED_USER_DATA_SOURCE"}; std::vector<std::string> dates {"5/19/2020", "5/18/2020", "5/17/2020", "5/16/2020", "5/15/2020", "5/14/2020", "5/13/2020"}; std::string system_in = request.param(":system").as<std::string>(); std::string status = "111010111110001011100100111000100110001010000010100111010"; response.send(Pistache::Http::Code::Ok, "{\"message\": \"Hello World\"}"); } void RequestHandler::PopulateBackfillCommand (const Pistache::Rest::Request& request, Pistache::Http::ResponseWriter response) { std::string date = request.param(":date").as<std::string>(); std::string system = request.param(":system").as<std::string>(); std::string source = request.param(":source").as<std::string>(); std::string command = "sample command to run backfill for " + source + " on " + system + " for " + date; response.send(Pistache::Http::Code::Ok, command); } } // namespace wireless_android_play_analytics<|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkImageDataStreamer.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkImageDataStreamer.h" #include "vtkCommand.h" #include "vtkExtentTranslator.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkImageDataStreamer, "1.27"); vtkStandardNewMacro(vtkImageDataStreamer); vtkCxxSetObjectMacro(vtkImageDataStreamer,ExtentTranslator,vtkExtentTranslator); //---------------------------------------------------------------------------- vtkImageDataStreamer::vtkImageDataStreamer() { // default to 10 divisions this->NumberOfStreamDivisions = 10; // create default translator this->ExtentTranslator = vtkExtentTranslator::New(); } vtkImageDataStreamer::~vtkImageDataStreamer() { if (this->ExtentTranslator) { this->ExtentTranslator->Delete(); } } //---------------------------------------------------------------------------- void vtkImageDataStreamer::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "NumberOfStreamDivisions: " << this->NumberOfStreamDivisions << endl; if ( this->ExtentTranslator ) { os << indent << "ExtentTranslator:\n"; this->ExtentTranslator->PrintSelf(os,indent.GetNextIndent()); } else { os << indent << "ExtentTranslator: (none)\n"; } } //---------------------------------------------------------------------------- void vtkImageDataStreamer::UpdateData(vtkDataObject *vtkNotUsed(out)) { int idx; vtkImageData *input = this->GetInput(); vtkImageData *output = this->GetOutput(); int piece; // prevent chasing our tail if (this->Updating) { return; } // Propagate the update call - make sure everything we // might rely on is up-to-date // Must call PropagateUpdateExtent before UpdateData if multiple // inputs since they may lead back to the same data object. this->Updating = 1; if (!input || !output) { vtkWarningMacro("ImageDataStreamer Requires an input to execute!"); return; } // Initialize all the outputs vtkExtentTranslator *translator = this->GetExtentTranslator(); output->PrepareForNewData(); // If there is a start method, call it this->AbortExecute = 0; this->Progress = 0.0; this->InvokeEvent(vtkCommand::StartEvent,NULL); output->SetExtent(output->GetUpdateExtent()); output->AllocateScalars(); // now start the loop over the number of pieces translator->SetWholeExtent(output->GetUpdateExtent()); translator->SetNumberOfPieces(this->NumberOfStreamDivisions); for (piece = 0; piece < this->NumberOfStreamDivisions && !this->AbortExecute; piece++) { translator->SetPiece(piece); if (translator->PieceToExtentByPoints()) { input->SetUpdateExtent(translator->GetExtent()); input->PropagateUpdateExtent(); input->UpdateData(); // copy the resulting data into the output buffer output->CopyAndCastFrom(input, translator->GetExtent()); this->UpdateProgress((float)piece/(this->NumberOfStreamDivisions - 1.0)); } } this->Updating = 0; // If we ended due to aborting, push the progress up to 1.0 (since // it probably didn't end there) if ( !this->AbortExecute ) { this->UpdateProgress(1.0); } // Call the end method, if there is one this->InvokeEvent(vtkCommand::EndEvent,NULL); // Now we have to mark the data as up to data. for (idx = 0; idx < this->NumberOfOutputs; ++idx) { if (this->Outputs[idx]) { this->Outputs[idx]->DataHasBeenGenerated(); } } // Release any inputs if marked for release for (idx = 0; idx < this->NumberOfInputs; ++idx) { if (this->Inputs[idx] != NULL) { if ( this->Inputs[idx]->ShouldIReleaseData() ) { this->Inputs[idx]->ReleaseData(); } } } // Information gets invalidated as soon as Update is called, // so validate it again here. this->InformationTime.Modified(); } <commit_msg>ERR: was not passing through data other than scalars.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkImageDataStreamer.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkImageDataStreamer.h" #include "vtkCommand.h" #include "vtkExtentTranslator.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkImageDataStreamer, "1.28"); vtkStandardNewMacro(vtkImageDataStreamer); vtkCxxSetObjectMacro(vtkImageDataStreamer,ExtentTranslator,vtkExtentTranslator); //---------------------------------------------------------------------------- vtkImageDataStreamer::vtkImageDataStreamer() { // default to 10 divisions this->NumberOfStreamDivisions = 10; // create default translator this->ExtentTranslator = vtkExtentTranslator::New(); } vtkImageDataStreamer::~vtkImageDataStreamer() { if (this->ExtentTranslator) { this->ExtentTranslator->Delete(); } } //---------------------------------------------------------------------------- void vtkImageDataStreamer::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "NumberOfStreamDivisions: " << this->NumberOfStreamDivisions << endl; if ( this->ExtentTranslator ) { os << indent << "ExtentTranslator:\n"; this->ExtentTranslator->PrintSelf(os,indent.GetNextIndent()); } else { os << indent << "ExtentTranslator: (none)\n"; } } //---------------------------------------------------------------------------- void vtkImageDataStreamer::UpdateData(vtkDataObject *vtkNotUsed(out)) { int idx; vtkImageData *input = this->GetInput(); vtkImageData *output = this->GetOutput(); int piece; // prevent chasing our tail if (this->Updating) { return; } // Propagate the update call - make sure everything we // might rely on is up-to-date // Must call PropagateUpdateExtent before UpdateData if multiple // inputs since they may lead back to the same data object. this->Updating = 1; if (!input || !output) { vtkWarningMacro("ImageDataStreamer Requires an input to execute!"); return; } // Initialize all the outputs vtkExtentTranslator *translator = this->GetExtentTranslator(); output->PrepareForNewData(); // If there is a start method, call it this->AbortExecute = 0; this->Progress = 0.0; this->InvokeEvent(vtkCommand::StartEvent,NULL); output->SetExtent(output->GetUpdateExtent()); //output->AllocateScalars(); AllocateOutputData(output); // now start the loop over the number of pieces translator->SetWholeExtent(output->GetUpdateExtent()); translator->SetNumberOfPieces(this->NumberOfStreamDivisions); for (piece = 0; piece < this->NumberOfStreamDivisions && !this->AbortExecute; piece++) { translator->SetPiece(piece); if (translator->PieceToExtentByPoints()) { input->SetUpdateExtent(translator->GetExtent()); input->PropagateUpdateExtent(); input->UpdateData(); // copy the resulting data into the output buffer output->CopyAndCastFrom(input, translator->GetExtent()); this->UpdateProgress((float)piece/(this->NumberOfStreamDivisions - 1.0)); } } this->Updating = 0; // If we ended due to aborting, push the progress up to 1.0 (since // it probably didn't end there) if ( !this->AbortExecute ) { this->UpdateProgress(1.0); } // Call the end method, if there is one this->InvokeEvent(vtkCommand::EndEvent,NULL); // Now we have to mark the data as up to data. for (idx = 0; idx < this->NumberOfOutputs; ++idx) { if (this->Outputs[idx]) { this->Outputs[idx]->DataHasBeenGenerated(); } } // Release any inputs if marked for release for (idx = 0; idx < this->NumberOfInputs; ++idx) { if (this->Inputs[idx] != NULL) { if ( this->Inputs[idx]->ShouldIReleaseData() ) { this->Inputs[idx]->ReleaseData(); } } } // Information gets invalidated as soon as Update is called, // so validate it again here. this->InformationTime.Modified(); } <|endoftext|>
<commit_before>#include "boost/python.hpp" #include "boost/python/extract.hpp" #include "boost/python/numeric.hpp" // See http://docs.scipy.org/doc/numpy-dev/reference/c-api.deprecations.html //#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // See http://docs.scipy.org/doc/numpy/reference/c-api.array.html#miscellaneous #define PY_ARRAY_UNIQUE_SYMBOL bashes_ARRAY_API #define NO_IMPORT_ARRAY #include "numpy/arrayobject.h" #include <iostream> namespace bp = boost::python; namespace bpn = boost::python::numeric; namespace bashes { namespace { // Example using only boost::python::numeric::array void printFirst(bpn::array data) { // Access a built-in type (an array) bpn::array a = data; // Need to <extract> array elements because their type is unknown std::cout << "First array item: " << bp::extract<int>(a[0]) << std::endl; }; // Example using numpy c-api constructs // see http://stackoverflow.com/questions/9128519/reading-many-values-from-numpy-c-api bp::object timesTwo(bpn::array m){ // access underlying numpy PyObject pointer of input array PyObject* m_obj = PyArray_FROM_OTF(m.ptr(), NPY_DOUBLE, NPY_IN_ARRAY); // to avoid memory leaks, let a Boost::Python object manage the array bp::object temp((bp::handle<>(m_obj))); // number of array dimensions int ndim = PyArray_NDIM(m_obj); std::cout << "bashes::timesTwo: ndim of input array: " << ndim << std::endl; // get direct access to the array data const double* data = static_cast<const double*>(PyArray_DATA(m_obj)); // make the output array, and get access to its data PyObject* res = PyArray_SimpleNew(ndim, PyArray_DIMS(m_obj), NPY_DOUBLE); // access output array data double* res_data = static_cast<double*>(PyArray_DATA(res)); // number of elements in array const unsigned size = PyArray_SIZE(m_obj); std::cout << "bashes::timesTwo: size of input array: " << size << std::endl; // times by two for (unsigned i = 0; i < size; ++i) { res_data[i] = 2*data[i]; } // go back to using Boost::Python constructs return bp::object((bp::handle<>(res))); }; } // anonymous void pyExportEstimatorHelpers() { bp::def("printFirst", &printFirst); bp::def("timesTwo", &timesTwo); } } // bashes<commit_msg>expand bpn namespace abbreviation<commit_after>#include "boost/python.hpp" #include "boost/python/extract.hpp" #include "boost/python/numeric.hpp" // See http://docs.scipy.org/doc/numpy-dev/reference/c-api.deprecations.html //#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // See http://docs.scipy.org/doc/numpy/reference/c-api.array.html#miscellaneous #define PY_ARRAY_UNIQUE_SYMBOL bashes_ARRAY_API #define NO_IMPORT_ARRAY #include "numpy/arrayobject.h" #include <iostream> namespace bp = boost::python; namespace bashes { namespace { // Example using only boost::python::numeric::array void printFirst(bp::numeric::array data) { // Access a built-in type (an array) bp::numeric::array a = data; // Need to <extract> array elements because their type is unknown std::cout << "First array item: " << bp::extract<int>(a[0]) << std::endl; }; // Example using numpy c-api constructs // see http://stackoverflow.com/questions/9128519/reading-many-values-from-numpy-c-api bp::object timesTwo(bp::numeric::array m){ // access underlying numpy PyObject pointer of input array PyObject* m_obj = PyArray_FROM_OTF(m.ptr(), NPY_DOUBLE, NPY_IN_ARRAY); // to avoid memory leaks, let a Boost::Python object manage the array bp::object temp((bp::handle<>(m_obj))); // number of array dimensions int ndim = PyArray_NDIM(m_obj); std::cout << "bashes::timesTwo: ndim of input array: " << ndim << std::endl; // get direct access to the array data const double* data = static_cast<const double*>(PyArray_DATA(m_obj)); // make the output array, and get access to its data PyObject* res = PyArray_SimpleNew(ndim, PyArray_DIMS(m_obj), NPY_DOUBLE); // access output array data double* res_data = static_cast<double*>(PyArray_DATA(res)); // number of elements in array const unsigned size = PyArray_SIZE(m_obj); std::cout << "bashes::timesTwo: size of input array: " << size << std::endl; // times by two for (unsigned i = 0; i < size; ++i) { res_data[i] = 2*data[i]; } // go back to using Boost::Python constructs return bp::object((bp::handle<>(res))); }; } // anonymous void pyExportEstimatorHelpers() { bp::numeric::array::set_module_and_type("numpy", "ndarray"); bp::def("printFirst", &printFirst); bp::def("timesTwo", &timesTwo); } } // bashes<|endoftext|>
<commit_before>#include <sstream> #include "PyNumber.hh" using namespace py; using std::unique_ptr; //------------------------------------------------------------------------------ namespace { ref<Unicode> tp_repr(PyNumber* self) { auto const& args = self->fmt_->get_args(); std::stringstream ss; ss << "String(" << args.size << ", " << args.precision << ", pad='" << args.pad << "', sign='" << args.sign << ", nan='" << args.nan << "', inf='" << args.inf << "', point='" << args.point << "', bad='" << args.bad << "')"; return Unicode::from(ss.str()); } int get_precision( Object* arg) { int precision; if (arg == Py_None) precision = fixfmt::Number::PRECISION_NONE; else { precision = arg->long_value(); if (precision < 0) precision = fixfmt::Number::PRECISION_NONE; } return precision; } fixfmt::Number::Scale get_scale( Object* arg) { fixfmt::Number::Scale scale = {}; auto const aliases = ((Object*) &PyNumber::type_)->GetAttrString("SCALES"); if (Dict::Check(aliases)) { auto const alias = cast<Dict>(aliases)->GetItem(arg, false); if (alias != nullptr) arg = alias; } if (arg == Py_None) ; // accept default else if (!Sequence::Check(arg)) throw ValueError("scale must be a two-item sequence"); else { Sequence* scale_seq = cast<Sequence>(arg); if (scale_seq->Length() != 2) throw ValueError("scale must be a two-item sequence"); scale.factor = scale_seq->GetItem(0)->double_value(); if (!(scale.factor > 0)) throw ValueError("invalid scale factor"); scale.suffix = scale_seq->GetItem(1)->Str()->as_utf8_string(); } return scale; } // FIXME: Accept sign=None. static void tp_init( PyNumber* self, Tuple* args, Dict* kw_args) { static char const* arg_names[] = { "size", "precision", "pad", "sign", "nan", "inf", "point", "bad", "scale", nullptr }; int size; Object* precision_arg = (Object*) Py_None; #if PY3K int pad = fixfmt::Number::PAD_SPACE; int sign = fixfmt::Number::SIGN_NEGATIVE; int point = '.'; int bad = '#'; #else char pad = fixfmt::Number::PAD_SPACE; char sign = fixfmt::Number::SIGN_NEGATIVE; char point = '.'; char bad = '#'; #endif char const* nan = "NaN"; char const* inf = "inf"; Object* scale_arg = (Object*) Py_None; Arg::ParseTupleAndKeywords( args, kw_args, #if PY3K "i|O$CCetetCCO", #else "i|OccetetccO", #endif arg_names, &size, &precision_arg, &pad, &sign, "utf-8", &nan, "utf-8", &inf, &point, &bad, &scale_arg); if (size < 0) throw ValueError("negative size"); auto const precision = get_precision(precision_arg); if ( sign != fixfmt::Number::SIGN_NONE && sign != fixfmt::Number::SIGN_NEGATIVE && sign != fixfmt::Number::SIGN_ALWAYS) throw ValueError("invalid sign"); if (! (pad == fixfmt::Number::PAD_SPACE || pad == fixfmt::Number::PAD_ZERO)) throw ValueError("invalid pad"); auto const scale = get_scale(scale_arg); new(self) PyNumber; self->fmt_ = std::make_unique<fixfmt::Number>( fixfmt::Number::Args{ size, precision, (char) pad, (char) sign, scale, (char) point, (char) bad, nan, inf}); } ref<Object> tp_call(PyNumber* self, Tuple* args, Dict* kw_args) { static char const* arg_names[] = {"value", nullptr}; double val; // FIXME: Handle integer types separately. Arg::ParseTupleAndKeywords(args, kw_args, "d", arg_names, &val); return Unicode::from((*self->fmt_)(val)); } auto methods = Methods<PyNumber>() ; ref<Object> get_bad(PyNumber* const self, void* /* closure */) { return Unicode::from(self->fmt_->get_args().bad); } void set_bad(PyNumber* const self, Object* val, void* /* closure */) { auto const bad_str = val->Str(); if (bad_str->Length() != 1) throw ValueError("invalid bad"); auto args = self->fmt_->get_args(); // FIXME: Wrong for multibyte characters. args.bad = bad_str->as_utf8_string()[0]; self->fmt_->set_args(args); } ref<Object> get_inf(PyNumber* const self, void* /* closure */) { return Unicode::from(self->fmt_->get_args().inf); } void set_inf(PyNumber* const self, Object* val, void* /* closure */) { auto args = self->fmt_->get_args(); args.inf = val->Str()->as_utf8_string().c_str(); self->fmt_->set_args(args); } ref<Object> get_nan(PyNumber* const self, void* /* closure */) { return Unicode::from(self->fmt_->get_args().nan); } void set_nan(PyNumber* const self, Object* val, void* /* closure */) { auto args = self->fmt_->get_args(); args.nan = val->Str()->as_utf8_string().c_str(); self->fmt_->set_args(args); } ref<Object> get_pad(PyNumber* const self, void* /* closure */) { return Unicode::from(self->fmt_->get_args().pad); } void set_pad(PyNumber* const self, Object* val, void* /* closure */) { auto const pad_str = val->Str(); if (pad_str->Length() != 1) throw ValueError("invalid pad"); // FIXME: Wrong for multibyte characters. auto const pad = pad_str->as_utf8_string()[0]; if ( pad != fixfmt::Number::PAD_SPACE && pad != fixfmt::Number::PAD_ZERO) throw ValueError("invalid pad"); auto args = self->fmt_->get_args(); args.pad = pad; self->fmt_->set_args(args); } ref<Object> get_point(PyNumber* const self, void* /* closure */) { return Unicode::from(self->fmt_->get_args().point); } void set_point(PyNumber* const self, Object* val, void* /* closure */) { auto const point_str = val->Str(); if (point_str->Length() != 1) throw ValueError("invalid point"); auto args = self->fmt_->get_args(); // FIXME: Wrong for multibyte characters. args.point = point_str->as_utf8_string()[0]; self->fmt_->set_args(args); } ref<Object> get_precision(PyNumber* const self, void* /* closure */) { int const precision = self->fmt_->get_args().precision; return precision == fixfmt::Number::PRECISION_NONE ? none_ref() : (ref<Object>) Long::FromLong(precision); } void set_precision(PyNumber* const self, Object* val, void* /* closure */) { auto args = self->fmt_->get_args(); args.precision = get_precision(val); self->fmt_->set_args(args); } ref<Object> get_scale( PyNumber* const self, void* /* closure */) { auto const& scale = self->fmt_->get_args().scale; if (scale.enabled()) return Tuple::builder << Float::from(scale.factor) << Unicode::from(scale.suffix); else return none_ref(); } void set_scale(PyNumber* const self, Object* val, void* /* closure */) { auto args = self->fmt_->get_args(); args.scale = get_scale(val); self->fmt_->set_args(args); } ref<Object> get_sign(PyNumber* const self, void* /* closure */) { return Unicode::from(self->fmt_->get_args().sign); } void set_sign(PyNumber* const self, Object* const val, void* /* closure */) { auto const sign_str = val->Str(); if (sign_str->Length() != 1) throw ValueError("invalid sign"); auto const sign = sign_str->as_utf8_string()[0]; if ( sign != fixfmt::Number::SIGN_NONE && sign != fixfmt::Number::SIGN_NEGATIVE && sign != fixfmt::Number::SIGN_ALWAYS) throw ValueError("invalid sign"); auto args = self->fmt_->get_args(); args.sign = sign; self->fmt_->set_args(args); } ref<Object> get_size(PyNumber* const self, void* /* closure */) { return Long::FromLong(self->fmt_->get_args().size); } void set_size(PyNumber* const self, Object* val, void* /* closure */) { auto const size = val->long_value(); if (size < 0) throw ValueError("size out of range"); auto args = self->fmt_->get_args(); args.size = size; self->fmt_->set_args(args); } ref<Object> get_width(PyNumber* const self, void* /* closure */) { return Long::FromLong(self->fmt_->get_width()); } auto getsets = GetSets<PyNumber>() .add_getset<get_bad , set_bad >("bad") .add_getset<get_inf , set_inf >("inf") .add_getset<get_nan , set_nan >("nan") .add_getset<get_pad , set_pad >("pad") .add_getset<get_point , set_point >("point") .add_getset<get_precision , set_precision >("precision") .add_getset<get_scale , set_scale >("scale") .add_getset<get_sign , set_sign >("sign") .add_getset<get_size , set_size >("size") .add_get<get_width> ("width") ; } // anonymous namespace Type PyNumber::type_ = PyTypeObject{ PyVarObject_HEAD_INIT(nullptr, 0) (char const*) "fixfmt._ext.Number", // tp_name (Py_ssize_t) sizeof(PyNumber), // tp_basicsize (Py_ssize_t) 0, // tp_itemsize (destructor) nullptr, // tp_dealloc (printfunc) nullptr, // tp_print (getattrfunc) nullptr, // tp_getattr (setattrfunc) nullptr, // tp_setattr #if PY3K (PyAsyncMethods*) nullptr, // tp_as_async #else (cmpfunc) nullptr, // tp_compare #endif (reprfunc) wrap<PyNumber, tp_repr>, // tp_repr (PyNumberMethods*) nullptr, // tp_as_number (PySequenceMethods*) nullptr, // tp_as_sequence (PyMappingMethods*) nullptr, // tp_as_mapping (hashfunc) nullptr, // tp_hash (ternaryfunc) wrap<PyNumber, tp_call>, // tp_call (reprfunc) nullptr, // tp_str (getattrofunc) nullptr, // tp_getattro (setattrofunc) nullptr, // tp_setattro (PyBufferProcs*) nullptr, // tp_as_buffer (unsigned long) Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags (char const*) nullptr, // tp_doc (traverseproc) nullptr, // tp_traverse (inquiry) nullptr, // tp_clear (richcmpfunc) nullptr, // tp_richcompare (Py_ssize_t) 0, // tp_weaklistoffset (getiterfunc) nullptr, // tp_iter (iternextfunc) nullptr, // tp_iternext (PyMethodDef*) methods, // tp_methods (PyMemberDef*) nullptr, // tp_members (PyGetSetDef*) getsets, // tp_getset (_typeobject*) nullptr, // tp_base (PyObject*) nullptr, // tp_dict (descrgetfunc) nullptr, // tp_descr_get (descrsetfunc) nullptr, // tp_descr_set (Py_ssize_t) 0, // tp_dictoffset (initproc) wrap<PyNumber, tp_init>, // tp_init (allocfunc) nullptr, // tp_alloc (newfunc) PyType_GenericNew, // tp_new (freefunc) nullptr, // tp_free (inquiry) nullptr, // tp_is_gc (PyObject*) nullptr, // tp_bases (PyObject*) nullptr, // tp_mro (PyObject*) nullptr, // tp_cache (PyObject*) nullptr, // tp_subclasses (PyObject*) nullptr, // tp_weaklist (destructor) nullptr, // tp_del (unsigned int) 0, // tp_version_tag #if PY3K (destructor) nullptr, // tp_finalize #endif }; <commit_msg>Fix repr.<commit_after>#include <sstream> #include "PyNumber.hh" using namespace py; using std::unique_ptr; //------------------------------------------------------------------------------ namespace { ref<Unicode> tp_repr(PyNumber* self) { auto const& args = self->fmt_->get_args(); std::stringstream ss; ss << "Number(" << args.size << ", " << args.precision << ", pad='" << args.pad << "', sign='" << args.sign << ", nan='" << args.nan << "', inf='" << args.inf << "', point='" << args.point << "', bad='" << args.bad << "')"; return Unicode::from(ss.str()); } int get_precision( Object* arg) { int precision; if (arg == Py_None) precision = fixfmt::Number::PRECISION_NONE; else { precision = arg->long_value(); if (precision < 0) precision = fixfmt::Number::PRECISION_NONE; } return precision; } fixfmt::Number::Scale get_scale( Object* arg) { fixfmt::Number::Scale scale = {}; auto const aliases = ((Object*) &PyNumber::type_)->GetAttrString("SCALES"); if (Dict::Check(aliases)) { auto const alias = cast<Dict>(aliases)->GetItem(arg, false); if (alias != nullptr) arg = alias; } if (arg == Py_None) ; // accept default else if (!Sequence::Check(arg)) throw ValueError("scale must be a two-item sequence"); else { Sequence* scale_seq = cast<Sequence>(arg); if (scale_seq->Length() != 2) throw ValueError("scale must be a two-item sequence"); scale.factor = scale_seq->GetItem(0)->double_value(); if (!(scale.factor > 0)) throw ValueError("invalid scale factor"); scale.suffix = scale_seq->GetItem(1)->Str()->as_utf8_string(); } return scale; } // FIXME: Accept sign=None. static void tp_init( PyNumber* self, Tuple* args, Dict* kw_args) { static char const* arg_names[] = { "size", "precision", "pad", "sign", "nan", "inf", "point", "bad", "scale", nullptr }; int size; Object* precision_arg = (Object*) Py_None; #if PY3K int pad = fixfmt::Number::PAD_SPACE; int sign = fixfmt::Number::SIGN_NEGATIVE; int point = '.'; int bad = '#'; #else char pad = fixfmt::Number::PAD_SPACE; char sign = fixfmt::Number::SIGN_NEGATIVE; char point = '.'; char bad = '#'; #endif char const* nan = "NaN"; char const* inf = "inf"; Object* scale_arg = (Object*) Py_None; Arg::ParseTupleAndKeywords( args, kw_args, #if PY3K "i|O$CCetetCCO", #else "i|OccetetccO", #endif arg_names, &size, &precision_arg, &pad, &sign, "utf-8", &nan, "utf-8", &inf, &point, &bad, &scale_arg); if (size < 0) throw ValueError("negative size"); auto const precision = get_precision(precision_arg); if ( sign != fixfmt::Number::SIGN_NONE && sign != fixfmt::Number::SIGN_NEGATIVE && sign != fixfmt::Number::SIGN_ALWAYS) throw ValueError("invalid sign"); if (! (pad == fixfmt::Number::PAD_SPACE || pad == fixfmt::Number::PAD_ZERO)) throw ValueError("invalid pad"); auto const scale = get_scale(scale_arg); new(self) PyNumber; self->fmt_ = std::make_unique<fixfmt::Number>( fixfmt::Number::Args{ size, precision, (char) pad, (char) sign, scale, (char) point, (char) bad, nan, inf}); } ref<Object> tp_call(PyNumber* self, Tuple* args, Dict* kw_args) { static char const* arg_names[] = {"value", nullptr}; double val; // FIXME: Handle integer types separately. Arg::ParseTupleAndKeywords(args, kw_args, "d", arg_names, &val); return Unicode::from((*self->fmt_)(val)); } auto methods = Methods<PyNumber>() ; ref<Object> get_bad(PyNumber* const self, void* /* closure */) { return Unicode::from(self->fmt_->get_args().bad); } void set_bad(PyNumber* const self, Object* val, void* /* closure */) { auto const bad_str = val->Str(); if (bad_str->Length() != 1) throw ValueError("invalid bad"); auto args = self->fmt_->get_args(); // FIXME: Wrong for multibyte characters. args.bad = bad_str->as_utf8_string()[0]; self->fmt_->set_args(args); } ref<Object> get_inf(PyNumber* const self, void* /* closure */) { return Unicode::from(self->fmt_->get_args().inf); } void set_inf(PyNumber* const self, Object* val, void* /* closure */) { auto args = self->fmt_->get_args(); args.inf = val->Str()->as_utf8_string().c_str(); self->fmt_->set_args(args); } ref<Object> get_nan(PyNumber* const self, void* /* closure */) { return Unicode::from(self->fmt_->get_args().nan); } void set_nan(PyNumber* const self, Object* val, void* /* closure */) { auto args = self->fmt_->get_args(); args.nan = val->Str()->as_utf8_string().c_str(); self->fmt_->set_args(args); } ref<Object> get_pad(PyNumber* const self, void* /* closure */) { return Unicode::from(self->fmt_->get_args().pad); } void set_pad(PyNumber* const self, Object* val, void* /* closure */) { auto const pad_str = val->Str(); if (pad_str->Length() != 1) throw ValueError("invalid pad"); // FIXME: Wrong for multibyte characters. auto const pad = pad_str->as_utf8_string()[0]; if ( pad != fixfmt::Number::PAD_SPACE && pad != fixfmt::Number::PAD_ZERO) throw ValueError("invalid pad"); auto args = self->fmt_->get_args(); args.pad = pad; self->fmt_->set_args(args); } ref<Object> get_point(PyNumber* const self, void* /* closure */) { return Unicode::from(self->fmt_->get_args().point); } void set_point(PyNumber* const self, Object* val, void* /* closure */) { auto const point_str = val->Str(); if (point_str->Length() != 1) throw ValueError("invalid point"); auto args = self->fmt_->get_args(); // FIXME: Wrong for multibyte characters. args.point = point_str->as_utf8_string()[0]; self->fmt_->set_args(args); } ref<Object> get_precision(PyNumber* const self, void* /* closure */) { int const precision = self->fmt_->get_args().precision; return precision == fixfmt::Number::PRECISION_NONE ? none_ref() : (ref<Object>) Long::FromLong(precision); } void set_precision(PyNumber* const self, Object* val, void* /* closure */) { auto args = self->fmt_->get_args(); args.precision = get_precision(val); self->fmt_->set_args(args); } ref<Object> get_scale( PyNumber* const self, void* /* closure */) { auto const& scale = self->fmt_->get_args().scale; if (scale.enabled()) return Tuple::builder << Float::from(scale.factor) << Unicode::from(scale.suffix); else return none_ref(); } void set_scale(PyNumber* const self, Object* val, void* /* closure */) { auto args = self->fmt_->get_args(); args.scale = get_scale(val); self->fmt_->set_args(args); } ref<Object> get_sign(PyNumber* const self, void* /* closure */) { return Unicode::from(self->fmt_->get_args().sign); } void set_sign(PyNumber* const self, Object* const val, void* /* closure */) { auto const sign_str = val->Str(); if (sign_str->Length() != 1) throw ValueError("invalid sign"); auto const sign = sign_str->as_utf8_string()[0]; if ( sign != fixfmt::Number::SIGN_NONE && sign != fixfmt::Number::SIGN_NEGATIVE && sign != fixfmt::Number::SIGN_ALWAYS) throw ValueError("invalid sign"); auto args = self->fmt_->get_args(); args.sign = sign; self->fmt_->set_args(args); } ref<Object> get_size(PyNumber* const self, void* /* closure */) { return Long::FromLong(self->fmt_->get_args().size); } void set_size(PyNumber* const self, Object* val, void* /* closure */) { auto const size = val->long_value(); if (size < 0) throw ValueError("size out of range"); auto args = self->fmt_->get_args(); args.size = size; self->fmt_->set_args(args); } ref<Object> get_width(PyNumber* const self, void* /* closure */) { return Long::FromLong(self->fmt_->get_width()); } auto getsets = GetSets<PyNumber>() .add_getset<get_bad , set_bad >("bad") .add_getset<get_inf , set_inf >("inf") .add_getset<get_nan , set_nan >("nan") .add_getset<get_pad , set_pad >("pad") .add_getset<get_point , set_point >("point") .add_getset<get_precision , set_precision >("precision") .add_getset<get_scale , set_scale >("scale") .add_getset<get_sign , set_sign >("sign") .add_getset<get_size , set_size >("size") .add_get<get_width> ("width") ; } // anonymous namespace Type PyNumber::type_ = PyTypeObject{ PyVarObject_HEAD_INIT(nullptr, 0) (char const*) "fixfmt._ext.Number", // tp_name (Py_ssize_t) sizeof(PyNumber), // tp_basicsize (Py_ssize_t) 0, // tp_itemsize (destructor) nullptr, // tp_dealloc (printfunc) nullptr, // tp_print (getattrfunc) nullptr, // tp_getattr (setattrfunc) nullptr, // tp_setattr #if PY3K (PyAsyncMethods*) nullptr, // tp_as_async #else (cmpfunc) nullptr, // tp_compare #endif (reprfunc) wrap<PyNumber, tp_repr>, // tp_repr (PyNumberMethods*) nullptr, // tp_as_number (PySequenceMethods*) nullptr, // tp_as_sequence (PyMappingMethods*) nullptr, // tp_as_mapping (hashfunc) nullptr, // tp_hash (ternaryfunc) wrap<PyNumber, tp_call>, // tp_call (reprfunc) nullptr, // tp_str (getattrofunc) nullptr, // tp_getattro (setattrofunc) nullptr, // tp_setattro (PyBufferProcs*) nullptr, // tp_as_buffer (unsigned long) Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags (char const*) nullptr, // tp_doc (traverseproc) nullptr, // tp_traverse (inquiry) nullptr, // tp_clear (richcmpfunc) nullptr, // tp_richcompare (Py_ssize_t) 0, // tp_weaklistoffset (getiterfunc) nullptr, // tp_iter (iternextfunc) nullptr, // tp_iternext (PyMethodDef*) methods, // tp_methods (PyMemberDef*) nullptr, // tp_members (PyGetSetDef*) getsets, // tp_getset (_typeobject*) nullptr, // tp_base (PyObject*) nullptr, // tp_dict (descrgetfunc) nullptr, // tp_descr_get (descrsetfunc) nullptr, // tp_descr_set (Py_ssize_t) 0, // tp_dictoffset (initproc) wrap<PyNumber, tp_init>, // tp_init (allocfunc) nullptr, // tp_alloc (newfunc) PyType_GenericNew, // tp_new (freefunc) nullptr, // tp_free (inquiry) nullptr, // tp_is_gc (PyObject*) nullptr, // tp_bases (PyObject*) nullptr, // tp_mro (PyObject*) nullptr, // tp_cache (PyObject*) nullptr, // tp_subclasses (PyObject*) nullptr, // tp_weaklist (destructor) nullptr, // tp_del (unsigned int) 0, // tp_version_tag #if PY3K (destructor) nullptr, // tp_finalize #endif }; <|endoftext|>
<commit_before>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: python/pybind11_Image.hpp * * Copyright 2017 Patrik Huber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #ifndef EOS_PYBIND11_IMAGE_HPP_ #define EOS_PYBIND11_IMAGE_HPP_ #include "pybind11/numpy.h" #include "Eigen/Core" #include <cstddef> #include <vector> NAMESPACE_BEGIN(pybind11) NAMESPACE_BEGIN(detail) /** * @file python/pybind11_Image.hpp * @brief Transparent conversion to and from Python for eos::core::Image. * * Numpy uses row-major storage order by default. * eos::core::Image uses col-major storage (like Eigen). * * If given non-standard strides or something from numpy, probably doesn't work. * May need to .clone()? in numpy before passing to the C++ function. */ /** * @brief Transparent conversion for eos::core::Image3u to and from Python. * * Converts an eos::core::Image3u to and from Python. Can construct a eos::core::Image3u from numpy arrays, * as well as potentially other Python array types. * * Note: Not sure what happens if the given numpy array is not contiguous, not in default (row-major) storage * order, or has non-standard strides. It may or may not work. */ template<> struct type_caster<eos::core::Image3u> { bool load(handle src, bool) { auto buf = pybind11::array::ensure(src); if (!buf) return false; // Todo: We should probably check that buf.strides(i) is "default", by dividing it by the Scalar type or something. if (!pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf)) { return false; // we only convert uint8_t for now. } if (buf.ndim() != 3) { return false; // we expected a numpy array with 3 dimensions. } // We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter): if (buf.shape(2) != 3) { return false; // We expected a 3-channel image. } // Note: If our Image class had support for col/row major, we could just map buf.mutable_data(). // Like with OpenCV: value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data()); // But since it doesn't, we just copy the data for now: value = eos::core::Image3u(buf.shape(0), buf.shape(1)); array_t<std::uint8_t> buf_as_array(buf); for (int r = 0; r < buf.shape(0); ++r) { for (int c = 0; c < buf.shape(1); ++c) { value(r, c)[0] = buf_as_array.at(r, c, 0); value(r, c)[1] = buf_as_array.at(r, c, 1); value(r, c)[2] = buf_as_array.at(r, c, 2); } } return true; }; static handle cast(const eos::core::Image3u& src, return_value_policy /* policy */, handle /* parent */) { const std::size_t num_channels = 3; std::vector<std::size_t> shape = { static_cast<std::size_t>(src.height()), static_cast<std::size_t>(src.width()), num_channels }; // (2048, 4, 1) is default which results in transposed image // Below line works now. In numpy the strides are (2048, 4, 1) though. I think a copy gets created nevertheless? std::vector<std::size_t> strides = { num_channels, num_channels * src.height(), 1 }; // might be cols or rows...? I think rows? // Note: I think with the change to the new Image class (July 2018), which is now row-major by default, the strides here might have changed. I didn't check. // Also, since the new Image stores a vector of Pixels, the question is whether there's any padding added by the compiler, but probably not, since all types that we use are 1 byte or a multiple thereof. // numpy: 'f' = fortran = col-major // 'c' = c = row-major = default I think. return array(pybind11::dtype::of<std::uint8_t>(), shape, strides, &src(0, 0).data()[0]).release(); }; PYBIND11_TYPE_CASTER(eos::core::Image3u, _("numpy.ndarray[uint8[m, n, 3]]")); }; /** * @brief Transparent conversion for eos::core::Image4u to and from Python. * * Converts an eos::core::Image4u to and from Python. Can construct a eos::core::Image4u from numpy arrays, * as well as potentially other Python array types. * * Note: Not sure what happens if the given numpy array is not contiguous, not in default (row-major) storage * order, or has non-standard strides. It may or may not work. */ template<> struct type_caster<eos::core::Image4u> { bool load(handle src, bool) { auto buf = pybind11::array::ensure(src); if (!buf) return false; // Todo: We should probably check that buf.strides(i) is "default", by dividing it by the Scalar type or something. if (!pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf)) { return false; // we only convert uint8_t for now. } if (buf.ndim() != 3) { return false; // we expected a numpy array with 3 dimensions. } // We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter): if (buf.shape(2) != 4) { return false; // We expected a 4-channel image. } // Note: If our Image class had support for col/row major, we could just map buf.mutable_data(). // Like with OpenCV: value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data()); // But since it doesn't, we just copy the data for now: value = eos::core::Image4u(buf.shape(0), buf.shape(1)); array_t<std::uint8_t> buf_as_array(buf); for (int r = 0; r < buf.shape(0); ++r) { for (int c = 0; c < buf.shape(1); ++c) { value(r, c)[0] = buf_as_array.at(r, c, 0); value(r, c)[1] = buf_as_array.at(r, c, 1); value(r, c)[2] = buf_as_array.at(r, c, 2); value(r, c)[3] = buf_as_array.at(r, c, 3); } } return true; }; static handle cast(const eos::core::Image4u& src, return_value_policy /* policy */, handle /* parent */) { const std::size_t num_channels = 4; std::vector<std::size_t> shape; shape = { static_cast<std::size_t>(src.height()), static_cast<std::size_t>(src.width()), num_channels }; // (2048, 4, 1) is default which results in transposed image // Below line works now. In numpy the strides are (2048, 4, 1) though. I think a copy gets created nevertheless? std::vector<size_t> strides = { num_channels, num_channels * src.height(), 1 }; // might be cols or rows...? I think rows? // Note: I think with the change to the new Image class (July 2018), which is now row-major by default, the strides here might have changed. I didn't check. // Also, since the new Image stores a vector of Pixels, the question is whether there's any padding added by the compiler, but probably not, since all types that we use are 1 byte or a multiple thereof. return array(pybind11::dtype::of<std::uint8_t>(), shape, strides, &src(0, 0).data()[0]).release(); }; PYBIND11_TYPE_CASTER(eos::core::Image4u, _("numpy.ndarray[uint8[m, n, 4]]")); }; NAMESPACE_END(detail) NAMESPACE_END(pybind11) #endif /* EOS_PYBIND11_IMAGE_HPP_ */ <commit_msg>Changed strides in Image python bindings to account for row-major Image class<commit_after>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: python/pybind11_Image.hpp * * Copyright 2017 Patrik Huber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #ifndef EOS_PYBIND11_IMAGE_HPP_ #define EOS_PYBIND11_IMAGE_HPP_ #include "pybind11/numpy.h" #include "Eigen/Core" #include <cstddef> #include <vector> NAMESPACE_BEGIN(pybind11) NAMESPACE_BEGIN(detail) /** * @file python/pybind11_Image.hpp * @brief Transparent conversion to and from Python for eos::core::Image. * * Numpy uses row-major storage order by default. * eos::core::Image uses col-major storage (like Eigen). * * If given non-standard strides or something from numpy, probably doesn't work. * May need to .clone()? in numpy before passing to the C++ function. */ /** * @brief Transparent conversion for eos::core::Image3u to and from Python. * * Converts an eos::core::Image3u to and from Python. Can construct a eos::core::Image3u from numpy arrays, * as well as potentially other Python array types. * * Note: Not sure what happens if the given numpy array is not contiguous, not in default (row-major) storage * order, or has non-standard strides. It may or may not work. */ template<> struct type_caster<eos::core::Image3u> { bool load(handle src, bool) { auto buf = pybind11::array::ensure(src); if (!buf) return false; // Todo: We should probably check that buf.strides(i) is "default", by dividing it by the Scalar type or something. if (!pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf)) { return false; // we only convert uint8_t for now. } if (buf.ndim() != 3) { return false; // we expected a numpy array with 3 dimensions. } // We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter): if (buf.shape(2) != 3) { return false; // We expected a 3-channel image. } // Note: If our Image class had support for col/row major, we could just map buf.mutable_data(). // Like with OpenCV: value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data()); // But since it doesn't, we just copy the data for now: value = eos::core::Image3u(buf.shape(0), buf.shape(1)); array_t<std::uint8_t> buf_as_array(buf); for (int r = 0; r < buf.shape(0); ++r) { for (int c = 0; c < buf.shape(1); ++c) { value(r, c)[0] = buf_as_array.at(r, c, 0); value(r, c)[1] = buf_as_array.at(r, c, 1); value(r, c)[2] = buf_as_array.at(r, c, 2); } } return true; }; static handle cast(const eos::core::Image3u& src, return_value_policy /* policy */, handle /* parent */) { const std::size_t num_channels = 3; std::vector<std::size_t> shape = { static_cast<std::size_t>(src.height()), static_cast<std::size_t>(src.width()), num_channels }; // (2048, 4, 1) is default which results in transposed image // Below line works now. In numpy the strides are (2048, 4, 1) though. I think a copy gets created nevertheless? //std::vector<std::size_t> strides = { num_channels, num_channels * src.height(), 1 }; // might be cols or rows...? I think rows? std::vector<std::size_t> strides = { num_channels * src.width(), num_channels, 1 }; // This seems to work with the row-major Image class. I just returned the same strides as the ones we got from NumPy. // Note: I think with the change to the new Image class (July 2018), which is now row-major by default, the strides here might have changed. I didn't check. // Also, since the new Image stores a vector of Pixels, the question is whether there's any padding added by the compiler, but probably not, since all types that we use are 1 byte or a multiple thereof. // numpy: 'f' = fortran = col-major // 'c' = c = row-major = default I think. return array(pybind11::dtype::of<std::uint8_t>(), shape, strides, &src(0, 0).data()[0]).release(); }; PYBIND11_TYPE_CASTER(eos::core::Image3u, _("numpy.ndarray[uint8[m, n, 3]]")); }; /** * @brief Transparent conversion for eos::core::Image4u to and from Python. * * Converts an eos::core::Image4u to and from Python. Can construct a eos::core::Image4u from numpy arrays, * as well as potentially other Python array types. * * Note: Not sure what happens if the given numpy array is not contiguous, not in default (row-major) storage * order, or has non-standard strides. It may or may not work. */ template<> struct type_caster<eos::core::Image4u> { bool load(handle src, bool) { auto buf = pybind11::array::ensure(src); if (!buf) return false; // Todo: We should probably check that buf.strides(i) is "default", by dividing it by the Scalar type or something. if (!pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf)) { return false; // we only convert uint8_t for now. } if (buf.ndim() != 3) { return false; // we expected a numpy array with 3 dimensions. } // We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter): if (buf.shape(2) != 4) { return false; // We expected a 4-channel image. } // Note: If our Image class had support for col/row major, we could just map buf.mutable_data(). // Like with OpenCV: value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data()); // But since it doesn't, we just copy the data for now: value = eos::core::Image4u(buf.shape(0), buf.shape(1)); array_t<std::uint8_t> buf_as_array(buf); for (int r = 0; r < buf.shape(0); ++r) { for (int c = 0; c < buf.shape(1); ++c) { value(r, c)[0] = buf_as_array.at(r, c, 0); value(r, c)[1] = buf_as_array.at(r, c, 1); value(r, c)[2] = buf_as_array.at(r, c, 2); value(r, c)[3] = buf_as_array.at(r, c, 3); } } return true; }; static handle cast(const eos::core::Image4u& src, return_value_policy /* policy */, handle /* parent */) { const std::size_t num_channels = 4; std::vector<std::size_t> shape; shape = { static_cast<std::size_t>(src.height()), static_cast<std::size_t>(src.width()), num_channels }; // (2048, 4, 1) is default which results in transposed image // Below line works now. In numpy the strides are (2048, 4, 1) though. I think a copy gets created nevertheless? std::vector<size_t> strides = { num_channels * src.width(), num_channels, 1 }; // might be cols or rows...? I think rows? // Note: I think with the change to the new Image class (July 2018), which is now row-major by default, the strides here might have changed. I didn't check. // Also, since the new Image stores a vector of Pixels, the question is whether there's any padding added by the compiler, but probably not, since all types that we use are 1 byte or a multiple thereof. return array(pybind11::dtype::of<std::uint8_t>(), shape, strides, &src(0, 0).data()[0]).release(); }; PYBIND11_TYPE_CASTER(eos::core::Image4u, _("numpy.ndarray[uint8[m, n, 4]]")); }; NAMESPACE_END(detail) NAMESPACE_END(pybind11) #endif /* EOS_PYBIND11_IMAGE_HPP_ */ <|endoftext|>
<commit_before>#ifndef _EIGEN3_HDF5_HPP #define _EIGEN3_HDF5_HPP #include <array> #include <cassert> #include <complex> #include <cstddef> #include <stdexcept> #include <string> #include <vector> //#include <hdf5.h> #include <H5Cpp.h> #include <Eigen/Dense> namespace EigenHDF5 { template <typename T> struct DatatypeSpecialization; // floating-point types template <> struct DatatypeSpecialization<float> { static inline const H5::DataType * get (void) { return &H5::PredType::NATIVE_FLOAT; } }; template <> struct DatatypeSpecialization<double> { static inline const H5::DataType * get (void) { return &H5::PredType::NATIVE_DOUBLE; } }; template <> struct DatatypeSpecialization<long double> { static inline const H5::DataType * get (void) { return &H5::PredType::NATIVE_LDOUBLE; } }; // integer types template <> struct DatatypeSpecialization<int> { static inline const H5::DataType * get (void) { return &H5::PredType::NATIVE_INT; } }; template <> struct DatatypeSpecialization<unsigned int> { static inline const H5::DataType * get (void) { return &H5::PredType::NATIVE_UINT; } }; // complex types // // inspired by http://www.mail-archive.com/hdf-forum@hdfgroup.org/msg00759.html template <typename T> class ComplexH5Type : public H5::CompType { public: ComplexH5Type (void) : CompType(sizeof(std::complex<T>)) { const H5::DataType * const datatype = DatatypeSpecialization<T>::get(); assert(datatype->getSize() == sizeof(T)); // If we call the members "r" and "i", h5py interprets the // structure correctly as complex numbers. this->insertMember(std::string("r"), 0, *datatype); this->insertMember(std::string("i"), sizeof(T), *datatype); this->pack(); } static const ComplexH5Type<T> * get_singleton (void) { // NOTE: constructing this could be a race condition static ComplexH5Type<T> singleton; return &singleton; } }; template <typename T> struct DatatypeSpecialization<std::complex<T> > { static inline const H5::DataType * get (void) { return ComplexH5Type<T>::get_singleton(); } }; // see http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html template <typename Derived> void save (H5::CommonFG &h5group, const std::string &name, const Eigen::EigenBase<Derived> &mat, const H5::DSetCreatPropList &plist=H5::DSetCreatPropList::DEFAULT) { typedef typename Derived::Scalar Scalar; const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> row_major_mat(mat); const std::array<hsize_t, 2> dimensions = { { static_cast<hsize_t>(mat.rows()), static_cast<hsize_t>(mat.cols()) } }; const H5::DataSpace dataspace(dimensions.size(), dimensions.data()); const H5::DataType * const datatype = DatatypeSpecialization<Scalar>::get(); H5::DataSet dataset = h5group.createDataSet(name, *datatype, dataspace, plist); dataset.write(row_major_mat.data(), *datatype); } template <typename Derived> void load (const H5::CommonFG &h5group, const std::string &name, const Eigen::DenseBase<Derived> &mat) { typedef typename Derived::Scalar Scalar; const H5::DataSet dataset = h5group.openDataSet(name); const H5::DataSpace dataspace = dataset.getSpace(); const std::size_t ndims = dataspace.getSimpleExtentNdims(); assert(ndims > 0); std::array<hsize_t, 2> dimensions; dimensions[1] = 1; // in case it's 1D if (ndims > dimensions.size()) { throw std::runtime_error("HDF5 array has too many dimensions."); } dataspace.getSimpleExtentDims(dimensions.data()); const hsize_t rows = dimensions[0], cols = dimensions[1]; std::vector<Scalar> data(rows * cols); const H5::DataType * const datatype = DatatypeSpecialization<Scalar>::get(); dataset.read(data.data(), *datatype, dataspace); // see http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html Eigen::DenseBase<Derived> &mat_ = const_cast<Eigen::DenseBase<Derived> &>(mat); mat_.derived().resize(rows, cols); mat_ = Eigen::Map<Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> >(data.data(), rows, cols); } } // namespace EigenHDF5 #endif <commit_msg>work for long integer types<commit_after>#ifndef _EIGEN3_HDF5_HPP #define _EIGEN3_HDF5_HPP #include <array> #include <cassert> #include <complex> #include <cstddef> #include <stdexcept> #include <string> #include <vector> //#include <hdf5.h> #include <H5Cpp.h> #include <Eigen/Dense> namespace EigenHDF5 { template <typename T> struct DatatypeSpecialization; // floating-point types template <> struct DatatypeSpecialization<float> { static inline const H5::DataType * get (void) { return &H5::PredType::NATIVE_FLOAT; } }; template <> struct DatatypeSpecialization<double> { static inline const H5::DataType * get (void) { return &H5::PredType::NATIVE_DOUBLE; } }; template <> struct DatatypeSpecialization<long double> { static inline const H5::DataType * get (void) { return &H5::PredType::NATIVE_LDOUBLE; } }; // integer types template <> struct DatatypeSpecialization<int> { static inline const H5::DataType * get (void) { return &H5::PredType::NATIVE_INT; } }; template <> struct DatatypeSpecialization<unsigned int> { static inline const H5::DataType * get (void) { return &H5::PredType::NATIVE_UINT; } }; template <> struct DatatypeSpecialization<long> { static inline const H5::DataType * get (void) { return &H5::PredType::NATIVE_LONG; } }; template <> struct DatatypeSpecialization<unsigned long> { static inline const H5::DataType * get (void) { return &H5::PredType::NATIVE_ULONG; } }; // complex types // // inspired by http://www.mail-archive.com/hdf-forum@hdfgroup.org/msg00759.html template <typename T> class ComplexH5Type : public H5::CompType { public: ComplexH5Type (void) : CompType(sizeof(std::complex<T>)) { const H5::DataType * const datatype = DatatypeSpecialization<T>::get(); assert(datatype->getSize() == sizeof(T)); // If we call the members "r" and "i", h5py interprets the // structure correctly as complex numbers. this->insertMember(std::string("r"), 0, *datatype); this->insertMember(std::string("i"), sizeof(T), *datatype); this->pack(); } static const ComplexH5Type<T> * get_singleton (void) { // NOTE: constructing this could be a race condition static ComplexH5Type<T> singleton; return &singleton; } }; template <typename T> struct DatatypeSpecialization<std::complex<T> > { static inline const H5::DataType * get (void) { return ComplexH5Type<T>::get_singleton(); } }; // see http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html template <typename Derived> void save (H5::CommonFG &h5group, const std::string &name, const Eigen::EigenBase<Derived> &mat, const H5::DSetCreatPropList &plist=H5::DSetCreatPropList::DEFAULT) { typedef typename Derived::Scalar Scalar; const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> row_major_mat(mat); const std::array<hsize_t, 2> dimensions = { { static_cast<hsize_t>(mat.rows()), static_cast<hsize_t>(mat.cols()) } }; const H5::DataSpace dataspace(dimensions.size(), dimensions.data()); const H5::DataType * const datatype = DatatypeSpecialization<Scalar>::get(); H5::DataSet dataset = h5group.createDataSet(name, *datatype, dataspace, plist); dataset.write(row_major_mat.data(), *datatype); } template <typename Derived> void load (const H5::CommonFG &h5group, const std::string &name, const Eigen::DenseBase<Derived> &mat) { typedef typename Derived::Scalar Scalar; const H5::DataSet dataset = h5group.openDataSet(name); const H5::DataSpace dataspace = dataset.getSpace(); const std::size_t ndims = dataspace.getSimpleExtentNdims(); assert(ndims > 0); std::array<hsize_t, 2> dimensions; dimensions[1] = 1; // in case it's 1D if (ndims > dimensions.size()) { throw std::runtime_error("HDF5 array has too many dimensions."); } dataspace.getSimpleExtentDims(dimensions.data()); const hsize_t rows = dimensions[0], cols = dimensions[1]; std::vector<Scalar> data(rows * cols); const H5::DataType * const datatype = DatatypeSpecialization<Scalar>::get(); dataset.read(data.data(), *datatype, dataspace); // see http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html Eigen::DenseBase<Derived> &mat_ = const_cast<Eigen::DenseBase<Derived> &>(mat); mat_.derived().resize(rows, cols); mat_ = Eigen::Map<Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> >(data.data(), rows, cols); } } // namespace EigenHDF5 #endif <|endoftext|>
<commit_before>#include "rapid_display/display.h" #include "actionlib/client/simple_action_client.h" #include "blinky/FaceAction.h" #include "ros/ros.h" #include "rapid_ros/action_client.h" using ros::Duration; namespace rapid { namespace display { Blinky::Blinky(rapid_ros::ActionClientInterface<blinky::FaceAction>* client) : client_(client), server_wait_time_(5) {} Blinky::~Blinky() { if (client_ != NULL) { delete client_; } else { ROS_ERROR("Pointer to ActionClient was null!"); } } bool Blinky::ShowDefault() { if (client_ == NULL) { ROS_ERROR("Pointer to ActionClient was null!"); return false; } if (!WaitForServer(server_wait_time_)) { ROS_ERROR("Timed out waiting for the Blinky server."); return false; } blinky::FaceGoal goal; goal.display_type = goal.DEFAULT; client_->sendGoal(goal); if (!client_->waitForResult(Duration(server_wait_time_))) { ROS_ERROR("Timed out waiting for Blinky result."); return false; } return true; } bool Blinky::ShowMessage(const std::string& h1_text, const std::string& h2_text) { if (client_ == NULL) { ROS_ERROR("Pointer to ActionClient was null!"); return false; } if (!WaitForServer(server_wait_time_)) { ROS_ERROR("Timed out waiting for the Blinky server."); return false; } blinky::FaceGoal goal; goal.display_type = goal.DISPLAY_MESSAGE; goal.h1_text = h1_text; goal.h2_text = h2_text; client_->sendGoal(goal); if (!client_->waitForResult(Duration(server_wait_time_))) { ROS_ERROR("Timed out waiting for Blinky result."); return false; } return true; } bool Blinky::AskMultipleChoice(const std::string& question, const std::vector<std::string>& choices, std::string* choice) { if (client_ == NULL) { ROS_ERROR("Pointer to ActionClient was null!"); return false; } if (!WaitForServer(server_wait_time_)) { ROS_ERROR("Timed out waiting for the Blinky server."); return false; } blinky::FaceGoal goal; goal.display_type = goal.ASK_CHOICE; goal.question = question; goal.choices = choices; client_->sendGoal(goal); blinky::FaceResultConstPtr result = client_->getResult(); *choice = result->choice; return true; } bool Blinky::WaitForServer(const int seconds) { if (client_ == NULL) { ROS_ERROR("Pointer to ActionClient was null!"); return false; } Duration duration(seconds); return client_->waitForServer(duration); } } // namespace display } // namespace rapid <commit_msg>Actually wait for the result.<commit_after>#include "rapid_display/display.h" #include "actionlib/client/simple_action_client.h" #include "blinky/FaceAction.h" #include "ros/ros.h" #include "rapid_ros/action_client.h" using ros::Duration; namespace rapid { namespace display { Blinky::Blinky(rapid_ros::ActionClientInterface<blinky::FaceAction>* client) : client_(client), server_wait_time_(5) {} Blinky::~Blinky() { if (client_ != NULL) { delete client_; } else { ROS_ERROR("Pointer to ActionClient was null!"); } } bool Blinky::ShowDefault() { if (client_ == NULL) { ROS_ERROR("Pointer to ActionClient was null!"); return false; } if (!WaitForServer(server_wait_time_)) { ROS_ERROR("Timed out waiting for the Blinky server."); return false; } blinky::FaceGoal goal; goal.display_type = goal.DEFAULT; client_->sendGoal(goal); if (!client_->waitForResult(Duration(server_wait_time_))) { ROS_ERROR("Timed out waiting for Blinky result."); return false; } return true; } bool Blinky::ShowMessage(const std::string& h1_text, const std::string& h2_text) { if (client_ == NULL) { ROS_ERROR("Pointer to ActionClient was null!"); return false; } if (!WaitForServer(server_wait_time_)) { ROS_ERROR("Timed out waiting for the Blinky server."); return false; } blinky::FaceGoal goal; goal.display_type = goal.DISPLAY_MESSAGE; goal.h1_text = h1_text; goal.h2_text = h2_text; client_->sendGoal(goal); if (!client_->waitForResult(Duration(server_wait_time_))) { ROS_ERROR("Timed out waiting for Blinky result."); return false; } return true; } bool Blinky::AskMultipleChoice(const std::string& question, const std::vector<std::string>& choices, std::string* choice) { if (client_ == NULL) { ROS_ERROR("Pointer to ActionClient was null!"); return false; } if (!WaitForServer(server_wait_time_)) { ROS_ERROR("Timed out waiting for the Blinky server."); return false; } blinky::FaceGoal goal; goal.display_type = goal.ASK_CHOICE; goal.question = question; goal.choices = choices; client_->sendGoal(goal); client_->waitForResult(); blinky::FaceResultConstPtr result = client_->getResult(); *choice = result->choice; return true; } bool Blinky::WaitForServer(const int seconds) { if (client_ == NULL) { ROS_ERROR("Pointer to ActionClient was null!"); return false; } Duration duration(seconds); return client_->waitForServer(duration); } } // namespace display } // namespace rapid <|endoftext|>
<commit_before>/****************************/ /* readschematicnetlist.cpp */ /****************************/ /* Read a nelist type Eeschema or OrcadPCB2 and build the component list * Manages the lines like : * ( XXXXXX VALEUR|(pin1,pin2,...=newalim) ID VALEUR */ #include "fctsys.h" #include "wxstruct.h" #include "common.h" #include "confirm.h" #include "kicad_string.h" #include "macros.h" #include "cvpcb.h" #include "protos.h" #include "cvstruct.h" #define SEPARATEUR '|' /* caractere separateur dans netliste */ /* routines locales : */ static int ReadPinConnection( FILE* f, COMPONENT* CurrentCmp ); /* Tri la liste des composants par ordre alphabetique et met a jour le nouveau * chainage avant/arriere retourne un pointeur sur le 1er element de la liste */ #define BUFFER_CHAR_SIZE 1024 // Size of buffers used to store netlist data /** * Function ReadSchematicNetlist * Read a Eeschema (or OrcadPCB) netlist * like: * # EESchema Netlist Version 1.1 created 15/5/2008-12:09:21 * ( * ( /32568D1E $noname JP1 CONN_8X2 {Lib=CONN_8X2} * ( 1 GND ) * ( 2 /REF10 ) * ( 3 GND ) * ( 4 /REF11 ) * ( 5 GND ) * ( 6 /REF7 ) * ( 7 GND ) * ( 8 /REF9 ) * ( 9 GND ) * ( 10 /REF6 ) * ( 11 GND ) * ( 12 /REF8 ) * ( 13 GND ) * ( 14 /REF4 ) * ( 15 GND ) * ( 16 /REF5 ) * ) * ( /325679C1 $noname RR1 9x1K {Lib=RR9} * ( 1 VCC ) * ( 2 /REF5 ) * ( 3 /REF4 ) * ( 4 /REF8 ) * ( 5 /REF6 ) * ( 6 /REF9 ) * ( 7 /REF7 ) * ( 8 /REF11 ) * ( 9 /REF10 ) * ( 10 ? ) * ) * ) * * * { Allowed footprints by component: * $component R5 * R? * SM0603 * SM0805 * $endlist * $component C2 * SM* * C? * C1-1 * $endlist * $endfootprintlist * } */ int WinEDA_CvpcbFrame::ReadSchematicNetlist() { char alim[1024]; int i, k, l; char* LibName; char Line[BUFFER_CHAR_SIZE + 1]; wxString component_reference; /* buffer for component reference (U1, R4...) */ wxString schematic_timestamp; /* buffer for component time stamp */ wxString footprint_name; /* buffer for component footprint field */ wxString component_value; /* buffer for component values (470K, 22nF ...) */ char* ptchar; COMPONENT* Cmp; FILE* source; m_modified = false; m_isEESchemaNetlist = false; /* Clear components buffer */ if( !m_components.empty() ) { m_components.clear(); } source = wxFopen( m_NetlistFileName.GetFullPath(), wxT( "rt" ) ); if( source == 0 ) { DisplayError( this, _( "File <" ) + m_NetlistFileName.GetFullPath() + _( "> not found" ) ); return -1; } /* Read the file header (must be "( { OrCAD PCB" or "({ OrCAD PCB" ) * or "# EESchema Netliste" */ (void) fgets( Line, BUFFER_CHAR_SIZE, source ); /* test for netlist type PCB2 */ i = strnicmp( Line, "( {", 3 ); if( i != 0 ) i = strnicmp( Line, "({", 2 ); if( i != 0 ) { i = strnicmp( Line, "# EESchema", 7 ); /* net type EESchema */ if( i == 0 ) m_isEESchemaNetlist = TRUE; } if( i != 0 ) { wxString msg, Lineconv = CONV_FROM_UTF8( Line ); msg.Printf( _( "Unknown file format <%s>" ), Lineconv.GetData() ); DisplayError( this, msg ); fclose( source ); return -3; } SetStatusText( _( "Netlist Format: EESchema" ), 0 ); /* Read the netlist */ for( ; ; ) { /* Search the beginning of a component description */ if( fgets( Line, BUFFER_CHAR_SIZE, source ) == 0 ) break; /* Remove blanks */ i = 0; while( Line[i] == ' ' ) i++; /* remove empty lines : */ if( Line[i] < ' ' ) continue; if( strnicmp( &Line[i], "{ Allowed footprints", 20 ) == 0 ) { ReadFootprintFilterList( source ); continue; } if( strnicmp( &Line[i], "( ", 2 ) != 0 ) continue; /*******************************/ /* Component description found */ /*******************************/ while( Line[i] != ' ' ) i++; while( Line[i] == ' ' ) i++; /* i points the beginning of the schematic time stamp */ schematic_timestamp.Empty(); while( Line[i] != ' ' ) schematic_timestamp.Append( Line[i++] ); /* search val/ref.lib */ while( Line[i] == ' ' ) i++; /* i points the component value */ LibName = Line + i; component_reference.Empty(); footprint_name.Empty(); component_value.Empty(); memset( alim, 0, sizeof(alim) ); /* Read value */ ptchar = strstr( &Line[i], " " ); // Search end of value field (space) if( ptchar == 0 ) { wxString msg; msg.Printf( _( "Netlist error: %s" ), Line ); DisplayError( this, msg ); k = 0; } else k = ptchar - Line; for( ; i < k; i++ ) { if( Line[i] == SEPARATEUR ) break; footprint_name.Append( Line[i] ); } if( (Line[++i] == '(') && (Line[k - 1] == ')' ) ) { i++; l = 0; while( k - 1 > i ) alim[l++] = Line[i++]; } else i = k; /* Search component reference */ while( Line[i] != ' ' ) i++; /* goto end of value field */ while( Line[i] == ' ' ) i++; /* goto beginning of reference */ /* debut reference trouv */ for( ; ; i++ ) { #if defined(KICAD_GOST) if( Line[i] == ' ' ) #else if( Line[i] <= ' ' ) #endif break; component_reference.Append( Line[i] ); } /* Search component value */ while( Line[i] == ' ' ) i++; /** goto beginning of value */ for( ; ; i++ ) { #if defined(KICAD_GOST) if( (Line[i] == ' ') || (Line[i] == '\n') ) #else if( Line[i] <= ' ' ) #endif break; component_value.Append( Line[i] ); } /* Store info for this component */ Cmp = new COMPONENT(); Cmp->m_Reference = component_reference; Cmp->m_Value = component_value; m_components.push_back( Cmp ); if( m_isEESchemaNetlist ) /* copy footprint name: */ { if( strnicmp( LibName, "$noname", 7 ) != 0 ) { while( *LibName > ' ' ) { Cmp->m_Module.Append( *LibName ); LibName++; } } } Cmp->m_TimeStamp = schematic_timestamp; ReadPinConnection( source, Cmp ); } fclose( source ); m_components.sort(); return 0; } int WinEDA_CvpcbFrame::ReadFootprintFilterList( FILE* f ) { char Line[BUFFER_CHAR_SIZE + 1]; wxString CmpRef; COMPONENT* Cmp = NULL; for( ; ; ) { if( fgets( Line, BUFFER_CHAR_SIZE, f ) == 0 ) break; if( strnicmp( Line, "$endlist", 8 ) == 0 ) { Cmp = NULL; continue; } if( strnicmp( Line, "$endfootprintlist", 4 ) == 0 ) return 0; if( strnicmp( Line, "$component", 10 ) == 0 ) // New component ref found { CmpRef = CONV_FROM_UTF8( Line + 11 ); CmpRef.Trim( TRUE ); CmpRef.Trim( FALSE ); /* Search the new component in list */ BOOST_FOREACH( COMPONENT& component, m_components ) { Cmp = &component; if( Cmp->m_Reference == CmpRef ) break; } } else if( Cmp ) { wxString fp = CONV_FROM_UTF8( Line + 1 ); fp.Trim( FALSE ); fp.Trim( TRUE ); Cmp->m_FootprintFilter.Add( fp ); } } return 1; } int ReadPinConnection( FILE* f, COMPONENT* Cmp ) { int i, jj; wxString numpin; wxString net; char Line[BUFFER_CHAR_SIZE + 1]; PIN* Pin = NULL; for( ; ; ) { /* debut description trouv */ for( ; ; ) { if( fgets( Line, BUFFER_CHAR_SIZE, f ) == 0 ) return -1; /* remove blanks from the beginning of the line */ i = 0; while( Line[i] == ' ' ) i++; while( Line[i] == '(' ) i++; while( Line[i] == ' ' ) i++; /* remove empty lines : */ if( Line[i] < ' ' ) continue; /* fin de description ? */ if( Line[i] == ')' ) return 0; net.Empty(); numpin.Empty(); /* Read pin name , 4 letters */ for( jj = 0; jj < 4; jj++, i++ ) { if( Line[i] == ' ' ) break; numpin.Append( Line[i] ); } /* Read netname */ while( Line[i] == ' ' ) i++; for( ; ; i++ ) { if( Line[i] <= ' ' ) break; net.Append( Line[i] ); } Pin = new PIN(); Pin->m_Number = numpin; Pin->m_Net = net; Cmp->m_Pins.push_back( Pin ); } } } <commit_msg>cvpcb: russian GOST windows bug fix<commit_after>/****************************/ /* readschematicnetlist.cpp */ /****************************/ /* Read a nelist type Eeschema or OrcadPCB2 and build the component list * Manages the lines like : * ( XXXXXX VALEUR|(pin1,pin2,...=newalim) ID VALEUR */ #include "fctsys.h" #include "wxstruct.h" #include "common.h" #include "confirm.h" #include "kicad_string.h" #include "macros.h" #include "cvpcb.h" #include "protos.h" #include "cvstruct.h" #define SEPARATEUR '|' /* caractere separateur dans netliste */ /* routines locales : */ static int ReadPinConnection( FILE* f, COMPONENT* CurrentCmp ); /* Tri la liste des composants par ordre alphabetique et met a jour le nouveau * chainage avant/arriere retourne un pointeur sur le 1er element de la liste */ #define BUFFER_CHAR_SIZE 1024 // Size of buffers used to store netlist data /** * Function ReadSchematicNetlist * Read a Eeschema (or OrcadPCB) netlist * like: * # EESchema Netlist Version 1.1 created 15/5/2008-12:09:21 * ( * ( /32568D1E $noname JP1 CONN_8X2 {Lib=CONN_8X2} * ( 1 GND ) * ( 2 /REF10 ) * ( 3 GND ) * ( 4 /REF11 ) * ( 5 GND ) * ( 6 /REF7 ) * ( 7 GND ) * ( 8 /REF9 ) * ( 9 GND ) * ( 10 /REF6 ) * ( 11 GND ) * ( 12 /REF8 ) * ( 13 GND ) * ( 14 /REF4 ) * ( 15 GND ) * ( 16 /REF5 ) * ) * ( /325679C1 $noname RR1 9x1K {Lib=RR9} * ( 1 VCC ) * ( 2 /REF5 ) * ( 3 /REF4 ) * ( 4 /REF8 ) * ( 5 /REF6 ) * ( 6 /REF9 ) * ( 7 /REF7 ) * ( 8 /REF11 ) * ( 9 /REF10 ) * ( 10 ? ) * ) * ) * * * { Allowed footprints by component: * $component R5 * R? * SM0603 * SM0805 * $endlist * $component C2 * SM* * C? * C1-1 * $endlist * $endfootprintlist * } */ int WinEDA_CvpcbFrame::ReadSchematicNetlist() { char alim[1024]; int i, k, l; char* LibName; char Line[BUFFER_CHAR_SIZE + 1]; wxString component_reference; /* buffer for component reference (U1, R4...) */ wxString schematic_timestamp; /* buffer for component time stamp */ wxString footprint_name; /* buffer for component footprint field */ wxString component_value; /* buffer for component values (470K, 22nF ...) */ char* ptchar; COMPONENT* Cmp; FILE* source; m_modified = false; m_isEESchemaNetlist = false; /* Clear components buffer */ if( !m_components.empty() ) { m_components.clear(); } source = wxFopen( m_NetlistFileName.GetFullPath(), wxT( "rt" ) ); if( source == 0 ) { DisplayError( this, _( "File <" ) + m_NetlistFileName.GetFullPath() + _( "> not found" ) ); return -1; } /* Read the file header (must be "( { OrCAD PCB" or "({ OrCAD PCB" ) * or "# EESchema Netliste" */ (void) fgets( Line, BUFFER_CHAR_SIZE, source ); /* test for netlist type PCB2 */ i = strnicmp( Line, "( {", 3 ); if( i != 0 ) i = strnicmp( Line, "({", 2 ); if( i != 0 ) { i = strnicmp( Line, "# EESchema", 7 ); /* net type EESchema */ if( i == 0 ) m_isEESchemaNetlist = TRUE; } if( i != 0 ) { wxString msg, Lineconv = CONV_FROM_UTF8( Line ); msg.Printf( _( "Unknown file format <%s>" ), Lineconv.GetData() ); DisplayError( this, msg ); fclose( source ); return -3; } SetStatusText( _( "Netlist Format: EESchema" ), 0 ); /* Read the netlist */ for( ; ; ) { /* Search the beginning of a component description */ if( fgets( Line, BUFFER_CHAR_SIZE, source ) == 0 ) break; /* Remove blanks */ i = 0; while( Line[i] == ' ' ) i++; /* remove empty lines : */ if( Line[i] < ' ' ) continue; if( strnicmp( &Line[i], "{ Allowed footprints", 20 ) == 0 ) { ReadFootprintFilterList( source ); continue; } if( strnicmp( &Line[i], "( ", 2 ) != 0 ) continue; /*******************************/ /* Component description found */ /*******************************/ while( Line[i] != ' ' ) i++; while( Line[i] == ' ' ) i++; /* i points the beginning of the schematic time stamp */ schematic_timestamp.Empty(); while( Line[i] != ' ' ) schematic_timestamp.Append( Line[i++] ); /* search val/ref.lib */ while( Line[i] == ' ' ) i++; /* i points the component value */ LibName = Line + i; component_reference.Empty(); footprint_name.Empty(); component_value.Empty(); memset( alim, 0, sizeof(alim) ); /* Read value */ ptchar = strstr( &Line[i], " " ); // Search end of value field (space) if( ptchar == 0 ) { wxString msg; msg.Printf( _( "Netlist error: %s" ), Line ); DisplayError( this, msg ); k = 0; } else k = ptchar - Line; for( ; i < k; i++ ) { if( Line[i] == SEPARATEUR ) break; footprint_name.Append( Line[i] ); } if( (Line[++i] == '(') && (Line[k - 1] == ')' ) ) { i++; l = 0; while( k - 1 > i ) alim[l++] = Line[i++]; } else i = k; /* Search component reference */ while( Line[i] != ' ' ) i++; /* goto end of value field */ while( Line[i] == ' ' ) i++; /* goto beginning of reference */ /* debut reference trouv */ for( ; ; i++ ) { #if defined(KICAD_GOST) if( Line[i] == ' ' ) #else if( Line[i] <= ' ' ) #endif break; component_reference.Append( Line[i] ); } /* Search component value */ while( Line[i] == ' ' ) i++; /** goto beginning of value */ for( ; ; i++ ) { #if defined(KICAD_GOST) if( (Line[i] == ' ') || (Line[i] == '\n') || (Line[i] == '\r') ) #else if( Line[i] <= ' ' ) #endif break; component_value.Append( Line[i] ); } /* Store info for this component */ Cmp = new COMPONENT(); Cmp->m_Reference = component_reference; Cmp->m_Value = component_value; m_components.push_back( Cmp ); if( m_isEESchemaNetlist ) /* copy footprint name: */ { if( strnicmp( LibName, "$noname", 7 ) != 0 ) { while( *LibName > ' ' ) { Cmp->m_Module.Append( *LibName ); LibName++; } } } Cmp->m_TimeStamp = schematic_timestamp; ReadPinConnection( source, Cmp ); } fclose( source ); m_components.sort(); return 0; } int WinEDA_CvpcbFrame::ReadFootprintFilterList( FILE* f ) { char Line[BUFFER_CHAR_SIZE + 1]; wxString CmpRef; COMPONENT* Cmp = NULL; for( ; ; ) { if( fgets( Line, BUFFER_CHAR_SIZE, f ) == 0 ) break; if( strnicmp( Line, "$endlist", 8 ) == 0 ) { Cmp = NULL; continue; } if( strnicmp( Line, "$endfootprintlist", 4 ) == 0 ) return 0; if( strnicmp( Line, "$component", 10 ) == 0 ) // New component ref found { CmpRef = CONV_FROM_UTF8( Line + 11 ); CmpRef.Trim( TRUE ); CmpRef.Trim( FALSE ); /* Search the new component in list */ BOOST_FOREACH( COMPONENT& component, m_components ) { Cmp = &component; if( Cmp->m_Reference == CmpRef ) break; } } else if( Cmp ) { wxString fp = CONV_FROM_UTF8( Line + 1 ); fp.Trim( FALSE ); fp.Trim( TRUE ); Cmp->m_FootprintFilter.Add( fp ); } } return 1; } int ReadPinConnection( FILE* f, COMPONENT* Cmp ) { int i, jj; wxString numpin; wxString net; char Line[BUFFER_CHAR_SIZE + 1]; PIN* Pin = NULL; for( ; ; ) { /* debut description trouv */ for( ; ; ) { if( fgets( Line, BUFFER_CHAR_SIZE, f ) == 0 ) return -1; /* remove blanks from the beginning of the line */ i = 0; while( Line[i] == ' ' ) i++; while( Line[i] == '(' ) i++; while( Line[i] == ' ' ) i++; /* remove empty lines : */ if( Line[i] < ' ' ) continue; /* fin de description ? */ if( Line[i] == ')' ) return 0; net.Empty(); numpin.Empty(); /* Read pin name , 4 letters */ for( jj = 0; jj < 4; jj++, i++ ) { if( Line[i] == ' ' ) break; numpin.Append( Line[i] ); } /* Read netname */ while( Line[i] == ' ' ) i++; for( ; ; i++ ) { if( Line[i] <= ' ' ) break; net.Append( Line[i] ); } Pin = new PIN(); Pin->m_Number = numpin; Pin->m_Net = net; Cmp->m_Pins.push_back( Pin ); } } } <|endoftext|>
<commit_before>/* * @Copyright: Copyright[2015]<Alejandro Bordallo> * @Date: 2015-05-17 * @Email: alex.bordallo@ed.ac.uk * @Desc: Joystick remote control node */ #include "joy_remote.h" JoyRemote::JoyRemote(ros::NodeHandle* nh) { nh_ = nh; joy_sub_ = nh_->subscribe("joy", 1000, &JoyRemote::joyCallback, this); moveTowardClient = nh_->serviceClient<motion::MoveToward>( "/motion/move_toward", true); wakeUpClient = nh_->serviceClient<std_srvs::Empty>( "/motion/wake_up", true); moveInitClient = nh_->serviceClient<std_srvs::Empty>( "/motion/move_init", true); standClient = nh_->serviceClient<motion::SetPosture>( "/motion/goto_posture", true); restClient = nh_->serviceClient<std_srvs::Empty>( "/motion/rest", true); stopMoveClient = nh_->serviceClient<std_srvs::Empty>( "/motion/stop_move", true); INFO("Joystick remote node initialised" << std::endl); wakeUpFlag = false; moveInitFlag = false; standFlag = false; restFlag = false; standSrv.request.speed = 1.0f; } JoyRemote::~JoyRemote() { ros::shutdown(); } void JoyRemote::joyCallback(const sensor_msgs::Joy::ConstPtr& msg) { if (msg->buttons[1]) { wakeUpFlag = true; } else if (msg->buttons[2]) { moveInitFlag = true; } else if (msg->buttons[3]) { standFlag = true; } else if (msg->buttons[0]) { restFlag = true; } else { float x = msg->axes[1]; float y = msg->axes[0]; float theta = msg->axes[3]; moveSrv.request.norm_velocity.x = x; moveSrv.request.norm_velocity.y = y; moveSrv.request.norm_velocity.theta = theta; } } void JoyRemote::sendCmd() { if (wakeUpFlag) { this->wakeUp(); } else if (moveInitFlag) { this->moveInit(); } else if (standFlag) { this->stand(); } else if (restFlag) { this->rest(); } else {moveTowardClient.call(moveSrv);} } void JoyRemote::wakeUp() { wakeUpClient.call(wakeUpSrv); wakeUpFlag = false; } void JoyRemote::moveInit() { moveInitClient.call(moveInitSrv); moveInitFlag = false; } void JoyRemote::stand() { wakeUpClient.call(wakeUpSrv); standSrv.request.posture_name = "Stand"; standClient.call(standSrv); moveInitClient.call(moveInitSrv); standFlag = false; } void JoyRemote::rest() { stopMoveClient.call(stopSrv); sleep(0.25); moveInitClient.call(moveInitSrv); sleep(0.25); restClient.call(restSrv); restFlag = false; } int main(int argc, char *argv[]) { ros::init(argc, argv, "JoyRemote"); ros::NodeHandle nh; JoyRemote joyTest(&nh); ros::Rate r(5); while (ros::ok()) { joyTest.sendCmd(); ros::spinOnce(); r.sleep(); } return 0; } <commit_msg>Add check if first required service is available for remote control<commit_after>/* * @Copyright: Copyright[2015]<Alejandro Bordallo> * @Date: 2015-05-17 * @Email: alex.bordallo@ed.ac.uk * @Desc: Joystick remote control node */ #include "joy_remote.h" JoyRemote::JoyRemote(ros::NodeHandle* nh) { nh_ = nh; joy_sub_ = nh_->subscribe("joy", 1000, &JoyRemote::joyCallback, this); moveTowardClient = nh_->serviceClient<motion::MoveToward>( "/motion/move_toward", true); moveTowardClient.waitForExistence(); wakeUpClient = nh_->serviceClient<std_srvs::Empty>( "/motion/wake_up", true); moveInitClient = nh_->serviceClient<std_srvs::Empty>( "/motion/move_init", true); standClient = nh_->serviceClient<motion::SetPosture>( "/motion/goto_posture", true); restClient = nh_->serviceClient<std_srvs::Empty>( "/motion/rest", true); stopMoveClient = nh_->serviceClient<std_srvs::Empty>( "/motion/stop_move", true); INFO("Joystick remote node initialised" << std::endl); wakeUpFlag = false; moveInitFlag = false; standFlag = false; restFlag = false; standSrv.request.speed = 1.0f; } JoyRemote::~JoyRemote() { ros::shutdown(); } void JoyRemote::joyCallback(const sensor_msgs::Joy::ConstPtr& msg) { if (msg->buttons[1]) { wakeUpFlag = true; } else if (msg->buttons[2]) { moveInitFlag = true; } else if (msg->buttons[3]) { standFlag = true; } else if (msg->buttons[0]) { restFlag = true; } else { float x = msg->axes[1]; float y = msg->axes[0]; float theta = msg->axes[3]; moveSrv.request.norm_velocity.x = x; moveSrv.request.norm_velocity.y = y; moveSrv.request.norm_velocity.theta = theta; } } void JoyRemote::sendCmd() { if (wakeUpFlag) { this->wakeUp(); } else if (moveInitFlag) { this->moveInit(); } else if (standFlag) { this->stand(); } else if (restFlag) { this->rest(); } else {moveTowardClient.call(moveSrv);} } void JoyRemote::wakeUp() { wakeUpClient.call(wakeUpSrv); wakeUpFlag = false; } void JoyRemote::moveInit() { moveInitClient.call(moveInitSrv); moveInitFlag = false; } void JoyRemote::stand() { wakeUpClient.call(wakeUpSrv); standSrv.request.posture_name = "Stand"; standClient.call(standSrv); moveInitClient.call(moveInitSrv); standFlag = false; } void JoyRemote::rest() { stopMoveClient.call(stopSrv); sleep(0.25); moveInitClient.call(moveInitSrv); sleep(0.25); restClient.call(restSrv); restFlag = false; } int main(int argc, char *argv[]) { ros::init(argc, argv, "JoyRemote"); ros::NodeHandle nh; JoyRemote joyTest(&nh); ros::Rate r(5); while (ros::ok()) { joyTest.sendCmd(); ros::spinOnce(); r.sleep(); } return 0; } <|endoftext|>
<commit_before>/** * @file CommonAPIService.hpp * @author Denis Kotov * @date 3 Apr 2017 * @brief Contains CommonAPIService wrapper class for creating service * @copyright MIT License. Open source: https://github.com/redradist/Inter-Component-Communication.git */ #ifndef ICC_COMMONAPISERVICE_HPP #define ICC_COMMONAPISERVICE_HPP #include <CommonAPI/CommonAPI.hpp> #include <helpers/concept_base_of_template.hpp> namespace icc { namespace commonapi { template<typename Service> class CommonAPIService : public Service { static_assert(icc::helpers::is_base_of_template<Service, CommonAPI::Stub>::value, "Service does not derived from CommonAPI::Stub"); public: CommonAPIService() = default; CommonAPIService(const std::string &_domain, const std::string &_instance) : domain_(_domain), instance_(_instance) { registerService(domain_, instance_); } CommonAPIService(CommonAPIService const &_service) = delete; CommonAPIService(const Service &_service) = delete; ~CommonAPIService() { unregisterService(); } public: bool registerService(const std::string &_domain, const std::string &_instance) { if (!is_registered) { std::shared_ptr<CommonAPI::Runtime> runtime = CommonAPI::Runtime::get(); service_ = std::shared_ptr<Service>(this, [](Service *) { // Do nothing to prevent double deletion }); if (service_) { is_registered = runtime->registerService(_domain, _instance, service_); if (is_registered) { domain_ = _domain; instance_ = _instance; } } } return is_registered; } bool unregisterService() { if (is_registered) { std::shared_ptr<CommonAPI::Runtime> runtime = CommonAPI::Runtime::get(); if (!(is_registered = !runtime->unregisterService(domain_, this->getStubAdapter()->getInterface(), instance_))) { service_ = nullptr; } } return !is_registered; } private: bool is_registered = false; std::string domain_; std::string instance_; std::shared_ptr<Service> service_ = nullptr; }; } } #endif // ICC_COMMONAPISERVICE_HPP <commit_msg>Improved registring of services<commit_after>/** * @file CommonAPIService.hpp * @author Denis Kotov * @date 3 Apr 2017 * @brief Contains CommonAPIService wrapper class for creating service * @copyright MIT License. Open source: https://github.com/redradist/Inter-Component-Communication.git */ #ifndef ICC_COMMONAPISERVICE_HPP #define ICC_COMMONAPISERVICE_HPP #include <CommonAPI/CommonAPI.hpp> #include <helpers/concept_base_of_template.hpp> namespace icc { namespace commonapi { template<typename Service> class CommonAPIService : public Service { static_assert(icc::helpers::is_base_of_template<Service, CommonAPI::Stub>::value, "Service does not derived from CommonAPI::Stub"); public: CommonAPIService() = default; CommonAPIService(const std::string &_domain, const std::string &_instance) : domain_(_domain), instance_(_instance) { registerService(domain_, instance_); } CommonAPIService(CommonAPIService const &_service) = delete; CommonAPIService(const Service &_service) = delete; ~CommonAPIService() { unregisterService(); } public: bool registerService(const std::string &_domain, const std::string &_instance) { if (!is_registered) { std::shared_ptr<CommonAPI::Runtime> runtime = CommonAPI::Runtime::get(); service_ = std::shared_ptr<Service>(this, [](Service *) { // Do nothing to prevent double deletion }); if (service_) { is_registered = runtime->registerService(_domain, _instance, service_); if (is_registered) { domain_ = _domain; instance_ = _instance; } else { service_ = nullptr; } } } return is_registered; } bool unregisterService() { if (is_registered) { std::shared_ptr<CommonAPI::Runtime> runtime = CommonAPI::Runtime::get(); if (!(is_registered = !runtime->unregisterService(domain_, this->getStubAdapter()->getInterface(), instance_))) { service_ = nullptr; } } return !is_registered; } private: bool is_registered = false; std::string domain_; std::string instance_; std::shared_ptr<Service> service_ = nullptr; }; } } #endif // ICC_COMMONAPISERVICE_HPP <|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. ===================================================================*/ #include "mitkPluginActivator.h" #include "DicomEventHandler.h" #include <service/event/ctkEventConstants.h> #include <ctkDictionary.h> #include <mitkLogMacros.h> #include <mitkDicomSeriesReader.h> #include <mitkDataNode.h> #include <QmitkBaseFunctionalityComponent.h> #include <mitkIDataStorageService.h> #include <service/event/ctkEventAdmin.h> #include <ctkServiceReference.h> #include <mitkRenderingManager.h> DicomEventHandler::DicomEventHandler() { } DicomEventHandler::~DicomEventHandler() { } void DicomEventHandler::OnSignalAddSeriesToDataManager(const ctkEvent& ctkEvent) { QString patientName = ctkEvent.getProperty("PatientName").toString(); QString studyUID = ctkEvent.getProperty("StudyUID").toString(); QString studyName = ctkEvent.getProperty("StudyName").toString(); QString seriesUID = ctkEvent.getProperty("SeriesUID").toString(); QString seriesName = ctkEvent.getProperty("SeriesName").toString(); QString path = ctkEvent.getProperty("Path").toString(); std::list<std::string> qualifiedUIDs; mitk::DicomSeriesReader::StringContainer seriesToLoad; std::size_t found; mitk::DicomSeriesReader::UidFileNamesMap dicomSeriesMap = mitk::DicomSeriesReader::GetSeries(path.toStdString(),false); mitk::DicomSeriesReader::UidFileNamesMap::const_iterator qualifiedSeriesInstanceUIDIterator; for(qualifiedSeriesInstanceUIDIterator = dicomSeriesMap.begin(); qualifiedSeriesInstanceUIDIterator != dicomSeriesMap.end(); ++qualifiedSeriesInstanceUIDIterator) { found = qualifiedSeriesInstanceUIDIterator->first.find(seriesUID.toStdString()); if(found!= qualifiedSeriesInstanceUIDIterator->first.npos) { qualifiedUIDs.push_back(qualifiedSeriesInstanceUIDIterator->first); seriesToLoad = qualifiedSeriesInstanceUIDIterator->second; } } mitk::DataNode::Pointer node = mitk::DicomSeriesReader::LoadDicomSeries(seriesToLoad); if (node.IsNull()) { MITK_ERROR << "Could not load series: " << seriesUID.toStdString(); } else { //Get Reference for default data storage. ctkServiceReference serviceReference =mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage(); dataStorage->Add(node); // Initialize the RenderWindow mitk::TimeSlicedGeometry::Pointer geometry = dataStorage->ComputeBoundingGeometry3D(dataStorage->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geometry); } } void DicomEventHandler::OnSignalRemoveSeriesFromStorage(const ctkEvent& ctkEvent) { } void DicomEventHandler::SubscribeSlots() { ctkServiceReference ref = mitk::PluginActivator::getContext()->getServiceReference<ctkEventAdmin>(); if (ref) { ctkEventAdmin* eventAdmin = mitk::PluginActivator::getContext()->getService<ctkEventAdmin>(ref); ctkDictionary properties; properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/ADD"; eventAdmin->subscribeSlot(this, SLOT(OnSignalAddSeriesToDataManager(ctkEvent)), properties); properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/DELETED"; eventAdmin->subscribeSlot(this, SLOT(OnSignalRemoveSeriesFromStorage(ctkEvent)), properties); } } <commit_msg>avoided EventHandler to iterate over the dicom folder another time. DicomSeriesReader::GetSeries() won't be called anymore. Now LoadDicomSeries() is called directly with a list of all files from the series provided due event properies.<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. ===================================================================*/ #include "mitkPluginActivator.h" #include "DicomEventHandler.h" #include <service/event/ctkEventConstants.h> #include <ctkDictionary.h> #include <mitkLogMacros.h> #include <mitkDicomSeriesReader.h> #include <mitkDataNode.h> #include <QmitkBaseFunctionalityComponent.h> #include <mitkIDataStorageService.h> #include <service/event/ctkEventAdmin.h> #include <ctkServiceReference.h> #include <mitkRenderingManager.h> #include <QVector> DicomEventHandler::DicomEventHandler() { } DicomEventHandler::~DicomEventHandler() { } void DicomEventHandler::OnSignalAddSeriesToDataManager(const ctkEvent& ctkEvent) { QStringList listOfFilesForSeries; mitk::DicomSeriesReader::StringContainer seriesToLoad; listOfFilesForSeries = ctkEvent.getProperty("FilesForSeries").toStringList(); if (!listOfFilesForSeries.isEmpty()){ QStringListIterator it(listOfFilesForSeries); while (it.hasNext()) { seriesToLoad.push_back(it.next().toStdString()); } mitk::DataNode::Pointer node = mitk::DicomSeriesReader::LoadDicomSeries(seriesToLoad); if (node.IsNull()) { MITK_ERROR << "Error loading series: " << ctkEvent.getProperty("SeriesName").toString().toStdString() << " id: " <<ctkEvent.getProperty("SeriesUID").toString().toStdString(); } else { //Get Reference for default data storage. ctkServiceReference serviceReference =mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage(); dataStorage->Add(node); // Initialize the RenderWindow mitk::TimeSlicedGeometry::Pointer geometry = dataStorage->ComputeBoundingGeometry3D(dataStorage->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geometry); } } else { MITK_INFO << "There are no files for the current series"; } } void DicomEventHandler::OnSignalRemoveSeriesFromStorage(const ctkEvent& ctkEvent) { } void DicomEventHandler::SubscribeSlots() { ctkServiceReference ref = mitk::PluginActivator::getContext()->getServiceReference<ctkEventAdmin>(); if (ref) { ctkEventAdmin* eventAdmin = mitk::PluginActivator::getContext()->getService<ctkEventAdmin>(ref); ctkDictionary properties; properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/ADD"; eventAdmin->subscribeSlot(this, SLOT(OnSignalAddSeriesToDataManager(ctkEvent)), properties); properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/DELETED"; eventAdmin->subscribeSlot(this, SLOT(OnSignalRemoveSeriesFromStorage(ctkEvent)), properties); } } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2015 Jamis Hoo * Distributed under the MIT license * (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) * * Project: * Filename: user_fs.cc * Version: 1.0 * Author: Jamis Hoo * E-mail: hoojamis@gmail.com * Date: Jun 4, 2015 * Time: 22:52:30 * Description: main class of this GSFS *****************************************************************************/ #include "user_fs.h" #include <stdexcept> #include "bytes_order.h" // calling order of functions below: // master node: setMaster -> initDirTree -> initHost -> initTCPNetwork // slave node: initDirTree -> initHost -> initTCPNetwork void UserFS::setMaster() { _host_id = 1; } void UserFS::initHost(const std::string& addr, const uint16_t tcp_port, const uint16_t ssh_port) { boost::unique_lock< boost::shared_mutex > lock(_access); // this functions should only be called when program initializes Hosts::Host host; host.id = _host_id; host.address = addr; host.mountdir = _dir; host.tmpdir = _tmpdir; host.tcp_port = tcp_port; host.ssh_port = ssh_port; // push self's host at 0 _hosts.push(host); } // this function may throw exceptions void UserFS::initDirTree(const std::string& dir, const std::string& tmpdir) { using namespace boost::filesystem; boost::unique_lock< boost::shared_mutex > lock(_access); if (!exists(dir)) throw std::invalid_argument(dir + " not exists. "); if (!is_directory(dir)) throw std::invalid_argument(dir + " is not directory. "); if (exists(tmpdir / dir)) throw std::invalid_argument(std::string("Assert ") + path(tmpdir / dir).string() + " not exists. "); if (!is_directory(dir)) throw std::invalid_argument(dir + " is not directory. "); if (!create_directory(tmpdir / dir)) throw std::invalid_argument(std::string("Failed creating directory ") + path(tmpdir / dir).string() + "."); _tmpdir = absolute(tmpdir).string(); _dir = dir; _dir_tree.initialize(); _dir_tree.root()->type = DirTree::TreeNode::DIRECTORY; // It seems there's is a portable way to get dir size, just set it to 0 // If anybody knows how to do that, please tell me. Thanks. _dir_tree.root()->size = 0; _dir_tree.root()->host_id = _host_id; _dir_tree.root()->mtime = last_write_time(dir); _dir_tree.root()->num_links = hard_link_count(dir); std::function< void (const path&, const path&, const DirTree::TreeNode&) > traverseDirectory; traverseDirectory = [this, &traverseDirectory] (const path& dir, const path& _tmpdir, const DirTree::TreeNode& parent)->void { for (auto& f: directory_iterator(dir)) { auto file_type = symlink_status(f).type(); decltype(DirTree::TreeNode::type) treenode_type; switch (file_type) { case file_type::directory_file: treenode_type = DirTree::TreeNode::DIRECTORY; break; case file_type::regular_file: treenode_type = DirTree::TreeNode::REGULAR; break; case file_type::character_file: treenode_type = DirTree::TreeNode::CHRDEVICE; break; case file_type::block_file: treenode_type = DirTree::TreeNode::BLKDEVICE; break; case file_type::fifo_file: treenode_type = DirTree::TreeNode::FIFO; break; case file_type::symlink_file: treenode_type = DirTree::TreeNode::SYMLINK; break; case file_type::socket_file: treenode_type = DirTree::TreeNode::SOCKET; break; case file_type::type_unknown: default: treenode_type = DirTree::TreeNode::UNKNOWN; } if (treenode_type == DirTree::TreeNode::UNKNOWN) continue; else if (treenode_type == DirTree::TreeNode::DIRECTORY) { create_directory(_tmpdir / f.path()); DirTree::TreeNode dirnode; dirnode.type = treenode_type; dirnode.name = f.path().filename().string(); dirnode.size = 0; dirnode.mtime = last_write_time(f.path()); dirnode.host_id = _host_id; dirnode.num_links = hard_link_count(f.path()); auto insert_rtv = parent.children.insert(dirnode); traverseDirectory(f, _tmpdir, *(insert_rtv.first)); } else { // create hard link (src, dst) create_hard_link(f, _tmpdir / f.path()); DirTree::TreeNode filenode; filenode.type = treenode_type; filenode.name = f.path().filename().string(); filenode.size = file_size(f); filenode.mtime = last_write_time(f.path()); filenode.host_id = _host_id; // GSFS create another hard link for files except directory filenode.num_links = 1 + hard_link_count(f.path()); parent.children.insert(filenode); } } }; traverseDirectory(_dir, _tmpdir, *_dir_tree.root()); } // returns true on error bool UserFS::initTCPNetwork(const std::string& addr, const uint16_t port) { bool is_master = _host_id == 1; bool init_rtv = _tcp_manager.initialize(is_master, addr, port); if (init_rtv) return 1; _tcp_manager.start(); // push master's host if (is_master) _hosts.push(_hosts[0]); // else wait for master's recognition or rejection else { std::string dir_tree_seq; std::string host_seq; { boost::shared_lock< boost::shared_mutex > lock(_access); dir_tree_seq = DirTree::serialize(_dir_tree); host_seq = Hosts::Host::serialize(_hosts[0]); } std::string dir_tree_seq_len = host_to_network_64(dir_tree_seq.length()); std::string host_seq_len = host_to_network_64(host_seq.length()); std::string protocol_type = host_to_network_64(0x00); std::string message = protocol_type + dir_tree_seq_len + dir_tree_seq + host_seq_len + host_seq; _tcp_manager.write(message); _slave_wait_sem.wait(); } return 0; } const DirTree::TreeNode* UserFS::find(const std::string& path) { boost::shared_lock< boost::shared_mutex > lock(_access); return _dir_tree.find(path); } // returns num of bytes read on success // returns < 0 on error intmax_t UserFS::read(const uint64_t node_id, const std::string path, const size_t offset, const size_t size, char* buff) { // remote node isn't inserted into ssh manager if (!_ssh_manager.findHost(node_id)) { bool rtv = _ssh_manager.insertHost(node_id, _hosts[node_id].address, _hosts[node_id].ssh_port); if (rtv) return -1; } boost::filesystem::path remote_path = _hosts[node_id].tmpdir; remote_path /= _hosts[node_id].mountdir; remote_path /= path; std::string remote_path_string = remote_path.string(); // read local file if (node_id == _host_id) { std::ifstream fin(remote_path_string); fin.seekg(offset); fin.read(buff, size); if (fin.fail() || fin.bad()) return -1; size_t bytes_read = fin.gcount(); return bytes_read; } // read remote file return _ssh_manager.read(node_id, remote_path_string, offset, size, buff); } // send update packet to all slaves void UserFS::sendUpdate() { std::string dir_tree_seq; std::string hosts_seq; { boost::shared_lock< boost::shared_mutex > lock(_access); dir_tree_seq = DirTree::serialize(_dir_tree); hosts_seq = Hosts::serialize(_hosts); } sendUpdate(dir_tree_seq, hosts_seq); } void UserFS::sendUpdate(const std::string& dir_tree_seq, const std::string& hosts_seq) { std::string message = host_to_network_64(0x02); message += host_to_network_64(dir_tree_seq.length()); message += dir_tree_seq; message += host_to_network_64(hosts_seq.length()); message += hosts_seq; // send to all slaves _tcp_manager.write(message); } // Callback Functions for slaves' tcp manager: // slave get recognized from master void UserFS::slaveRecognized(const uint64_t slave_id, const std::string& dir_tree_seq, const std::string& hosts_seq) { // deploy dir tree DirTree merged_tree = DirTree::deserialize(dir_tree_seq); // deploy hosts _host_id = slave_id; Hosts merged_hosts = Hosts::deserialize(hosts_seq); { boost::unique_lock< boost::shared_mutex > lock(_access); _dir_tree.root()->children = merged_tree.root()->children; _hosts = merged_hosts; } // wake up main thread _slave_wait_sem.post(); } // master sent a update packet, update dirtree and hosts void UserFS::updateInfo(const std::string& dir_tree_seq, const std::string& hosts_seq) { DirTree new_tree = DirTree::deserialize(dir_tree_seq); Hosts merged_hosts = Hosts::deserialize(hosts_seq); { boost::unique_lock< boost::shared_mutex > lock(_access); _dir_tree.root()->children = new_tree.root()->children; _hosts = merged_hosts; } } // connect failed or slave disconnect from master void UserFS::disconnect() { // clear dir tree { boost::unique_lock< boost::shared_mutex > lock(_access); _dir_tree.removeNotOf(_host_id); } } // Callback Functions for master' tcp manager: // slave disconnect from master void UserFS::disconnect(const TCPMasterMessager::Connection::iterator handle) { uint64_t& slave_id = std::get<4>(*handle); // slave is initializting if (slave_id == 0) return; // remove this slave's node in dir tree { boost::unique_lock< boost::shared_mutex > lock(_access); _dir_tree.removeOf(slave_id); } slave_id = 0; sendUpdate(); } // new slave coming, chekc dirtree, allocate host_id, merge dir_tree and hosts void UserFS::newConnection(const std::string& dir_tree_seq, const std::string& host_seq, const TCPMasterMessager::Connection::iterator handle) { // deserialize DirTree slave_dir_tree = DirTree::deserialize(dir_tree_seq); Hosts::Host slave_host = Hosts::Host::deserialize(host_seq); // check conflicts std::vector<std::string> conflicts; { boost::shared_lock< boost::shared_mutex > lock(_access); conflicts = _dir_tree.hasConflict(slave_dir_tree); } // there's conflict, close connection if (conflicts.size()) return _tcp_manager.close(handle); // else // alloc slave id uint64_t slave_id = _max_host_id++; slave_host.id = slave_id; slave_dir_tree.root()->setHostID(slave_id); std::get<4>(*handle) = slave_id; { boost::unique_lock< boost::shared_mutex > lock(_access); // merge dir tree _dir_tree.merge(slave_dir_tree); // merge host _hosts.push(slave_host); } // construct response message std::string merged_dir_tree_seq; std::string merged_hosts_seq; { boost::shared_lock< boost::shared_mutex > lock(_access); merged_dir_tree_seq = DirTree::serialize(_dir_tree); merged_hosts_seq = Hosts::serialize(_hosts); } std::string merged_dir_tree_seq_len = host_to_network_64(merged_dir_tree_seq.length()); std::string merged_hosts_seq_len = host_to_network_64(merged_hosts_seq.length()); std::string protocol_type = host_to_network_64(0x01); std::string slave_id_seq = host_to_network_64(slave_id); std::string message = protocol_type + slave_id_seq + merged_dir_tree_seq_len + merged_dir_tree_seq + merged_hosts_seq_len + merged_hosts_seq; // send to slave _tcp_manager.writeTo(message, handle); sendUpdate(merged_dir_tree_seq, merged_hosts_seq); } <commit_msg>adjust indent<commit_after>/****************************************************************************** * Copyright (c) 2015 Jamis Hoo * Distributed under the MIT license * (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) * * Project: * Filename: user_fs.cc * Version: 1.0 * Author: Jamis Hoo * E-mail: hoojamis@gmail.com * Date: Jun 4, 2015 * Time: 22:52:30 * Description: main class of this GSFS *****************************************************************************/ #include "user_fs.h" #include <stdexcept> #include "bytes_order.h" // calling order of functions below: // master node: setMaster -> initDirTree -> initHost -> initTCPNetwork // slave node: initDirTree -> initHost -> initTCPNetwork void UserFS::setMaster() { _host_id = 1; } void UserFS::initHost(const std::string& addr, const uint16_t tcp_port, const uint16_t ssh_port) { boost::unique_lock< boost::shared_mutex > lock(_access); // this functions should only be called when program initializes Hosts::Host host; host.id = _host_id; host.address = addr; host.mountdir = _dir; host.tmpdir = _tmpdir; host.tcp_port = tcp_port; host.ssh_port = ssh_port; // push self's host at 0 _hosts.push(host); } // this function may throw exceptions void UserFS::initDirTree(const std::string& dir, const std::string& tmpdir) { using namespace boost::filesystem; boost::unique_lock< boost::shared_mutex > lock(_access); if (!exists(dir)) throw std::invalid_argument(dir + " not exists. "); if (!is_directory(dir)) throw std::invalid_argument(dir + " is not directory. "); if (exists(tmpdir / dir)) throw std::invalid_argument(std::string("Assert ") + path(tmpdir / dir).string() + " not exists. "); if (!is_directory(dir)) throw std::invalid_argument(dir + " is not directory. "); if (!create_directory(tmpdir / dir)) throw std::invalid_argument(std::string("Failed creating directory ") + path(tmpdir / dir).string() + "."); _tmpdir = absolute(tmpdir).string(); _dir = dir; _dir_tree.initialize(); _dir_tree.root()->type = DirTree::TreeNode::DIRECTORY; // It seems there's is a portable way to get dir size, just set it to 0 // If anybody knows how to do that, please tell me. Thanks. _dir_tree.root()->size = 0; _dir_tree.root()->host_id = _host_id; _dir_tree.root()->mtime = last_write_time(dir); _dir_tree.root()->num_links = hard_link_count(dir); std::function< void (const path&, const path&, const DirTree::TreeNode&) > traverseDirectory; traverseDirectory = [this, &traverseDirectory] (const path& dir, const path& _tmpdir, const DirTree::TreeNode& parent)->void { for (auto& f: directory_iterator(dir)) { auto file_type = symlink_status(f).type(); decltype(DirTree::TreeNode::type) treenode_type; switch (file_type) { case file_type::directory_file: treenode_type = DirTree::TreeNode::DIRECTORY; break; case file_type::regular_file: treenode_type = DirTree::TreeNode::REGULAR; break; case file_type::character_file: treenode_type = DirTree::TreeNode::CHRDEVICE; break; case file_type::block_file: treenode_type = DirTree::TreeNode::BLKDEVICE; break; case file_type::fifo_file: treenode_type = DirTree::TreeNode::FIFO; break; case file_type::symlink_file: treenode_type = DirTree::TreeNode::SYMLINK; break; case file_type::socket_file: treenode_type = DirTree::TreeNode::SOCKET; break; case file_type::type_unknown: default: treenode_type = DirTree::TreeNode::UNKNOWN; } if (treenode_type == DirTree::TreeNode::UNKNOWN) continue; else if (treenode_type == DirTree::TreeNode::DIRECTORY) { create_directory(_tmpdir / f.path()); DirTree::TreeNode dirnode; dirnode.type = treenode_type; dirnode.name = f.path().filename().string(); dirnode.size = 0; dirnode.mtime = last_write_time(f.path()); dirnode.host_id = _host_id; dirnode.num_links = hard_link_count(f.path()); auto insert_rtv = parent.children.insert(dirnode); traverseDirectory(f, _tmpdir, *(insert_rtv.first)); } else { // create hard link (src, dst) create_hard_link(f, _tmpdir / f.path()); DirTree::TreeNode filenode; filenode.type = treenode_type; filenode.name = f.path().filename().string(); filenode.size = file_size(f); filenode.mtime = last_write_time(f.path()); filenode.host_id = _host_id; // GSFS create another hard link for files except directory filenode.num_links = 1 + hard_link_count(f.path()); parent.children.insert(filenode); } } }; traverseDirectory(_dir, _tmpdir, *_dir_tree.root()); } // returns true on error bool UserFS::initTCPNetwork(const std::string& addr, const uint16_t port) { bool is_master = _host_id == 1; bool init_rtv = _tcp_manager.initialize(is_master, addr, port); if (init_rtv) return 1; _tcp_manager.start(); // push master's host if (is_master) _hosts.push(_hosts[0]); // else wait for master's recognition or rejection else { std::string dir_tree_seq; std::string host_seq; { boost::shared_lock< boost::shared_mutex > lock(_access); dir_tree_seq = DirTree::serialize(_dir_tree); host_seq = Hosts::Host::serialize(_hosts[0]); } std::string dir_tree_seq_len = host_to_network_64(dir_tree_seq.length()); std::string host_seq_len = host_to_network_64(host_seq.length()); std::string protocol_type = host_to_network_64(0x00); std::string message = protocol_type + dir_tree_seq_len + dir_tree_seq + host_seq_len + host_seq; _tcp_manager.write(message); _slave_wait_sem.wait(); } return 0; } const DirTree::TreeNode* UserFS::find(const std::string& path) { boost::shared_lock< boost::shared_mutex > lock(_access); return _dir_tree.find(path); } // returns num of bytes read on success // returns < 0 on error intmax_t UserFS::read(const uint64_t node_id, const std::string path, const size_t offset, const size_t size, char* buff) { // remote node isn't inserted into ssh manager if (!_ssh_manager.findHost(node_id)) { bool rtv = _ssh_manager.insertHost(node_id, _hosts[node_id].address, _hosts[node_id].ssh_port); if (rtv) return -1; } boost::filesystem::path remote_path = _hosts[node_id].tmpdir; remote_path /= _hosts[node_id].mountdir; remote_path /= path; std::string remote_path_string = remote_path.string(); // read local file if (node_id == _host_id) { std::ifstream fin(remote_path_string); fin.seekg(offset); fin.read(buff, size); if (fin.fail() || fin.bad()) return -1; size_t bytes_read = fin.gcount(); return bytes_read; } // read remote file return _ssh_manager.read(node_id, remote_path_string, offset, size, buff); } // send update packet to all slaves void UserFS::sendUpdate() { std::string dir_tree_seq; std::string hosts_seq; { boost::shared_lock< boost::shared_mutex > lock(_access); dir_tree_seq = DirTree::serialize(_dir_tree); hosts_seq = Hosts::serialize(_hosts); } sendUpdate(dir_tree_seq, hosts_seq); } void UserFS::sendUpdate(const std::string& dir_tree_seq, const std::string& hosts_seq) { std::string message = host_to_network_64(0x02); message += host_to_network_64(dir_tree_seq.length()); message += dir_tree_seq; message += host_to_network_64(hosts_seq.length()); message += hosts_seq; // send to all slaves _tcp_manager.write(message); } // Callback Functions for slaves' tcp manager: // slave get recognized from master void UserFS::slaveRecognized(const uint64_t slave_id, const std::string& dir_tree_seq, const std::string& hosts_seq) { // deploy dir tree DirTree merged_tree = DirTree::deserialize(dir_tree_seq); // deploy hosts _host_id = slave_id; Hosts merged_hosts = Hosts::deserialize(hosts_seq); { boost::unique_lock< boost::shared_mutex > lock(_access); _dir_tree.root()->children = merged_tree.root()->children; _hosts = merged_hosts; } // wake up main thread _slave_wait_sem.post(); } // master sent a update packet, update dirtree and hosts void UserFS::updateInfo(const std::string& dir_tree_seq, const std::string& hosts_seq) { DirTree new_tree = DirTree::deserialize(dir_tree_seq); Hosts merged_hosts = Hosts::deserialize(hosts_seq); { boost::unique_lock< boost::shared_mutex > lock(_access); _dir_tree.root()->children = new_tree.root()->children; _hosts = merged_hosts; } } // connect failed or slave disconnect from master void UserFS::disconnect() { // clear dir tree { boost::unique_lock< boost::shared_mutex > lock(_access); _dir_tree.removeNotOf(_host_id); } } // Callback Functions for master' tcp manager: // slave disconnect from master void UserFS::disconnect(const TCPMasterMessager::Connection::iterator handle) { uint64_t& slave_id = std::get<4>(*handle); // slave is initializting if (slave_id == 0) return; // remove this slave's node in dir tree { boost::unique_lock< boost::shared_mutex > lock(_access); _dir_tree.removeOf(slave_id); } slave_id = 0; sendUpdate(); } // new slave coming, chekc dirtree, allocate host_id, merge dir_tree and hosts void UserFS::newConnection(const std::string& dir_tree_seq, const std::string& host_seq, const TCPMasterMessager::Connection::iterator handle) { // deserialize DirTree slave_dir_tree = DirTree::deserialize(dir_tree_seq); Hosts::Host slave_host = Hosts::Host::deserialize(host_seq); // check conflicts std::vector<std::string> conflicts; { boost::shared_lock< boost::shared_mutex > lock(_access); conflicts = _dir_tree.hasConflict(slave_dir_tree); } // there's conflict, close connection if (conflicts.size()) return _tcp_manager.close(handle); // else // alloc slave id uint64_t slave_id = _max_host_id++; slave_host.id = slave_id; slave_dir_tree.root()->setHostID(slave_id); std::get<4>(*handle) = slave_id; { boost::unique_lock< boost::shared_mutex > lock(_access); // merge dir tree _dir_tree.merge(slave_dir_tree); // merge host _hosts.push(slave_host); } // construct response message std::string merged_dir_tree_seq; std::string merged_hosts_seq; { boost::shared_lock< boost::shared_mutex > lock(_access); merged_dir_tree_seq = DirTree::serialize(_dir_tree); merged_hosts_seq = Hosts::serialize(_hosts); } std::string merged_dir_tree_seq_len = host_to_network_64(merged_dir_tree_seq.length()); std::string merged_hosts_seq_len = host_to_network_64(merged_hosts_seq.length()); std::string protocol_type = host_to_network_64(0x01); std::string slave_id_seq = host_to_network_64(slave_id); std::string message = protocol_type + slave_id_seq + merged_dir_tree_seq_len + merged_dir_tree_seq + merged_hosts_seq_len + merged_hosts_seq; // send to slave _tcp_manager.writeTo(message, handle); sendUpdate(merged_dir_tree_seq, merged_hosts_seq); } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbVirtualDimensionality.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbStreamingStatisticsVectorImageFilter.h" const unsigned int Dimension = 2; typedef double PixelType; typedef otb::VectorImage<PixelType, Dimension> ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::StreamingStatisticsVectorImageFilter<ImageType> StreamingStatisticsVectorImageFilterType; typedef otb::VirtualDimensionality<double> VDType; int otbVirtualDimensionalityNewTest(int argc, char * argv[]) { VDType::Pointer vd = VDType::New(); std::cout << vd << std::endl; return EXIT_SUCCESS; } int otbVirtualDimensionalityTest(int argc, char * argv[]) { const char * infname = argv[1]; const char * outfname = argv[2]; double far = atof(argv[3]); // False Alarm Rate StreamingStatisticsVectorImageFilterType::Pointer stats = StreamingStatisticsVectorImageFilterType::New(); ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(infname); stats->SetInput(reader->GetOutput()); stats->Update(); VDType::Pointer vd = VDType::New(); vd->SetCovariance(stats->GetCovariance().GetVnlMatrix()); vd->SetCorrelation(stats->GetCorrelation().GetVnlMatrix()); vd->SetNumberOfPixels(reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels()); std::ofstream file; file.open(outfname); file.precision(5); for (int i = 2; i < 10; ++i) { double far = vcl_pow(static_cast<double>(10),static_cast<double>(-i)); vd->SetFAR(far); vd->Compute(); std::cout << "FAR : 1E-" << i << " -> Nb Endmembers: " << vd->GetNumberOfEndmembers() << std::endl; file << "FAR : 1E-" << i << " -> Nb Endmembers: " << vd->GetNumberOfEndmembers() << std::endl; } file.close(); return EXIT_SUCCESS; } <commit_msg>STYLE<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbVirtualDimensionality.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbStreamingStatisticsVectorImageFilter.h" const unsigned int Dimension = 2; typedef double PixelType; typedef otb::VectorImage<PixelType, Dimension> ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::StreamingStatisticsVectorImageFilter<ImageType> StreamingStatisticsVectorImageFilterType; typedef otb::VirtualDimensionality<double> VDType; int otbVirtualDimensionalityNewTest(int argc, char * argv[]) { VDType::Pointer vd = VDType::New(); std::cout << vd << std::endl; return EXIT_SUCCESS; } int otbVirtualDimensionalityTest(int argc, char * argv[]) { const char * infname = argv[1]; const char * outfname = argv[2]; double far = atof(argv[3]); // False Alarm Rate StreamingStatisticsVectorImageFilterType::Pointer stats = StreamingStatisticsVectorImageFilterType::New(); ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(infname); stats->SetInput(reader->GetOutput()); stats->Update(); VDType::Pointer vd = VDType::New(); vd->SetCovariance(stats->GetCovariance().GetVnlMatrix()); vd->SetCorrelation(stats->GetCorrelation().GetVnlMatrix()); vd->SetNumberOfPixels(reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels()); std::ofstream file; file.open(outfname); file.precision(5); for (int i = 2; i < 10; ++i) { double far = vcl_pow(static_cast<double>(10), static_cast<double>(-i)); vd->SetFAR(far); vd->Compute(); std::cout << "FAR : 1E-" << i << " -> Nb Endmembers: " << vd->GetNumberOfEndmembers() << std::endl; file << "FAR : 1E-" << i << " -> Nb Endmembers: " << vd->GetNumberOfEndmembers() << std::endl; } file.close(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#ifndef EBITEN_GRAPHICS_TEXTURE_HPP #define EBITEN_GRAPHICS_TEXTURE_HPP #include "ebiten/platform.hpp" #ifdef EBITEN_MACOSX #include "ebiten/graphics/detail/opengl/texture_id.hpp" #endif namespace ebiten { namespace graphics { typedef detail::texture_id texture_id; class texture { private: texture_id id_; std::size_t width_; std::size_t height_; public: // TODO: Is 0 a magic number? texture() : id_(0), width_(0), height_(0) { } texture(texture const&) = default; texture& operator=(texture const&) = default; texture(texture_id const& id_, std::size_t width_, std::size_t height_) : id_(id_), width_(width_), height_(height_) { } texture_id id() const { return this->id_; } std::size_t width() const { return this->width_; } std::size_t height() const { return this->height_; } operator bool() const { return this->id_ != 0; } }; } } #endif <commit_msg>Added comments<commit_after>#ifndef EBITEN_GRAPHICS_TEXTURE_HPP #define EBITEN_GRAPHICS_TEXTURE_HPP #include "ebiten/platform.hpp" #ifdef EBITEN_MACOSX #include "ebiten/graphics/detail/opengl/texture_id.hpp" #endif namespace ebiten { namespace graphics { typedef detail::texture_id texture_id; class texture { private: texture_id id_; std::size_t width_; std::size_t height_; public: // TODO: Is 0 a magic number? texture() : id_(0), width_(0), height_(0) { } texture(texture const&) = default; texture& operator=(texture const&) = default; texture(texture_id const& id_, std::size_t width_, std::size_t height_) : id_(id_), width_(width_), height_(height_) { } texture_id id() const { return this->id_; } std::size_t width() const { return this->width_; } std::size_t height() const { return this->height_; } operator bool() const { return this->id_ != 0; } }; } } // TODO: implement operator= (with nullptr), swap, and so on? #endif <|endoftext|>