text
stringlengths
54
60.6k
<commit_before>/*! @file @copyright Edouard Alligand and Joel Falcou 2015-2017 (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_BRIGAND_TYPES_INHERIT_HPP #define BOOST_BRIGAND_TYPES_INHERIT_HPP #include <brigand/types/empty_base.hpp> namespace brigand { template<typename... Ts> struct inherit; template<typename T> struct inherit<T> { struct type : public T {}; }; template<> struct inherit<> { using type = empty_base; }; template<> struct inherit<empty_base> { using type = empty_base; }; template<typename T1, typename T2> struct inherit<T1,T2> { struct type : public T1, T2 {}; }; template<typename T1> struct inherit<T1,empty_base> { using type = T1; }; template<typename T2> struct inherit<empty_base,T2> { using type = T2; }; template<> struct inherit<empty_base,empty_base> { using type = empty_base; }; template<typename T1, typename T2, typename T3, typename... Ts> struct inherit<T1, T2, T3, Ts...> : inherit<T1, typename inherit<T2,typename inherit<T3, Ts...>::type>::type> {}; } #endif <commit_msg>Delete inherit.hpp<commit_after><|endoftext|>
<commit_before>#include "Object.hpp" void Object::add_coordinates(float x, float y, COORDINATE_TYPE type) { if(type == WINDOW) return _window_coordinates.push_back(Coordinate(x, y)); _world_coordinates.push_back(Coordinate(x, y)); } void Object::add_coordinates(Coordinate coord, COORDINATE_TYPE type) { if(type == WINDOW) return _window_coordinates.push_back(coord); _world_coordinates.push_back(coord); } void Object::add_coordinates(std::vector<Coordinate> coord, COORDINATE_TYPE type) { if(type == WINDOW){ _window_coordinates = coord; return; } _world_coordinates = coord; } void Object::update_coordinate(Coordinate coord, int pos) { _world_coordinates[pos] = coord; } Coordinate Object::center_point() { auto n = _world_coordinates.size(); float sum_x = 0; float sum_y = 0; for (auto i = 0u; i < n; ++i) { sum_x += _world_coordinates[i].x(); sum_y += _world_coordinates[i].y(); } return Coordinate((sum_x / n), (sum_y / n)); } /** * Given a curve, returns a vector with all the small segmentes needed to draw * it on the viewport. */ std::vector<Line*> Curve::get_segments() { if (_segments.empty()) { for (auto t = 1e-3; t < 1; t += _step) { Coordinate p1 = get_point(t); Coordinate p2 = get_point(t + _step); auto line = new Line("Curve segment", LINE); line->add_coordinates({p1, p2}, WORLD); _segments.push_back(line); } } return _segments; } void Curve::set_segments(std::vector<Line*> segments) { _segments = segments; } Coordinate Bezier::get_point(float t) { auto p = world_coordinate(); auto x = bezier(t, p[0].x(), p[1].x(), p[2].x(), p[3].x()); auto y = bezier(t, p[0].y(), p[1].y(), p[2].y(), p[3].y()); return Coordinate(x, y); } float Bezier::bezier(float t, float p1n, float p2n, float p3n, float p4n) { float t3 = pow(t, 3); float t2 = pow(t, 2); return (p1n * (-1 * t3 + 3 * t2 - 3 * t + 1)) + (p2n * (3 * t3 - 6 * t2 + 3 * t)) + (p3n * (-3 * t3 + 3 * t2)) + (p4n * t3); } Coordinate Spline::get_point(float t) { auto p = world_coordinate(); auto x = spline(t, p[0].x(), p[1].x(), p[2].x(), p[3].x()); auto y = spline(t, p[0].y(), p[1].y(), p[2].y(), p[3].y()); return Coordinate(x, y); } float Spline::spline(float t, float p1n, float p2n, float p3n, float p4n) { /* TODO */ float t3 = pow(t, 3); float t2 = pow(t, 2); return (p1n * (-1 * t3 + 3 * t2 - 3 * t + 1)) + (p2n * (3 * t3 - 6 * t2 + 3 * t)) + (p3n * (-3 * t3 + 3 * t)) + (p4n * (t3 + 4 * t2 + t)); } <commit_msg>[WIP] B-Spline using blending functions<commit_after>#include "Object.hpp" void Object::add_coordinates(float x, float y, COORDINATE_TYPE type) { if(type == WINDOW) return _window_coordinates.push_back(Coordinate(x, y)); _world_coordinates.push_back(Coordinate(x, y)); } void Object::add_coordinates(Coordinate coord, COORDINATE_TYPE type) { if(type == WINDOW) return _window_coordinates.push_back(coord); _world_coordinates.push_back(coord); } void Object::add_coordinates(std::vector<Coordinate> coord, COORDINATE_TYPE type) { if(type == WINDOW){ _window_coordinates = coord; return; } _world_coordinates = coord; } void Object::update_coordinate(Coordinate coord, int pos) { _world_coordinates[pos] = coord; } Coordinate Object::center_point() { auto n = _world_coordinates.size(); float sum_x = 0; float sum_y = 0; for (auto i = 0u; i < n; ++i) { sum_x += _world_coordinates[i].x(); sum_y += _world_coordinates[i].y(); } return Coordinate((sum_x / n), (sum_y / n)); } /** * Given a curve, returns a vector with all the small segmentes needed to draw * it on the viewport. */ std::vector<Line*> Curve::get_segments() { if (_segments.empty()) { for (auto t = 1e-3; t < 1; t += _step) { Coordinate p1 = get_point(t); Coordinate p2 = get_point(t + _step); auto line = new Line("Curve segment", LINE); line->add_coordinates({p1, p2}, WORLD); _segments.push_back(line); } } return _segments; } void Curve::set_segments(std::vector<Line*> segments) { _segments = segments; } Coordinate Bezier::get_point(float t) { auto p = world_coordinate(); auto x = bezier(t, p[0].x(), p[1].x(), p[2].x(), p[3].x()); auto y = bezier(t, p[0].y(), p[1].y(), p[2].y(), p[3].y()); return Coordinate(x, y); } float Bezier::bezier(float t, float p1n, float p2n, float p3n, float p4n) { float t3 = pow(t, 3); float t2 = pow(t, 2); return (p1n * (-1 * t3 + 3 * t2 - 3 * t + 1)) + (p2n * (3 * t3 - 6 * t2 + 3 * t)) + (p3n * (-3 * t3 + 3 * t2)) + (p4n * t3); } Coordinate Spline::get_point(float t) { auto p = world_coordinate(); auto x = spline(t, p[0].x(), p[1].x(), p[2].x(), p[3].x()); auto y = spline(t, p[0].y(), p[1].y(), p[2].y(), p[3].y()); return Coordinate(x, y); } float Spline::spline(float t, float p1n, float p2n, float p3n, float p4n) { /* TODO */ float t3 = pow(t, 3); float t2 = pow(t, 2); return ((p1n * (-1 * t3 + 3 * t2 - 3 * t + 1)) + (p2n * (3 * t3 - 6 * t2 + 3 * t)) + (p3n * (-3 * t3 + 3 * t)) + (p4n * (t3 + 4 * t2 + t))) / 6; } <|endoftext|>
<commit_before>/* * Copyright (c) 2014 - 2015 Kulykov Oleh <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdlib.h> #include <assert.h> #if defined(CMAKE_BUILD) #undef CMAKE_BUILD #endif #if defined(__BUILDING_RECORE_DYNAMIC_LIBRARY__) #undef __BUILDING_RECORE_DYNAMIC_LIBRARY__ #endif #include <fayecpp.h> #if defined(HAVE_FAYECPP_CONFIG_H) #include "fayecpp_config.h" #endif #if defined(CMAKE_BUILD) #undef CMAKE_BUILD #endif #if defined(RE_HAVE_UNISTD_H) #include <unistd.h> #endif #if !defined(__RE_HAVE_THREADS__) && defined(__RE_OS_WINDOWS__) #include <Windows.h> #define __RE_THREADING_WINDOWS__ 1 #define __RE_HAVE_THREADS__ 1 #endif #if !defined(__RE_HAVE_THREADS__) && defined(RE_HAVE_PTHREAD_H) #include <pthread.h> #define __RE_THREADING_PTHREAD__ 1 #define __RE_HAVE_THREADS__ 1 #endif #if defined(__RE_THREADING_PTHREAD__) #define LOCK_MUTEX(mPtr) pthread_mutex_lock(mPtr); #define UNLOCK_MUTEX(mPtr) pthread_mutex_unlock(mPtr); #elif defined(__RE_THREADING_WINDOWS__) #define LOCK_MUTEX(mPtr) TryEnterCriticalSection(mPtr); #define UNLOCK_MUTEX(mPtr) LeaveCriticalSection(mPtr); #endif #ifndef SAFE_DELETE #define SAFE_DELETE(o) if(o){delete o;o=NULL;} #endif #ifndef SAFE_FREE #define SAFE_FREE(m) if(m){free((void *)m);m=NULL;} #endif using namespace FayeCpp; class FayeDelegate; static Client * _client = NULL; static FayeDelegate * _delegate = NULL; static int _result = EXIT_SUCCESS; #define STEP_WAIT 0 #define STEP_CONNECT 1 static int _step = STEP_CONNECT; static int _subscribedChannels = 0; class FayeDelegate : public FayeCpp::Delegate { public: virtual void onFayeTransportConnected(FayeCpp::Client * client) { RELog::log("DELEGATE onFayeTransportConnected"); } virtual void onFayeTransportDisconnected(FayeCpp::Client * client) { RELog::log("DELEGATE onFayeTransportDisconnected"); _result++; SAFE_DELETE(_client) } virtual void onFayeClientConnected(FayeCpp::Client * client) { RELog::log("DELEGATE onFayeClientConnected"); RELog::log("Start connecting OK"); } virtual void onFayeClientDisconnected(FayeCpp::Client * client) { RELog::log("DELEGATE onFayeClientDisconnected"); _result++; SAFE_DELETE(_client) } virtual void onFayeClientSubscribedToChannel(FayeCpp::Client * client, const FayeCpp::REString & channel) { RELog::log("DELEGATE onFayeClientSubscribedToChannel: %s", channel.UTF8String()); if ((++_subscribedChannels) == 2) { SAFE_DELETE(_client) } } virtual void onFayeClientUnsubscribedFromChannel(FayeCpp::Client * client, const FayeCpp::REString & channel) { RELog::log("DELEGATE onFayeClientUnsubscribedFromChannel"); } virtual void onFayeClientReceivedMessageFromChannel(FayeCpp::Client * client, const FayeCpp::REVariantMap & message, const FayeCpp::REString & channel) { RELog::log("DELEGATE onFayeClientReceivedMessageFromChannel"); } virtual void onFayeClientWillSendMessage(FayeCpp::Client * client, FayeCpp::REVariantMap & message) { RELog::log("DELEGATE onFayeClientWillSendMessage"); } virtual void onFayeClientWillReceiveMessage(FayeCpp::Client * client, FayeCpp::REVariantMap & message) { RELog::log("DELEGATE onFayeClientWillReceiveMessage"); } virtual void onFayeErrorString(FayeCpp::Client * client, const FayeCpp::REString & errorString) { RELog::log("DELEGATE ERROR: %s", errorString.UTF8String()); _result++; SAFE_DELETE(_client) } FayeDelegate() { } virtual ~FayeDelegate() { } }; int main(int argc, char* argv[]) { RELog::log("Client info: %s", Client::info()); RELog::log("Start test"); _client = new Client(); if (!_client) return (++_result); _delegate = new FayeDelegate(); if (!_delegate) return (++_result); while (_client && _delegate) { switch (_step) { case STEP_CONNECT: RELog::log("Start connecting ..."); _step = STEP_WAIT; _client->setExtValue("Some ext value"); _client->setUsingIPV6(false); _client->setUrl("xxxxx://xxxxxxxxxxxxxx:80/faye"); _client->setDelegate(_delegate); _client->connect(); _client->subscribeToChannel("/xxxxxxxxxxx"); _client->subscribeToChannel("/xxxxxx/xxxxxxxxx"); break; default: break; } #if defined(__RE_THREADING_WINDOWS__) Sleep(10); #elif defined(__RE_THREADING_PTHREAD__) && defined(HAVE_FUNCTION_USLEEP) usleep(100); #endif } SAFE_DELETE(_client) SAFE_DELETE(_delegate) return 0; // return _result; } <commit_msg>Delay in connection test<commit_after>/* * Copyright (c) 2014 - 2015 Kulykov Oleh <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdlib.h> #include <assert.h> #if defined(CMAKE_BUILD) #undef CMAKE_BUILD #endif #if defined(__BUILDING_RECORE_DYNAMIC_LIBRARY__) #undef __BUILDING_RECORE_DYNAMIC_LIBRARY__ #endif #include <fayecpp.h> #if defined(HAVE_FAYECPP_CONFIG_H) #include "fayecpp_config.h" #endif #if defined(CMAKE_BUILD) #undef CMAKE_BUILD #endif #if defined(RE_HAVE_UNISTD_H) #include <unistd.h> #endif #if !defined(__RE_HAVE_THREADS__) && defined(__RE_OS_WINDOWS__) #include <Windows.h> #define __RE_THREADING_WINDOWS__ 1 #define __RE_HAVE_THREADS__ 1 #endif #if !defined(__RE_HAVE_THREADS__) && defined(RE_HAVE_PTHREAD_H) #include <pthread.h> #define __RE_THREADING_PTHREAD__ 1 #define __RE_HAVE_THREADS__ 1 #endif #if defined(__RE_THREADING_PTHREAD__) #define LOCK_MUTEX(mPtr) pthread_mutex_lock(mPtr); #define UNLOCK_MUTEX(mPtr) pthread_mutex_unlock(mPtr); #elif defined(__RE_THREADING_WINDOWS__) #define LOCK_MUTEX(mPtr) TryEnterCriticalSection(mPtr); #define UNLOCK_MUTEX(mPtr) LeaveCriticalSection(mPtr); #endif #ifndef SAFE_DELETE #define SAFE_DELETE(o) if(o){delete o;o=NULL;} #endif #ifndef SAFE_FREE #define SAFE_FREE(m) if(m){free((void *)m);m=NULL;} #endif using namespace FayeCpp; class FayeDelegate; static Client * _client = NULL; static FayeDelegate * _delegate = NULL; static int _result = EXIT_SUCCESS; #define STEP_WAIT 0 #define STEP_CONNECT 1 static int _step = STEP_CONNECT; static int _subscribedChannels = 0; class FayeDelegate : public FayeCpp::Delegate { public: virtual void onFayeTransportConnected(FayeCpp::Client * client) { RELog::log("DELEGATE onFayeTransportConnected"); } virtual void onFayeTransportDisconnected(FayeCpp::Client * client) { RELog::log("DELEGATE onFayeTransportDisconnected"); _result++; SAFE_DELETE(_client) } virtual void onFayeClientConnected(FayeCpp::Client * client) { RELog::log("DELEGATE onFayeClientConnected"); RELog::log("Start connecting OK"); } virtual void onFayeClientDisconnected(FayeCpp::Client * client) { RELog::log("DELEGATE onFayeClientDisconnected"); _result++; SAFE_DELETE(_client) } virtual void onFayeClientSubscribedToChannel(FayeCpp::Client * client, const FayeCpp::REString & channel) { RELog::log("DELEGATE onFayeClientSubscribedToChannel: %s", channel.UTF8String()); if ((++_subscribedChannels) == 2) { SAFE_DELETE(_client) } } virtual void onFayeClientUnsubscribedFromChannel(FayeCpp::Client * client, const FayeCpp::REString & channel) { RELog::log("DELEGATE onFayeClientUnsubscribedFromChannel"); } virtual void onFayeClientReceivedMessageFromChannel(FayeCpp::Client * client, const FayeCpp::REVariantMap & message, const FayeCpp::REString & channel) { RELog::log("DELEGATE onFayeClientReceivedMessageFromChannel"); } virtual void onFayeClientWillSendMessage(FayeCpp::Client * client, FayeCpp::REVariantMap & message) { RELog::log("DELEGATE onFayeClientWillSendMessage"); } virtual void onFayeClientWillReceiveMessage(FayeCpp::Client * client, FayeCpp::REVariantMap & message) { RELog::log("DELEGATE onFayeClientWillReceiveMessage"); } virtual void onFayeErrorString(FayeCpp::Client * client, const FayeCpp::REString & errorString) { RELog::log("DELEGATE ERROR: %s", errorString.UTF8String()); _result++; SAFE_DELETE(_client) } FayeDelegate() { } virtual ~FayeDelegate() { } }; int main(int argc, char* argv[]) { RELog::log("Client info: %s", Client::info()); RELog::log("Start test"); _client = new Client(); if (!_client) return (++_result); _delegate = new FayeDelegate(); if (!_delegate) return (++_result); while (_client && _delegate) { switch (_step) { case STEP_CONNECT: RELog::log("Start connecting ..."); _step = STEP_WAIT; _client->setExtValue("Some ext value"); _client->setUsingIPV6(false); _client->setUrl("xxxxx://xxxxxxxxxxxxxx:80/faye"); _client->setDelegate(_delegate); _client->connect(); _client->subscribeToChannel("/xxxxxxxxxxx"); _client->subscribeToChannel("/xxxxxx/xxxxxxxxx"); break; default: break; } #if defined(__RE_THREADING_WINDOWS__) Sleep(10); #elif defined(__RE_THREADING_PTHREAD__) && defined(RE_HAVE_FUNCTION_USLEEP) usleep(100); #endif } SAFE_DELETE(_client) SAFE_DELETE(_delegate) return 0; // return _result; } <|endoftext|>
<commit_before>#ifndef CORDIC_HH #define CORDIC_HH #include <vpp/vpp.hh> #include <eigen3/Eigen/Core> using namespace vpp; using namespace std; using namespace Eigen; #define cordic_1K 0x26DD3B6A #define half_pi 0x6487ED51 #define MUL 1073741824.000000 #define CORDIC_NTAB 32 int cordic_ctab [] = {0x3243F6A8, 0x1DAC6705, 0x0FADBAFC, 0x07F56EA6, 0x03FEAB76, 0x01FFD55B, 0x00FFFAAA, 0x007FFF55, 0x003FFFEA, 0x001FFFFD, 0x000FFFFF, 0x0007FFFF, 0x0003FFFF, 0x0001FFFF, 0x0000FFFF, 0x00007FFF, 0x00003FFF, 0x00001FFF, 0x00000FFF, 0x000007FF, 0x000003FF, 0x000001FF, 0x000000FF, 0x0000007F, 0x0000003F, 0x0000001F, 0x0000000F, 0x00000008, 0x00000004, 0x00000002, 0x00000001, 0x00000000, }; #endif // CORDIC_HH <commit_msg>Update Cordic<commit_after>#ifndef CORDIC_HH #define CORDIC_HH #include <vpp/vpp.hh> #include <Eigen/Core> using namespace vpp; using namespace std; using namespace Eigen; #define cordic_1K 0x26DD3B6A #define half_pi 0x6487ED51 #define MUL 1073741824.000000 #define CORDIC_NTAB 32 int cordic_ctab [] = {0x3243F6A8, 0x1DAC6705, 0x0FADBAFC, 0x07F56EA6, 0x03FEAB76, 0x01FFD55B, 0x00FFFAAA, 0x007FFF55, 0x003FFFEA, 0x001FFFFD, 0x000FFFFF, 0x0007FFFF, 0x0003FFFF, 0x0001FFFF, 0x0000FFFF, 0x00007FFF, 0x00003FFF, 0x00001FFF, 0x00000FFF, 0x000007FF, 0x000003FF, 0x000001FF, 0x000000FF, 0x0000007F, 0x0000003F, 0x0000001F, 0x0000000F, 0x00000008, 0x00000004, 0x00000002, 0x00000001, 0x00000000, }; #endif // CORDIC_HH <|endoftext|>
<commit_before>/* Copyright 2008 Brain Research Institute, Melbourne, Australia Written by J-Donald Tournier, 27/06/08. This file is part of MRtrix. MRtrix 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. MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include "command.h" #include "progressbar.h" #include "image.h" #include "algo/threaded_copy.h" #include "adapter/extract.h" #include "adapter/permute_axes.h" #include "dwi/gradient.h" using namespace MR; using namespace App; void usage () { DESCRIPTION + "perform conversion between different file types and optionally " "extract a subset of the input image." + "If used correctly, this program can be a very useful workhorse. " "In addition to converting images between different formats, it can " "be used to extract specific studies from a data set, extract a " "specific region of interest, or flip the images."; ARGUMENTS + Argument ("input", "the input image.").type_image_in () + Argument ("output", "the output image.").type_image_out (); OPTIONS + Option ("coord", "extract data from the input image only at the coordinates specified.") .allow_multiple() + Argument ("axis").type_integer (0, 0, std::numeric_limits<int>::max()) + Argument ("coord").type_sequence_int() + Option ("vox", "change the voxel dimensions of the output image. The new sizes should " "be provided as a comma-separated list of values. Only those values " "specified will be changed. For example: 1,,3.5 will change the voxel " "size along the x & z axes, and leave the y-axis voxel size unchanged.") + Argument ("sizes").type_sequence_float() + Option ("axes", "specify the axes from the input image that will be used to form the output " "image. This allows the permutation, ommission, or addition of axes into the " "output image. The axes should be supplied as a comma-separated list of axes. " "Any ommitted axes must have dimension 1. Axes can be inserted by supplying " "-1 at the corresponding position in the list.") + Argument ("axes").type_sequence_int() + Stride::Options + DataType::options() + DWI::GradImportOptions (false) + DWI::GradExportOptions(); } typedef cfloat complex_type; template <class HeaderType> inline std::vector<int> set_header (Header& header, const HeaderType& input) { header = input.header(); header.intensity_offset() = 0.0; header.intensity_scale() = 1.0; if (get_options ("grad").size() || get_options ("fslgrad").size()) header.set_DW_scheme (DWI::get_DW_scheme<default_type> (header)); Options opt = get_options ("axes"); std::vector<int> axes; if (opt.size()) { axes = opt[0][0]; header.set_ndim (axes.size()); for (size_t i = 0; i < axes.size(); ++i) { if (axes[i] >= static_cast<int> (input.ndim())) throw Exception ("axis supplied to option -axes is out of bounds"); header.size(i) = axes[i] < 0 ? 1 : input.size (axes[i]); } } opt = get_options ("vox"); if (opt.size()) { std::vector<default_type> vox = opt[0][0]; if (vox.size() > header.ndim()) throw Exception ("too many axes supplied to -vox option"); for (size_t n = 0; n < vox.size(); ++n) { if (std::isfinite (vox[n])) header.voxsize(n) = vox[n]; } } Stride::set_from_command_line (header); return axes; } template <class InputImageType> inline void copy_permute (InputImageType& in, Header& header, const std::string& output_filename) { DataType datatype = header.datatype(); std::vector<int> axes = set_header (header, in); header.datatype() = datatype; auto out = header.create (output_filename).get_image<complex_type>(); DWI::export_grad_commandline (out.header()); if (axes.size()) { Adapter::PermuteAxes<InputImageType> perm (in, axes); threaded_copy_with_progress (perm, out, 2); } else threaded_copy_with_progress (in, out, 2); } void run () { auto in = Header::open (argument[0]).get_image<complex_type>(); Header header (in.header()); header.datatype() = DataType::from_command_line (header.datatype()); if (in.datatype().is_complex() && !header.datatype().is_complex()) WARN ("requested datatype is real but input datatype is complex - imaginary component will be ignored"); Options opt = get_options ("coord"); if (opt.size()) { std::vector<std::vector<int> > pos (in.ndim()); for (size_t n = 0; n < opt.size(); n++) { int axis = opt[n][0]; if (pos[axis].size()) throw Exception ("\"coord\" option specified twice for axis " + str (axis)); pos[axis] = parse_ints (opt[n][1], in.size(axis)-1); if (axis == 3 && in.header().keyval().find("dw_scheme") != in.header().keyval().end()) { auto grad = in.header().parse_DW_scheme<default_type>(); if ((int)grad.rows() != in.size(3)) { WARN ("Diffusion encoding of input file does not match number of image volumes; omitting gradient information from output image"); header.keyval().erase ("dw_scheme"); } else { Math::Matrix<default_type> extract_grad (pos[3].size(), 4); for (size_t dir = 0; dir != pos[3].size(); ++dir) extract_grad.row(dir) = grad.row((pos[3])[dir]); header.set_DW_scheme (extract_grad); } } } for (size_t n = 0; n < in.ndim(); ++n) { if (pos[n].empty()) { pos[n].resize (in.size (n)); for (size_t i = 0; i < pos[n].size(); i++) pos[n][i] = i; } } Adapter::Extract<decltype(in)> extract (in, pos); copy_permute (extract, header, argument[1]); } else copy_permute (in, header, argument[1]); } <commit_msg>revert mrconvert to master version to ease later merges<commit_after>/* Copyright 2008 Brain Research Institute, Melbourne, Australia Written by J-Donald Tournier, 27/06/08. This file is part of MRtrix. MRtrix 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. MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include "command.h" #include "progressbar.h" #include "image/buffer.h" #include "image/voxel.h" #include "image/axis.h" #include "image/threaded_copy.h" #include "image/adapter/extract.h" #include "image/adapter/permute_axes.h" #include "image/stride.h" #include "dwi/gradient.h" using namespace MR; using namespace App; void usage () { DESCRIPTION + "perform conversion between different file types and optionally " "extract a subset of the input image." + "If used correctly, this program can be a very useful workhorse. " "In addition to converting images between different formats, it can " "be used to extract specific studies from a data set, extract a " "specific region of interest, or flip the images."; ARGUMENTS + Argument ("input", "the input image.").type_image_in () + Argument ("output", "the output image.").type_image_out (); OPTIONS + Option ("coord", "extract data from the input image only at the coordinates specified.") .allow_multiple() + Argument ("axis").type_integer (0, 0, std::numeric_limits<int>::max()) + Argument ("coord").type_sequence_int() + Option ("vox", "change the voxel dimensions of the output image. The new sizes should " "be provided as a comma-separated list of values. Only those values " "specified will be changed. For example: 1,,3.5 will change the voxel " "size along the x & z axes, and leave the y-axis voxel size unchanged.") + Argument ("sizes").type_sequence_float() + Option ("axes", "specify the axes from the input image that will be used to form the output " "image. This allows the permutation, ommission, or addition of axes into the " "output image. The axes should be supplied as a comma-separated list of axes. " "Any ommitted axes must have dimension 1. Axes can be inserted by supplying " "-1 at the corresponding position in the list.") + Argument ("axes").type_sequence_int() + Image::Stride::StrideOption + DataType::options() + DWI::GradImportOptions (false) + DWI::GradExportOptions(); } typedef cfloat complex_type; template <class InfoType> inline std::vector<int> set_header (Image::Header& header, const InfoType& input) { header.info() = input.info(); header.intensity_offset() = 0.0; header.intensity_scale() = 1.0; if (get_options ("grad").size() || get_options ("fslgrad").size()) header.DW_scheme() = DWI::get_DW_scheme<float> (header); Options opt = get_options ("axes"); std::vector<int> axes; if (opt.size()) { axes = opt[0][0]; header.set_ndim (axes.size()); for (size_t i = 0; i < axes.size(); ++i) { if (axes[i] >= static_cast<int> (input.ndim())) throw Exception ("axis supplied to option -axes is out of bounds"); header.dim(i) = axes[i] < 0 ? 1 : input.dim (axes[i]); } } opt = get_options ("vox"); if (opt.size()) { std::vector<float> vox = opt[0][0]; if (vox.size() > header.ndim()) throw Exception ("too many axes supplied to -vox option"); for (size_t n = 0; n < vox.size(); ++n) { if (std::isfinite (vox[n])) header.vox(n) = vox[n]; } } Image::Stride::set_from_command_line (header); return axes; } template <class InputVoxelType> inline void copy_permute (InputVoxelType& in, Image::Header& header_out, const std::string& output_filename) { DataType datatype = header_out.datatype(); std::vector<int> axes = set_header (header_out, in); header_out.datatype() = datatype; Image::Buffer<complex_type> buffer_out (output_filename, header_out); DWI::export_grad_commandline (buffer_out); auto out = buffer_out.voxel(); if (axes.size()) { Image::Adapter::PermuteAxes<InputVoxelType> perm (in, axes); Image::threaded_copy_with_progress (perm, out, 2); } else Image::threaded_copy_with_progress (in, out, 2); } void run () { Image::Header header_in (argument[0]); Image::Buffer<complex_type> buffer_in (header_in); auto in = buffer_in.voxel(); Image::Header header_out (header_in); header_out.datatype() = DataType::from_command_line (header_out.datatype()); if (header_in.datatype().is_complex() && !header_out.datatype().is_complex()) WARN ("requested datatype is real but input datatype is complex - imaginary component will be ignored"); Options opt = get_options ("coord"); if (opt.size()) { std::vector<std::vector<int> > pos (buffer_in.ndim()); for (size_t n = 0; n < opt.size(); n++) { int axis = opt[n][0]; if (pos[axis].size()) throw Exception ("\"coord\" option specified twice for axis " + str (axis)); pos[axis] = parse_ints (opt[n][1], buffer_in.dim(axis)-1); if (axis == 3 && header_in.DW_scheme().is_set()) { Math::Matrix<float>& grad (header_in.DW_scheme()); if ((int)grad.rows() != header_in.dim(3)) { WARN ("Diffusion encoding of input file does not match number of image volumes; omitting gradient information from output image"); header_out.DW_scheme().clear(); } else { Math::Matrix<float> extract_grad (pos[3].size(), 4); for (size_t dir = 0; dir != pos[3].size(); ++dir) extract_grad.row(dir) = grad.row((pos[3])[dir]); header_out.DW_scheme() = extract_grad; } } } for (size_t n = 0; n < buffer_in.ndim(); ++n) { if (pos[n].empty()) { pos[n].resize (buffer_in.dim (n)); for (size_t i = 0; i < pos[n].size(); i++) pos[n][i] = i; } } Image::Adapter::Extract<decltype(in)> extract (in, pos); copy_permute (extract, header_out, argument[1]); } else copy_permute (in, header_out, argument[1]); } <|endoftext|>
<commit_before>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/socket_io.hpp" // print_endpoint #include "libtorrent/connection_queue.hpp" #include "libtorrent/http_connection.hpp" #include "setup_transfer.hpp" #include <fstream> #include <iostream> #include <boost/optional.hpp> using namespace libtorrent; io_service ios; connection_queue cq(ios); int connect_handler_called = 0; int handler_called = 0; int data_size = 0; int http_status = 0; error_code g_error_code; char data_buffer[4000]; void print_http_header(http_parser const& p) { std::cerr << " < " << p.status_code() << " " << p.message() << std::endl; for (std::map<std::string, std::string>::const_iterator i = p.headers().begin(), end(p.headers().end()); i != end; ++i) { std::cerr << " < " << i->first << ": " << i->second << std::endl; } } void http_connect_handler(http_connection& c) { ++connect_handler_called; TEST_CHECK(c.socket().is_open()); error_code ec; std::cerr << "connected to: " << print_endpoint(c.socket().remote_endpoint(ec)) << std::endl; // this is not necessarily true when using a proxy and proxying hostnames // TEST_CHECK(c.socket().remote_endpoint(ec).address() == address::from_string("127.0.0.1", ec)); } void http_handler(error_code const& ec, http_parser const& parser , char const* data, int size, http_connection& c) { ++handler_called; data_size = size; g_error_code = ec; if (parser.header_finished()) { http_status = parser.status_code(); if (http_status == 200) { TEST_CHECK(memcmp(data, data_buffer, size) == 0); } } print_http_header(parser); } void reset_globals() { connect_handler_called = 0; handler_called = 0; data_size = 0; http_status = 0; g_error_code = error_code(); } void run_test(std::string const& url, int size, int status, int connected , boost::optional<error_code> ec, proxy_settings const& ps) { reset_globals(); std::cerr << " ===== TESTING: " << url << " =====" << std::endl; std::cerr << " expecting: size: " << size << " status: " << status << " connected: " << connected << " error: " << (ec?ec->message():"no error") << std::endl; boost::shared_ptr<http_connection> h(new http_connection(ios, cq , &::http_handler, true, &::http_connect_handler)); h->get(url, seconds(1), 0, &ps); ios.reset(); error_code e; ios.run(e); std::cerr << "connect_handler_called: " << connect_handler_called << std::endl; std::cerr << "handler_called: " << handler_called << std::endl; std::cerr << "status: " << http_status << std::endl; std::cerr << "size: " << data_size << std::endl; std::cerr << "error_code: " << g_error_code.message() << std::endl; TEST_CHECK(connect_handler_called == connected); TEST_CHECK(handler_called == 1); TEST_CHECK(data_size == size || size == -1); TEST_CHECK(!ec || g_error_code == *ec); TEST_CHECK(http_status == status || status == -1); } void run_suite(std::string const& protocol, proxy_settings const& ps, int port) { if (ps.type != proxy_settings::none) { start_proxy(ps.port, ps.type); } char const* test_name[] = {"no", "SOCKS4", "SOCKS5" , "SOCKS5 password protected", "HTTP", "HTTP password protected"}; std::cout << "\n\n********************** using " << test_name[ps.type] << " proxy **********************\n" << std::endl; typedef boost::optional<error_code> err; // this requires the hosts file to be modified // run_test(protocol + "://test.dns.ts:8001/test_file", 3216, 200, 1, error_code(), ps); char url[256]; snprintf(url, sizeof(url), "%s://127.0.0.1:%d/", protocol.c_str(), port); std::string url_base(url); run_test(url_base + "relative/redirect", 3216, 200, 2, error_code(), ps); run_test(url_base + "redirect", 3216, 200, 2, error_code(), ps); run_test(url_base + "infinite_redirect", 0, 301, 6, error_code(), ps); run_test(url_base + "test_file", 3216, 200, 1, error_code(), ps); run_test(url_base + "test_file.gz", 3216, 200, 1, error_code(), ps); run_test(url_base + "non-existing-file", -1, 404, 1, err(), ps); // if we're going through an http proxy, we won't get the same error as if the hostname // resolution failed if ((ps.type == proxy_settings::http || ps.type == proxy_settings::http_pw) && protocol != "https") run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, 502, 1, err(), ps); else run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, -1, 0, err(), ps); if (ps.type != proxy_settings::none) stop_proxy(ps.port); } int test_main() { std::srand(std::time(0)); std::generate(data_buffer, data_buffer + sizeof(data_buffer), &std::rand); error_code ec; file test_file("test_file", file::write_only, ec); TEST_CHECK(!ec); if (ec) fprintf(stderr, "file error: %s\n", ec.message().c_str()); file::iovec_t b = { data_buffer, 3216}; test_file.writev(0, &b, 1, ec); TEST_CHECK(!ec); if (ec) fprintf(stderr, "file error: %s\n", ec.message().c_str()); test_file.close(); std::system("gzip -9 -c test_file > test_file.gz"); proxy_settings ps; ps.hostname = "127.0.0.1"; ps.port = 8034; ps.username = "testuser"; ps.password = "testpass"; int port = start_web_server(); for (int i = 0; i < 5; ++i) { ps.type = (proxy_settings::proxy_type)i; run_suite("http", ps, port); } stop_web_server(); #ifdef TORRENT_USE_OPENSSL port = start_web_server(true); for (int i = 0; i < 5; ++i) { ps.type = (proxy_settings::proxy_type)i; run_suite("https", ps, port); } stop_web_server(); #endif std::remove("test_file"); return 0; } <commit_msg>don't run the test that requires proper NX_DOMAIN support if the internet connection doesn't support it<commit_after>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/socket_io.hpp" // print_endpoint #include "libtorrent/connection_queue.hpp" #include "libtorrent/http_connection.hpp" #include "setup_transfer.hpp" #include <fstream> #include <iostream> #include <boost/optional.hpp> using namespace libtorrent; io_service ios; connection_queue cq(ios); int connect_handler_called = 0; int handler_called = 0; int data_size = 0; int http_status = 0; error_code g_error_code; char data_buffer[4000]; void print_http_header(http_parser const& p) { std::cerr << " < " << p.status_code() << " " << p.message() << std::endl; for (std::map<std::string, std::string>::const_iterator i = p.headers().begin(), end(p.headers().end()); i != end; ++i) { std::cerr << " < " << i->first << ": " << i->second << std::endl; } } void http_connect_handler(http_connection& c) { ++connect_handler_called; TEST_CHECK(c.socket().is_open()); error_code ec; std::cerr << "connected to: " << print_endpoint(c.socket().remote_endpoint(ec)) << std::endl; // this is not necessarily true when using a proxy and proxying hostnames // TEST_CHECK(c.socket().remote_endpoint(ec).address() == address::from_string("127.0.0.1", ec)); } void http_handler(error_code const& ec, http_parser const& parser , char const* data, int size, http_connection& c) { ++handler_called; data_size = size; g_error_code = ec; if (parser.header_finished()) { http_status = parser.status_code(); if (http_status == 200) { TEST_CHECK(memcmp(data, data_buffer, size) == 0); } } print_http_header(parser); } void reset_globals() { connect_handler_called = 0; handler_called = 0; data_size = 0; http_status = 0; g_error_code = error_code(); } void run_test(std::string const& url, int size, int status, int connected , boost::optional<error_code> ec, proxy_settings const& ps) { reset_globals(); std::cerr << " ===== TESTING: " << url << " =====" << std::endl; std::cerr << " expecting: size: " << size << " status: " << status << " connected: " << connected << " error: " << (ec?ec->message():"no error") << std::endl; boost::shared_ptr<http_connection> h(new http_connection(ios, cq , &::http_handler, true, &::http_connect_handler)); h->get(url, seconds(1), 0, &ps); ios.reset(); error_code e; ios.run(e); std::cerr << "connect_handler_called: " << connect_handler_called << std::endl; std::cerr << "handler_called: " << handler_called << std::endl; std::cerr << "status: " << http_status << std::endl; std::cerr << "size: " << data_size << std::endl; std::cerr << "error_code: " << g_error_code.message() << std::endl; TEST_CHECK(connect_handler_called == connected); TEST_CHECK(handler_called == 1); TEST_CHECK(data_size == size || size == -1); TEST_CHECK(!ec || g_error_code == *ec); TEST_CHECK(http_status == status || status == -1); } void run_suite(std::string const& protocol, proxy_settings const& ps, int port) { if (ps.type != proxy_settings::none) { start_proxy(ps.port, ps.type); } char const* test_name[] = {"no", "SOCKS4", "SOCKS5" , "SOCKS5 password protected", "HTTP", "HTTP password protected"}; std::cout << "\n\n********************** using " << test_name[ps.type] << " proxy **********************\n" << std::endl; typedef boost::optional<error_code> err; // this requires the hosts file to be modified // run_test(protocol + "://test.dns.ts:8001/test_file", 3216, 200, 1, error_code(), ps); char url[256]; snprintf(url, sizeof(url), "%s://127.0.0.1:%d/", protocol.c_str(), port); std::string url_base(url); run_test(url_base + "relative/redirect", 3216, 200, 2, error_code(), ps); run_test(url_base + "redirect", 3216, 200, 2, error_code(), ps); run_test(url_base + "infinite_redirect", 0, 301, 6, error_code(), ps); run_test(url_base + "test_file", 3216, 200, 1, error_code(), ps); run_test(url_base + "test_file.gz", 3216, 200, 1, error_code(), ps); run_test(url_base + "non-existing-file", -1, 404, 1, err(), ps); // only run the tests to handle NX_DOMAIN if we have a proper internet // connection that doesn't inject false DNS responses (like Comcast does) hostent* h = gethostbyname("non-existent-domain.se"); if (h == 0 && h_errno == HOST_NOT_FOUND) { // if we're going through an http proxy, we won't get the same error as if the hostname // resolution failed if ((ps.type == proxy_settings::http || ps.type == proxy_settings::http_pw) && protocol != "https") run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, 502, 1, err(), ps); else run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, -1, 0, err(), ps); } if (ps.type != proxy_settings::none) stop_proxy(ps.port); } int test_main() { std::srand(std::time(0)); std::generate(data_buffer, data_buffer + sizeof(data_buffer), &std::rand); error_code ec; file test_file("test_file", file::write_only, ec); TEST_CHECK(!ec); if (ec) fprintf(stderr, "file error: %s\n", ec.message().c_str()); file::iovec_t b = { data_buffer, 3216}; test_file.writev(0, &b, 1, ec); TEST_CHECK(!ec); if (ec) fprintf(stderr, "file error: %s\n", ec.message().c_str()); test_file.close(); std::system("gzip -9 -c test_file > test_file.gz"); proxy_settings ps; ps.hostname = "127.0.0.1"; ps.port = 8034; ps.username = "testuser"; ps.password = "testpass"; int port = start_web_server(); for (int i = 0; i < 5; ++i) { ps.type = (proxy_settings::proxy_type)i; run_suite("http", ps, port); } stop_web_server(); #ifdef TORRENT_USE_OPENSSL port = start_web_server(true); for (int i = 0; i < 5; ++i) { ps.type = (proxy_settings::proxy_type)i; run_suite("https", ps, port); } stop_web_server(); #endif std::remove("test_file"); return 0; } <|endoftext|>
<commit_before>#include <mettle.hpp> using namespace mettle; #include <sstream> suite<> test_tuple_alg("tuple algorithms", [](auto &_) { subsuite<>(_, "tuple_for_until()", [](auto &_) { using detail::tuple_for_each; _.test("empty tuple", []() { std::tuple<> tup; std::size_t count = 0; tuple_for_each(tup, [&count](auto &&) { count++; }); expect("number of iterations", count, equal_to(0)); }); _.test("1-tuple", []() { std::tuple<int> tup(1); std::size_t count = 0; tuple_for_each(tup, [&count](auto &&item) { expect("tuple value", item, equal_to(1)); count++; }); expect("number of iterations", count, equal_to(1)); }); _.test("2-tuple", []() { std::tuple<int, std::string> tup(1, "two"); std::size_t count = 0; tuple_for_each(tup, [&count](auto &&) { count++; }); expect("number of iterations", count, equal_to(2)); std::tuple<int, int> tup2(0, 1); count = 0; tuple_for_each(tup2, [&count](auto &&item) { expect("tuple value", item, equal_to(count)); count++; }); expect("number of iterations", count, equal_to(2)); }); _.test("pair", []() { std::pair<int, std::string> pair(1, "two"); std::size_t count = 0; tuple_for_each(pair, [&count](auto &&) { count++; }); expect("number of iterations", count, equal_to(2)); }); _.test("early exit", []() { std::tuple<int, std::string> tup(1, "two"); std::size_t count = 0; tuple_for_each(tup, [&count](auto &&) { count++; return true; }); expect("number of iterations", count, equal_to(1)); }); _.test("modification", []() { std::tuple<int, int> tup(1, 2); tuple_for_each(tup, [](auto &&item) { item++; }); expect(tup, equal_to(std::make_tuple(2, 3))); }); }); subsuite<>(_, "tuple_joined()", [](auto &_) { using detail::tuple_joined; _.test("empty tuple", []() { std::tuple<> tup; std::ostringstream os1; os1 << tuple_joined(tup, [](auto &&) { return "bad"; }); expect(os1.str(), equal_to("")); std::ostringstream os2; os2 << tuple_joined(tup, [](auto &&) { return "bad"; }, " and "); expect(os2.str(), equal_to("")); }); _.test("1-tuple", []() { std::tuple<int> tup(1); std::ostringstream os1; os1 << tuple_joined(tup, [](auto &&item) { return item; }); expect(os1.str(), equal_to("1")); std::ostringstream os2; os2 << tuple_joined(tup, [](auto &&item) { return item; }, " and "); expect(os2.str(), equal_to("1")); }); _.test("2-tuple", []() { std::tuple<int, std::string> tup(1, "two"); std::ostringstream os1; os1 << tuple_joined(tup, [](auto &&item) { return item; }); expect(os1.str(), equal_to("1, two")); std::ostringstream os2; os2 << tuple_joined(tup, [](auto &&item) { return item; }, " and "); expect(os2.str(), equal_to("1 and two")); }); _.test("pair", []() { std::pair<int, std::string> pair(1, "two"); std::ostringstream os1; os1 << tuple_joined(pair, [](auto &&item) { return item; }); expect(os1.str(), equal_to("1, two")); std::ostringstream os2; os2 << tuple_joined(pair, [](auto &&item) { return item; }, " and "); expect(os2.str(), equal_to("1 and two")); }); }); }); <commit_msg>Fix test name<commit_after>#include <mettle.hpp> using namespace mettle; #include <sstream> suite<> test_tuple_alg("tuple algorithms", [](auto &_) { subsuite<>(_, "tuple_for_each()", [](auto &_) { using detail::tuple_for_each; _.test("empty tuple", []() { std::tuple<> tup; std::size_t count = 0; tuple_for_each(tup, [&count](auto &&) { count++; }); expect("number of iterations", count, equal_to(0)); }); _.test("1-tuple", []() { std::tuple<int> tup(1); std::size_t count = 0; tuple_for_each(tup, [&count](auto &&item) { expect("tuple value", item, equal_to(1)); count++; }); expect("number of iterations", count, equal_to(1)); }); _.test("2-tuple", []() { std::tuple<int, std::string> tup(1, "two"); std::size_t count = 0; tuple_for_each(tup, [&count](auto &&) { count++; }); expect("number of iterations", count, equal_to(2)); std::tuple<int, int> tup2(0, 1); count = 0; tuple_for_each(tup2, [&count](auto &&item) { expect("tuple value", item, equal_to(count)); count++; }); expect("number of iterations", count, equal_to(2)); }); _.test("pair", []() { std::pair<int, std::string> pair(1, "two"); std::size_t count = 0; tuple_for_each(pair, [&count](auto &&) { count++; }); expect("number of iterations", count, equal_to(2)); }); _.test("early exit", []() { std::tuple<int, std::string> tup(1, "two"); std::size_t count = 0; tuple_for_each(tup, [&count](auto &&) { count++; return true; }); expect("number of iterations", count, equal_to(1)); }); _.test("modification", []() { std::tuple<int, int> tup(1, 2); tuple_for_each(tup, [](auto &&item) { item++; }); expect(tup, equal_to(std::make_tuple(2, 3))); }); }); subsuite<>(_, "tuple_joined()", [](auto &_) { using detail::tuple_joined; _.test("empty tuple", []() { std::tuple<> tup; std::ostringstream os1; os1 << tuple_joined(tup, [](auto &&) { return "bad"; }); expect(os1.str(), equal_to("")); std::ostringstream os2; os2 << tuple_joined(tup, [](auto &&) { return "bad"; }, " and "); expect(os2.str(), equal_to("")); }); _.test("1-tuple", []() { std::tuple<int> tup(1); std::ostringstream os1; os1 << tuple_joined(tup, [](auto &&item) { return item; }); expect(os1.str(), equal_to("1")); std::ostringstream os2; os2 << tuple_joined(tup, [](auto &&item) { return item; }, " and "); expect(os2.str(), equal_to("1")); }); _.test("2-tuple", []() { std::tuple<int, std::string> tup(1, "two"); std::ostringstream os1; os1 << tuple_joined(tup, [](auto &&item) { return item; }); expect(os1.str(), equal_to("1, two")); std::ostringstream os2; os2 << tuple_joined(tup, [](auto &&item) { return item; }, " and "); expect(os2.str(), equal_to("1 and two")); }); _.test("pair", []() { std::pair<int, std::string> pair(1, "two"); std::ostringstream os1; os1 << tuple_joined(pair, [](auto &&item) { return item; }); expect(os1.str(), equal_to("1, two")); std::ostringstream os2; os2 << tuple_joined(pair, [](auto &&item) { return item; }, " and "); expect(os2.str(), equal_to("1 and two")); }); }); }); <|endoftext|>
<commit_before> #include <iostream> #include <unordered_map> #include <boost/algorithm/string.hpp> #include <vector> #include <Galois/Galois.h> #include <Galois/Graph/Graph.h> //#include <cstring> #include <string> #include <fstream> using namespace std; using namespace boost; typedef enum{pi,po,nd} node_type; struct Node { string label_type;//a0,b0... node_type type;// pi,po,nd int fanins; // Not required as of now bool fanout; //Not required as of now int level; }; typedef Galois::Graph::FirstGraph<Node,int,true> Graph; Graph g; int node_index = 0; vector<Graph::GraphNode> gnodes; vector<string> fields; bool checkWorkability(Graph::GraphNode gnode){ int count = 0; for (Graph::edge_iterator edge : g.out_edges(gnode)) { int edgedata = g.getEdgeData(edge); if(edgedata == 1|| edgedata ==2) count++; } if (count > 1) return false; else return true; } bool isEqualNodes(Graph::GraphNode gnode1, Graph::GraphNode gnode2){ int count = 0; for (Graph::edge_iterator edge1 : g.out_edges(gnode1)){ for (Graph::edge_iterator edge2 : g.out_edges(gnode2)){ if(g.getEdgeData(edge1)== 3) if(g.getEdgeData(edge2)== 3) if(g.getEdgeDst(edge1)==g.getEdgeDst(edge2)){ count++; } } } if(count == 2) return true; else return false; } bool find_cut(Graph::GraphNode &top,Graph::GraphNode &child_left,Graph::GraphNode &child_right) { if ( g.getData(top).level != 0 && g.getData(top).level != 1) { for (Graph::edge_iterator edge : g.out_edges(top)){ Graph::GraphNode dst = g.getEdgeDst(edge); if(g.getEdgeData(edge) == 3){ if(child_left==NULL){ child_left=dst; } else{ child_right=dst; } } } return true; } else return false; } void parseFileintoGraph(string inFile, unordered_map <string, int> &map){ ifstream fin; fin.open(inFile); // open a file if (!fin.good()){ cout << "file not found\n"; } else // read each line of the file while (!fin.eof()) { // read an entire line into memory string line; getline(fin,line); trim(line); split(fields, line, is_any_of(" ")); Node n; if(fields[0].compare("input") == 0 || fields[0].compare("output") == 0||fields[0].compare("wire") == 0) { for(unsigned i =1;i<fields.size();i++){ //add to hash map to index to corresponding node in array if(fields[i].size()>1) { //Add data to each node for level and type of input if(fields[0].compare("input") == 0) { n.type = pi; n.level = 0; n.label_type = fields[i].substr(0,fields[i].length()-1); //nodes[node_index].type = pi; //nodes[node_index].level = 0; //nodes[node_index].label_type = fields[i].substr(0,fields[i].length()-1); } if(fields[0].compare("output") == 0) { n.type = po; n.level = -1; n.label_type = fields[i].substr(0,fields[i].length()-1); //nodes[node_index].type = po; //nodes[node_index].label_type = fields[i].substr(0,fields[i].length()-1); } if(fields[0].compare("wire") == 0) { n.type = nd; n.level = -2; n.label_type = fields[i].substr(0,fields[i].length()-1); //nodes[node_index].type = nd; //nodes[node_index].label_type = fields[i].substr(0,fields[i].length()-1); } //remove last char b/c its ',' or ';' map[fields[i].substr(0,fields[i].length()-1)] = node_index; //gnodes[node_index] = g.createNode(nodes[node_index]); gnodes.push_back(g.createNode(n)); g.addNode(gnodes[gnodes.size()-1]); //cout << "node index: "<< node_index<<endl; node_index++; } } } //cout <<"compare assign"<<endl; if(fields[0].compare("assign") == 0) { int level1,level2; string f1,f3,f5; f1 = fields[1]; f3 = fields[3]; f5 = fields[5]; if(fields[4].compare("|") == 0) { //Edge weight: 2- Negative 1 - Positive f3 = f3.substr(0,f3.length()); f5 = f5.substr(0,f5.length()-1); g.getEdgeData(g.addEdge(gnodes[map[f3]]//src ,gnodes[map[f1]])) = 2;//dest g.getEdgeData(g.addEdge(gnodes[map[f5]] ,gnodes[map[f1]])) = 2; level1 = g.getData(gnodes[map[f3]]).level; level2 = g.getData(gnodes[map[f5]]).level; g.getEdgeData(g.addEdge(gnodes[map[f1]], gnodes[map[f3]])) = 3;//back edges to determine fanins -> wt. = 3 g.getEdgeData(g.addEdge(gnodes[map[f1]], gnodes[map[f5]])) = 3;//back edges to determins fanins -> wt. = 3 } else { size_t invert = fields[3].find_first_of("~"); if (invert != string::npos){ f3 = f3.substr(1,f3.length()); //addEdge(src,dest) //remove the '~' from the start of string //map[string] returns node index to find which node g.getEdgeData(g.addEdge(gnodes[map[f3]],gnodes[map[f1]])) = 2;// level1 = g.getData(gnodes[map[f3]]).level; g.getEdgeData(g.addEdge(gnodes[map[f1]], gnodes[map[f3]])) = 3;// Back edges to determine fanins -> wt. = 3 } else{ g.getEdgeData(g.addEdge(gnodes[map[f3]],gnodes[map[f1]])) = 1; level1 = g.getData(gnodes[map[f3]]).level; g.getEdgeData(g.addEdge(gnodes[map[f1]], gnodes[map[f3]])) = 3;// Back edges to determine fanins -> wt. = 3 } invert = fields[5].find_first_of("~"); if (invert != string::npos){ f5 = f5.substr(1,f5.length()-2); //remove first and last char b/c '~' to start and ';' at th //cout <<fields[5] << " substr"<<fields[5].substr(1,fields[5].length()-1)<<" "<<map[fields[5].substr(1,fields[5].length()-1)]<< " "<< nodes[map[fields[5].substr(1,fields[5].length()-1)]].label_type <<endl; g.getEdgeData(g.addEdge(gnodes[map[f5]],gnodes[map[f1]])) = 2; level2 = g.getData(gnodes[map[f5]]).level; g.getEdgeData(g.addEdge(gnodes[map[f1]], gnodes[map[f5]])) = 3;// Back edges to determine fanins -> wt. = 3 } else{ f5 = f5.substr(0,f5.length()-1); g.getEdgeData(g.addEdge(gnodes[map[f5]],gnodes[map[f1]])) = 1; level2 = g.getData(gnodes[map[f5]]).level; g.getEdgeData(g.addEdge(gnodes[map[f1]], gnodes[map[f5]])) = 3;// Back edges to determine fanins -> wt. = 3 } } if(level1>=level2) g.getData(gnodes[map[fields[1]]]).level= level1+1; else g.getData(gnodes[map[fields[1]]]).level= level2+1; } } } int main(int argc, char *argv[]) { unordered_map <string, int> map; if ( argc != 2 ) cout<<"usage: "<< argv[0] <<" <filename>\n"; else parseFileintoGraph(argv[1],map); //cout << g.getData(gnodes[0]).label_type << endl; // Traverse graph //for (Graph::iterator ii = g.begin(), ei = g.end(); ii != ei; ++ii) { for ( Graph::GraphNode src : g){ //Graph::GraphNode src = *ii; cout <<"src: "<< g.getData(src).label_type; cout <<" level: "<<g.getData(src).level; for (Graph::edge_iterator edge : g.out_edges(src)) { Graph::GraphNode dst = g.getEdgeDst(edge); cout <<" dest: "<< g.getData(dst).label_type; int edgeData = g.getEdgeData(edge); cout << " edge data " << edgeData; //assert(edgeData == 5); } cout <<endl; } if(checkWorkability(gnodes[map["n15"]])) cout << "1 output"<<endl; else cout <<"more than 1 output"<<endl; bool out; Graph::GraphNode child_left=NULL,child_right=NULL; if(find_cut(gnodes[map["s0"]],child_left,child_right)){ cout<<"Src node:"<<g.getData(gnodes[map["s0"]]).label_type << endl; cout<<"Child node 1:"<<g.getData(child_left).label_type << endl; cout<<"Child node 2:"<<g.getData(child_right).label_type << endl; } //if(isEqualNodes(gnodes[map["n8"]],gnodes[map["n8"]])) // cout << "equal nodes"<<endl; return 0; } <commit_msg>function to get children of a node<commit_after> #include <iostream> #include <unordered_map> #include <boost/algorithm/string.hpp> #include <vector> #include <Galois/Galois.h> #include <Galois/Graph/Graph.h> //#include <cstring> #include <string> #include <fstream> using namespace std; using namespace boost; typedef enum{pi,po,nd} node_type; struct Node { string label_type;//a0,b0... node_type type;// pi,po,nd int fanins; // Not required as of now bool fanout; //Not required as of now int level; }; typedef Galois::Graph::FirstGraph<Node,int,true> Graph; Graph g; int node_index = 0; vector<Graph::GraphNode> gnodes; vector<string> fields; bool checkWorkability(Graph::GraphNode gnode){ int count = 0; for (Graph::edge_iterator edge : g.out_edges(gnode)) { int edgedata = g.getEdgeData(edge); if(edgedata == 1|| edgedata ==2) count++; } if (count > 1) return false; else return true; } bool isEqualNodes(Graph::GraphNode gnode1, Graph::GraphNode gnode2){ int count = 0; if(g.getData(gnode1).label_type==g.getData(gnode2).label_type){ //cout<< "same node"<<endl; return true; } for (Graph::edge_iterator edge1 : g.out_edges(gnode1)){ for (Graph::edge_iterator edge2 : g.out_edges(gnode2)){ if(g.getEdgeData(edge1)== 3) if(g.getEdgeData(edge2)== 3) if(g.getEdgeDst(edge1)==g.getEdgeDst(edge2)){ count++; } } } if(count == 2) return true; else return false; } bool find_cut(Graph::GraphNode &top,Graph::GraphNode &child_left,Graph::GraphNode &child_right) { if ( g.getData(top).level != 0 && g.getData(top).level != 1) { for (Graph::edge_iterator edge : g.out_edges(top)){ Graph::GraphNode dst = g.getEdgeDst(edge); if(g.getEdgeData(edge) == 3){ if(child_left==NULL){ child_left=dst; } else{ child_right=dst; } } } return true; } else return false; } void parseFileintoGraph(string inFile, unordered_map <string, int> &map){ ifstream fin; fin.open(inFile); // open a file if (!fin.good()){ cout << "file not found\n"; } else // read each line of the file while (!fin.eof()) { // read an entire line into memory string line; getline(fin,line); trim(line); split(fields, line, is_any_of(" ")); Node n; if(fields[0].compare("input") == 0 || fields[0].compare("output") == 0||fields[0].compare("wire") == 0) { for(unsigned i =1;i<fields.size();i++){ //add to hash map to index to corresponding node in array if(fields[i].size()>1) { //Add data to each node for level and type of input if(fields[0].compare("input") == 0) { n.type = pi; n.level = 0; n.label_type = fields[i].substr(0,fields[i].length()-1); //nodes[node_index].type = pi; //nodes[node_index].level = 0; //nodes[node_index].label_type = fields[i].substr(0,fields[i].length()-1); } if(fields[0].compare("output") == 0) { n.type = po; n.level = -1; n.label_type = fields[i].substr(0,fields[i].length()-1); //nodes[node_index].type = po; //nodes[node_index].label_type = fields[i].substr(0,fields[i].length()-1); } if(fields[0].compare("wire") == 0) { n.type = nd; n.level = -2; n.label_type = fields[i].substr(0,fields[i].length()-1); //nodes[node_index].type = nd; //nodes[node_index].label_type = fields[i].substr(0,fields[i].length()-1); } //remove last char b/c its ',' or ';' map[fields[i].substr(0,fields[i].length()-1)] = node_index; //gnodes[node_index] = g.createNode(nodes[node_index]); gnodes.push_back(g.createNode(n)); g.addNode(gnodes[gnodes.size()-1]); //cout << "node index: "<< node_index<<endl; node_index++; } } } //cout <<"compare assign"<<endl; if(fields[0].compare("assign") == 0) { int level1,level2; string f1,f3,f5; f1 = fields[1]; f3 = fields[3]; f5 = fields[5]; if(fields[4].compare("|") == 0) { //Edge weight: 2- Negative 1 - Positive f3 = f3.substr(0,f3.length()); f5 = f5.substr(0,f5.length()-1); g.getEdgeData(g.addEdge(gnodes[map[f3]]//src ,gnodes[map[f1]])) = 2;//dest g.getEdgeData(g.addEdge(gnodes[map[f5]] ,gnodes[map[f1]])) = 2; level1 = g.getData(gnodes[map[f3]]).level; level2 = g.getData(gnodes[map[f5]]).level; g.getEdgeData(g.addEdge(gnodes[map[f1]], gnodes[map[f3]])) = 3;//back edges to determine fanins -> wt. = 3 g.getEdgeData(g.addEdge(gnodes[map[f1]], gnodes[map[f5]])) = 3;//back edges to determins fanins -> wt. = 3 } else { size_t invert = fields[3].find_first_of("~"); if (invert != string::npos){ f3 = f3.substr(1,f3.length()); //addEdge(src,dest) //remove the '~' from the start of string //map[string] returns node index to find which node g.getEdgeData(g.addEdge(gnodes[map[f3]],gnodes[map[f1]])) = 2;// level1 = g.getData(gnodes[map[f3]]).level; g.getEdgeData(g.addEdge(gnodes[map[f1]], gnodes[map[f3]])) = 3;// Back edges to determine fanins -> wt. = 3 } else{ g.getEdgeData(g.addEdge(gnodes[map[f3]],gnodes[map[f1]])) = 1; level1 = g.getData(gnodes[map[f3]]).level; g.getEdgeData(g.addEdge(gnodes[map[f1]], gnodes[map[f3]])) = 3;// Back edges to determine fanins -> wt. = 3 } invert = fields[5].find_first_of("~"); if (invert != string::npos){ f5 = f5.substr(1,f5.length()-2); //remove first and last char b/c '~' to start and ';' at th //cout <<fields[5] << " substr"<<fields[5].substr(1,fields[5].length()-1)<<" "<<map[fields[5].substr(1,fields[5].length()-1)]<< " "<< nodes[map[fields[5].substr(1,fields[5].length()-1)]].label_type <<endl; g.getEdgeData(g.addEdge(gnodes[map[f5]],gnodes[map[f1]])) = 2; level2 = g.getData(gnodes[map[f5]]).level; g.getEdgeData(g.addEdge(gnodes[map[f1]], gnodes[map[f5]])) = 3;// Back edges to determine fanins -> wt. = 3 } else{ f5 = f5.substr(0,f5.length()-1); g.getEdgeData(g.addEdge(gnodes[map[f5]],gnodes[map[f1]])) = 1; level2 = g.getData(gnodes[map[f5]]).level; g.getEdgeData(g.addEdge(gnodes[map[f1]], gnodes[map[f5]])) = 3;// Back edges to determine fanins -> wt. = 3 } } if(level1>=level2) g.getData(gnodes[map[fields[1]]]).level= level1+1; else g.getData(gnodes[map[fields[1]]]).level= level2+1; } } } bool checkxor(Graph::GraphNode node){ Graph::GraphNode inode1=NULL,inode2=NULL; Graph::GraphNode input1=NULL,input2=NULL,input3=NULL,input4=NULL; } void getChildren(Graph::GraphNode parent, Graph::GraphNode &child1, Graph::GraphNode &child2){ for (Graph::edge_iterator edge : g.out_edges(node)){ if(g.getEdgeData(edge)==3){ if (inode1==NULL) inode1 = g.getEdgeDst(edge); else inode2 = g.getEdgeDst(edge); } } } int main(int argc, char *argv[]) { unordered_map <string, int> map; if ( argc != 2 ) cout<<"usage: "<< argv[0] <<" <filename>\n"; else parseFileintoGraph(argv[1],map); //cout << g.getData(gnodes[0]).label_type << endl; // Traverse graph //for (Graph::iterator ii = g.begin(), ei = g.end(); ii != ei; ++ii) { for ( Graph::GraphNode src : g){ //Graph::GraphNode src = *ii; cout <<"src: "<< g.getData(src).label_type; cout <<" level: "<<g.getData(src).level; for (Graph::edge_iterator edge : g.out_edges(src)) { Graph::GraphNode dst = g.getEdgeDst(edge); cout <<" dest: "<< g.getData(dst).label_type; int edgeData = g.getEdgeData(edge); cout << " edge data " << edgeData; //assert(edgeData == 5); } cout <<endl; } if(checkWorkability(gnodes[map["n15"]])) cout << "1 output"<<endl; else cout <<"more than 1 output"<<endl; bool out; Graph::GraphNode child_left=NULL,child_right=NULL; if(find_cut(gnodes[map["s0"]],child_left,child_right)){ cout<<"Src node:"<<g.getData(gnodes[map["s0"]]).label_type << endl; cout<<"Child node 1:"<<g.getData(child_left).label_type << endl; cout<<"Child node 2:"<<g.getData(child_right).label_type << endl; } if(isEqualNodes(gnodes[map["n8"]],gnodes[map["n8"]])) cout << "equal nodes"<<endl; return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "assert.h" #include "core.h" #include "protocol.h" #include "util.h" #include "scrypt.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { 0xA2F39055, 0x5EF2E56F, 0x57D54ADA, 0x50F812B0, 0x256187D5 }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0xfd; pchMessageStart[1] = 0xa4; pchMessageStart[2] = 0xdc; pchMessageStart[3] = 0x6c; vAlertPubKey = ParseHex("04d1832d7d0c59634d67d3023379403014c2878d0c2372d175219063a48fa06e6d429e09f36d3196ec544c2cfdd12d6fe510a399595f75ebb6da238eb5f70f2072"); nDefaultPort = 12340; nRPCPort = 12341; bnProofOfWorkLimit[ALGO_SHA256D] = CBigNum(~uint256(0) >> 20); // 1.00000000 bnProofOfWorkLimit[ALGO_SCRYPT] = CBigNum(~uint256(0) >> 20); bnProofOfWorkLimit[ALGO_GROESTL] = CBigNum(~uint256(0) >> 20); // 0.00195311 bnProofOfWorkLimit[ALGO_SKEIN] = CBigNum(~uint256(0) >> 20); // 0.00195311 bnProofOfWorkLimit[ALGO_QUBIT] = CBigNum(~uint256(0) >> 20); // 0.00097655 // Build the genesis block. const char* pszTimestamp = "Visir 10. oktober 2008 Gjaldeyrishoft sett a Islendinga"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 1 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04a5814813115273a109cff99907ba4a05d951873dae7acb6c973d0c9e7c88911a3dbc9aa600deac241b91707e7b4ffb30ad91c8e56e695a1ddf318592988afe0a") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1390598806; genesis.nBits = Params().ProofOfWorkLimit(ALGO_SCRYPT).GetCompact(); //genesis.nBits = 0x1e0fffff; genesis.nNonce = 538548; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x2a8e100939494904af825b488596ddd536b3a96226ad02e0f7ab7ae472b27a8e")); assert(genesis.hashMerkleRoot == uint256("0x8957e5e8d2f0e90c42e739ec62fcc5dd21064852da64b6528ebd46567f222169")); vSeeds.push_back(CDNSSeedData("luxembourgh", "s1.auroraseed.net")); vSeeds.push_back(CDNSSeedData("united-states-west", "aurseed1.criptoe.com")); vSeeds.push_back(CDNSSeedData("united-states-east", "s1.auroraseed.com")); vSeeds.push_back(CDNSSeedData("iceland", "s1.auroraseed.org")); vSeeds.push_back(CDNSSeedData("the-netherlands", "s1.auroraseed.eu")); base58Prefixes[PUBKEY_ADDRESS] = list_of(23); base58Prefixes[SCRIPT_ADDRESS] = list_of(5); base58Prefixes[SECRET_KEY] = list_of(176); base58Prefixes[SECRET_KEY_OLD] = list_of(151); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4); // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // Testnet class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0xfd; pchMessageStart[1] = 0xa4; pchMessageStart[2] = 0xdc; pchMessageStart[3] = 0x6d; // the "d" seperates test net from main net nDefaultPort = 4321; nRPCPort = 14321; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1448114586; genesis.nNonce = 123378; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x1e47fdcb0dd34a6b28c47ef90768bea62694bb3fe712d2d2687c7c20df634131")); // If genesis block hash does not match, then generate new genesis hash. if (hashGenesisBlock != uint256("0x1e47fdcb0dd34a6b28c47ef90768bea62694bb3fe712d2d2687c7c20df634131")) { printf("Searching for testnet genesis block...\n"); // This will figure out a valid hash and Nonce if you're creating a different genesis block: //uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256(); uint256 hashTarget = CBigNum().SetCompact(genesis.nBits).getuint256(); uint256 thash; uint256 bestfound; //static char scratchpad[SCRYPT_SCRATCHPAD_SIZE]; scrypt_1024_1_1_256(BEGIN(genesis.nVersion), BEGIN(bestfound)); while(true) { scrypt_1024_1_1_256(BEGIN(genesis.nVersion), BEGIN(thash)); //thash = scrypt_blockhash(BEGIN(block.nVersion)); if (thash <= hashTarget) break; //if ((genesis.nNonce & 0xFFF) == 0) if (thash <= bestfound) { bestfound = thash; printf("nonce %08X: hash = %s (target = %s)\n", genesis.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str()); } ++genesis.nNonce; if (genesis.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++genesis.nTime; } } printf("block.nTime = %u \n", genesis.nTime); printf("block.nNonce = %u \n", genesis.nNonce); printf("block.GetHash = %s\n", genesis.GetHash().ToString().c_str()); } vFixedSeeds.clear(); vSeeds.clear(); vSeeds.push_back(CDNSSeedData("testnet-united-states-east", "testnet1.auroraseed.com")); vSeeds.push_back(CDNSSeedData("testnet-united-states-west", "testnet2.criptoe.com")); base58Prefixes[PUBKEY_ADDRESS] = list_of(111); base58Prefixes[SCRIPT_ADDRESS] = list_of(196); base58Prefixes[SECRET_KEY] = list_of(239); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94); } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // Regression test class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xbf; pchMessageStart[2] = 0xb5; pchMessageStart[3] = 0xda; //nSubsidyHalvingInterval = 150; // bnProofOfWorkLimit = CBigNum(); genesis.nTime = 1296688602; genesis.nBits = 0x207fffff; genesis.nNonce = 0; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 19444; strDataDir = "regtest"; //assert(hashGenesisBlock == uint256("0x0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <commit_msg>Copyright notice fix.<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2016 The Auroracoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "assert.h" #include "core.h" #include "protocol.h" #include "util.h" #include "scrypt.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { 0xA2F39055, 0x5EF2E56F, 0x57D54ADA, 0x50F812B0, 0x256187D5 }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0xfd; pchMessageStart[1] = 0xa4; pchMessageStart[2] = 0xdc; pchMessageStart[3] = 0x6c; vAlertPubKey = ParseHex("04d1832d7d0c59634d67d3023379403014c2878d0c2372d175219063a48fa06e6d429e09f36d3196ec544c2cfdd12d6fe510a399595f75ebb6da238eb5f70f2072"); nDefaultPort = 12340; nRPCPort = 12341; bnProofOfWorkLimit[ALGO_SHA256D] = CBigNum(~uint256(0) >> 20); // 1.00000000 bnProofOfWorkLimit[ALGO_SCRYPT] = CBigNum(~uint256(0) >> 20); bnProofOfWorkLimit[ALGO_GROESTL] = CBigNum(~uint256(0) >> 20); // 0.00195311 bnProofOfWorkLimit[ALGO_SKEIN] = CBigNum(~uint256(0) >> 20); // 0.00195311 bnProofOfWorkLimit[ALGO_QUBIT] = CBigNum(~uint256(0) >> 20); // 0.00097655 // Build the genesis block. const char* pszTimestamp = "Visir 10. oktober 2008 Gjaldeyrishoft sett a Islendinga"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 1 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04a5814813115273a109cff99907ba4a05d951873dae7acb6c973d0c9e7c88911a3dbc9aa600deac241b91707e7b4ffb30ad91c8e56e695a1ddf318592988afe0a") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1390598806; genesis.nBits = Params().ProofOfWorkLimit(ALGO_SCRYPT).GetCompact(); //genesis.nBits = 0x1e0fffff; genesis.nNonce = 538548; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x2a8e100939494904af825b488596ddd536b3a96226ad02e0f7ab7ae472b27a8e")); assert(genesis.hashMerkleRoot == uint256("0x8957e5e8d2f0e90c42e739ec62fcc5dd21064852da64b6528ebd46567f222169")); vSeeds.push_back(CDNSSeedData("luxembourgh", "s1.auroraseed.net")); vSeeds.push_back(CDNSSeedData("united-states-west", "aurseed1.criptoe.com")); vSeeds.push_back(CDNSSeedData("united-states-east", "s1.auroraseed.com")); vSeeds.push_back(CDNSSeedData("iceland", "s1.auroraseed.org")); vSeeds.push_back(CDNSSeedData("the-netherlands", "s1.auroraseed.eu")); base58Prefixes[PUBKEY_ADDRESS] = list_of(23); base58Prefixes[SCRIPT_ADDRESS] = list_of(5); base58Prefixes[SECRET_KEY] = list_of(176); base58Prefixes[SECRET_KEY_OLD] = list_of(151); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4); // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // Testnet class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0xfd; pchMessageStart[1] = 0xa4; pchMessageStart[2] = 0xdc; pchMessageStart[3] = 0x6d; // the "d" seperates test net from main net nDefaultPort = 4321; nRPCPort = 14321; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1448114586; genesis.nNonce = 123378; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x1e47fdcb0dd34a6b28c47ef90768bea62694bb3fe712d2d2687c7c20df634131")); // If genesis block hash does not match, then generate new genesis hash. if (hashGenesisBlock != uint256("0x1e47fdcb0dd34a6b28c47ef90768bea62694bb3fe712d2d2687c7c20df634131")) { printf("Searching for testnet genesis block...\n"); // This will figure out a valid hash and Nonce if you're creating a different genesis block: //uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256(); uint256 hashTarget = CBigNum().SetCompact(genesis.nBits).getuint256(); uint256 thash; uint256 bestfound; //static char scratchpad[SCRYPT_SCRATCHPAD_SIZE]; scrypt_1024_1_1_256(BEGIN(genesis.nVersion), BEGIN(bestfound)); while(true) { scrypt_1024_1_1_256(BEGIN(genesis.nVersion), BEGIN(thash)); //thash = scrypt_blockhash(BEGIN(block.nVersion)); if (thash <= hashTarget) break; //if ((genesis.nNonce & 0xFFF) == 0) if (thash <= bestfound) { bestfound = thash; printf("nonce %08X: hash = %s (target = %s)\n", genesis.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str()); } ++genesis.nNonce; if (genesis.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++genesis.nTime; } } printf("block.nTime = %u \n", genesis.nTime); printf("block.nNonce = %u \n", genesis.nNonce); printf("block.GetHash = %s\n", genesis.GetHash().ToString().c_str()); } vFixedSeeds.clear(); vSeeds.clear(); vSeeds.push_back(CDNSSeedData("testnet-united-states-east", "testnet1.auroraseed.com")); vSeeds.push_back(CDNSSeedData("testnet-united-states-west", "testnet2.criptoe.com")); base58Prefixes[PUBKEY_ADDRESS] = list_of(111); base58Prefixes[SCRIPT_ADDRESS] = list_of(196); base58Prefixes[SECRET_KEY] = list_of(239); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94); } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // Regression test class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xbf; pchMessageStart[2] = 0xb5; pchMessageStart[3] = 0xda; //nSubsidyHalvingInterval = 150; // bnProofOfWorkLimit = CBigNum(); genesis.nTime = 1296688602; genesis.nBits = 0x207fffff; genesis.nNonce = 0; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 19444; strDataDir = "regtest"; //assert(hashGenesisBlock == uint256("0x0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <|endoftext|>
<commit_before>/** @file @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "ts/ink_config.h" #include "records/I_RecHttp.h" #include "ts/ink_platform.h" #include "ts/X509HostnameValidator.h" #include "P_Net.h" #include "P_SSLClientUtils.h" #include <openssl/err.h> #include <openssl/pem.h> #if (OPENSSL_VERSION_NUMBER >= 0x10000000L) // openssl returns a const SSL_METHOD using ink_ssl_method_t = const SSL_METHOD *; #else typedef SSL_METHOD *ink_ssl_method_t; #endif int verify_callback(int preverify_ok, X509_STORE_CTX *ctx) { X509 *cert; int depth; int err; SSL *ssl; SSLDebug("Entered verify cb"); depth = X509_STORE_CTX_get_error_depth(ctx); cert = X509_STORE_CTX_get_current_cert(ctx); err = X509_STORE_CTX_get_error(ctx); /* * Retrieve the pointer to the SSL of the connection currently treated * and the application specific data stored into the SSL object. */ ssl = static_cast<SSL *>(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx())); SSLNetVConnection *netvc = SSLNetVCAccess(ssl); if (!preverify_ok) { // Don't bother to check the hostname if we failed openssl's verification SSLDebug("verify error:num=%d:%s:depth=%d", err, X509_verify_cert_error_string(err), depth); if (netvc && netvc->options.clientVerificationFlag == 2) { if (netvc->options.sni_servername) Warning("Hostname verification failed for (%s) but still continuing with the connection establishment", netvc->options.sni_servername.get()); else Warning("Server certificate verification failed but still continuing with the connection establishment"); return 1; } return preverify_ok; } if (depth != 0) { // Not server cert.... return preverify_ok; } if (netvc != nullptr) { netvc->callHooks(TS_EVENT_SSL_SERVER_VERIFY_HOOK); // Match SNI if present if (netvc->options.sni_servername) { char *matched_name = nullptr; if (validate_hostname(cert, reinterpret_cast<unsigned char *>(netvc->options.sni_servername.get()), false, &matched_name)) { SSLDebug("Hostname %s verified OK, matched %s", netvc->options.sni_servername.get(), matched_name); ats_free(matched_name); return preverify_ok; } Warning("Hostname verification failed for (%s)", netvc->options.sni_servername.get()); } // Otherwise match by IP else { char buff[INET6_ADDRSTRLEN]; ats_ip_ntop(netvc->get_remote_addr(), buff, INET6_ADDRSTRLEN); if (validate_hostname(cert, reinterpret_cast<unsigned char *>(buff), true, nullptr)) { SSLDebug("IP %s verified OK", buff); return preverify_ok; } Warning("IP verification failed for (%s)", buff); } if (netvc->options.clientVerificationFlag == 2) { Warning("Server certificate verification failed but continuing with the connection establishment:%s", netvc->options.sni_servername.get()); return preverify_ok; } return 0; } return preverify_ok; } SSL_CTX * SSLInitClientContext(const SSLConfigParams *params) { ink_ssl_method_t meth = nullptr; SSL_CTX *client_ctx = nullptr; char *clientKeyPtr = nullptr; // Note that we do not call RAND_seed() explicitly here, we depend on OpenSSL // to do the seeding of the PRNG for us. This is the case for all platforms that // has /dev/urandom for example. meth = SSLv23_client_method(); client_ctx = SSL_CTX_new(meth); // disable selected protocols SSL_CTX_set_options(client_ctx, params->ssl_ctx_options); if (!client_ctx) { SSLError("cannot create new client context"); ::exit(1); } if (params->ssl_client_ctx_protocols) { SSL_CTX_set_options(client_ctx, params->ssl_client_ctx_protocols); } if (params->client_cipherSuite != nullptr) { if (!SSL_CTX_set_cipher_list(client_ctx, params->client_cipherSuite)) { SSLError("invalid client cipher suite in records.config"); goto fail; } } // if no path is given for the client private key, // assume it is contained in the client certificate file. clientKeyPtr = params->clientKeyPath; if (clientKeyPtr == nullptr) { clientKeyPtr = params->clientCertPath; } if (params->clientCertPath != nullptr) { if (!SSL_CTX_use_certificate_chain_file(client_ctx, params->clientCertPath)) { SSLError("failed to load client certificate from %s", params->clientCertPath); goto fail; } if (!SSL_CTX_use_PrivateKey_file(client_ctx, clientKeyPtr, SSL_FILETYPE_PEM)) { SSLError("failed to load client private key file from %s", clientKeyPtr); goto fail; } if (!SSL_CTX_check_private_key(client_ctx)) { SSLError("client private key (%s) does not match the certificate public key (%s)", clientKeyPtr, params->clientCertPath); goto fail; } } if (params->clientVerify) { SSL_CTX_set_verify(client_ctx, SSL_VERIFY_PEER, verify_callback); SSL_CTX_set_verify_depth(client_ctx, params->client_verify_depth); if (params->clientCACertFilename != nullptr || params->clientCACertPath != nullptr) { if (!SSL_CTX_load_verify_locations(client_ctx, params->clientCACertFilename, params->clientCACertPath)) { SSLError("invalid client CA Certificate file (%s) or CA Certificate path (%s)", params->clientCACertFilename, params->clientCACertPath); goto fail; } } if (!SSL_CTX_set_default_verify_paths(client_ctx)) { SSLError("failed to set the default verify paths"); goto fail; } } if (SSLConfigParams::init_ssl_ctx_cb) { SSLConfigParams::init_ssl_ctx_cb(client_ctx, false); } return client_ctx; fail: SSLReleaseContext(client_ctx); ::exit(1); } <commit_msg>Log IP address in case servername is not present<commit_after>/** @file @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "ts/ink_config.h" #include "records/I_RecHttp.h" #include "ts/ink_platform.h" #include "ts/X509HostnameValidator.h" #include "P_Net.h" #include "P_SSLClientUtils.h" #include <openssl/err.h> #include <openssl/pem.h> #if (OPENSSL_VERSION_NUMBER >= 0x10000000L) // openssl returns a const SSL_METHOD using ink_ssl_method_t = const SSL_METHOD *; #else typedef SSL_METHOD *ink_ssl_method_t; #endif int verify_callback(int preverify_ok, X509_STORE_CTX *ctx) { X509 *cert; int depth; int err; SSL *ssl; SSLDebug("Entered verify cb"); depth = X509_STORE_CTX_get_error_depth(ctx); cert = X509_STORE_CTX_get_current_cert(ctx); err = X509_STORE_CTX_get_error(ctx); /* * Retrieve the pointer to the SSL of the connection currently treated * and the application specific data stored into the SSL object. */ ssl = static_cast<SSL *>(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx())); SSLNetVConnection *netvc = SSLNetVCAccess(ssl); if (!preverify_ok) { // Don't bother to check the hostname if we failed openssl's verification SSLDebug("verify error:num=%d:%s:depth=%d", err, X509_verify_cert_error_string(err), depth); if (netvc && netvc->options.clientVerificationFlag == 2) { if (netvc->options.sni_servername) Warning("Hostname verification failed for (%s) but still continuing with the connection establishment", netvc->options.sni_servername.get()); else { char buff[INET6_ADDRSTRLEN]; ats_ip_ntop(netvc->get_remote_addr(), buff, INET6_ADDRSTRLEN); Warning("Server certificate verification failed for %s but still continuing with the connection establishment", buff); } return 1; } return preverify_ok; } if (depth != 0) { // Not server cert.... return preverify_ok; } if (netvc != nullptr) { netvc->callHooks(TS_EVENT_SSL_SERVER_VERIFY_HOOK); // Match SNI if present if (netvc->options.sni_servername) { char *matched_name = nullptr; if (validate_hostname(cert, reinterpret_cast<unsigned char *>(netvc->options.sni_servername.get()), false, &matched_name)) { SSLDebug("Hostname %s verified OK, matched %s", netvc->options.sni_servername.get(), matched_name); ats_free(matched_name); return preverify_ok; } Warning("Hostname verification failed for (%s)", netvc->options.sni_servername.get()); } // Otherwise match by IP else { char buff[INET6_ADDRSTRLEN]; ats_ip_ntop(netvc->get_remote_addr(), buff, INET6_ADDRSTRLEN); if (validate_hostname(cert, reinterpret_cast<unsigned char *>(buff), true, nullptr)) { SSLDebug("IP %s verified OK", buff); return preverify_ok; } Warning("IP verification failed for (%s)", buff); } if (netvc->options.clientVerificationFlag == 2) { char buff[INET6_ADDRSTRLEN]; ats_ip_ntop(netvc->get_remote_addr(), buff, INET6_ADDRSTRLEN); Warning("Server certificate verification failed but continuing with the connection establishment:%s:%s", netvc->options.sni_servername.get(), buff); return preverify_ok; } return 0; } return preverify_ok; } SSL_CTX * SSLInitClientContext(const SSLConfigParams *params) { ink_ssl_method_t meth = nullptr; SSL_CTX *client_ctx = nullptr; char *clientKeyPtr = nullptr; // Note that we do not call RAND_seed() explicitly here, we depend on OpenSSL // to do the seeding of the PRNG for us. This is the case for all platforms that // has /dev/urandom for example. meth = SSLv23_client_method(); client_ctx = SSL_CTX_new(meth); // disable selected protocols SSL_CTX_set_options(client_ctx, params->ssl_ctx_options); if (!client_ctx) { SSLError("cannot create new client context"); ::exit(1); } if (params->ssl_client_ctx_protocols) { SSL_CTX_set_options(client_ctx, params->ssl_client_ctx_protocols); } if (params->client_cipherSuite != nullptr) { if (!SSL_CTX_set_cipher_list(client_ctx, params->client_cipherSuite)) { SSLError("invalid client cipher suite in records.config"); goto fail; } } // if no path is given for the client private key, // assume it is contained in the client certificate file. clientKeyPtr = params->clientKeyPath; if (clientKeyPtr == nullptr) { clientKeyPtr = params->clientCertPath; } if (params->clientCertPath != nullptr) { if (!SSL_CTX_use_certificate_chain_file(client_ctx, params->clientCertPath)) { SSLError("failed to load client certificate from %s", params->clientCertPath); goto fail; } if (!SSL_CTX_use_PrivateKey_file(client_ctx, clientKeyPtr, SSL_FILETYPE_PEM)) { SSLError("failed to load client private key file from %s", clientKeyPtr); goto fail; } if (!SSL_CTX_check_private_key(client_ctx)) { SSLError("client private key (%s) does not match the certificate public key (%s)", clientKeyPtr, params->clientCertPath); goto fail; } } if (params->clientVerify) { SSL_CTX_set_verify(client_ctx, SSL_VERIFY_PEER, verify_callback); SSL_CTX_set_verify_depth(client_ctx, params->client_verify_depth); if (params->clientCACertFilename != nullptr || params->clientCACertPath != nullptr) { if (!SSL_CTX_load_verify_locations(client_ctx, params->clientCACertFilename, params->clientCACertPath)) { SSLError("invalid client CA Certificate file (%s) or CA Certificate path (%s)", params->clientCACertFilename, params->clientCACertPath); goto fail; } } if (!SSL_CTX_set_default_verify_paths(client_ctx)) { SSLError("failed to set the default verify paths"); goto fail; } } if (SSLConfigParams::init_ssl_ctx_cb) { SSLConfigParams::init_ssl_ctx_cb(client_ctx, false); } return client_ctx; fail: SSLReleaseContext(client_ctx); ::exit(1); } <|endoftext|>
<commit_before>#include <netdb.h> #include <unistd.h> #include <sys/fcntl.h> #include "client.h" #include "duckchat.h" #include "raw.h" // Variables struct sockaddr_in client_addr; struct sockaddr_in server_addr; int client_socket; struct addrinfo *server_info; char *channel; // Prints an error message and exits the program. void Error(const char *msg) { std::cerr << msg << std::endl; exit(1); } // Connects to the server at a the given port. void Connect(char *domain, const char *port) { std::cout << "Connecting to " << domain << std::endl; struct addrinfo hints; struct addrinfo *server_info_tmp; int status; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = 0; if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) { std::cerr << "client: unable to resolve address: " << gai_strerror(status) << std::endl; exit(1); } // getaddrinfo() returns a list of address structures into server_info_tmp. // Try each address until we successfully connect(). // If socket() (or connect()) fails, close the socket and try the next address. for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) { if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) { continue; } if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) { fcntl(client_socket, F_SETFL, O_NONBLOCK); break; // Success } close(client_socket); } if (server_info == NULL) { Error("client: all sockets failed to connect"); } } // Sends a message to all users in on the active channel. int RequestSay(const char *message) { struct request_say say; memset(&say, 0, sizeof(say)); say.req_type = REQ_SAY; strncpy(say.req_text, message, SAY_MAX); strncpy(say.req_channel, channel, CHANNEL_MAX); if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to send message\n"); } return 0; } // Sends login requests to the server. int RequestLogin(char *username) { struct request_login login; memset(&login, 0, sizeof(login)); login.req_type = REQ_LOGIN; strncpy(login.req_username, username, USERNAME_MAX); size_t message_size = sizeof(struct request_login); if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request login\n"); } return 0; } // Sends logout requests to the server. int RequestLogout() { struct request_logout logout; memset((char *) &logout, 0, sizeof(logout)); logout.req_type = REQ_LOGOUT; size_t message_size = sizeof(struct request_logout); if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request logout\n"); } return 0; } // Sends join requests to the server. int RequestJoin(char *channel) { struct request_join join; memset((char *) &join, 0, sizeof(join)); join.req_type = REQ_JOIN; strncpy(join.req_channel, channel, CHANNEL_MAX); size_t message_size = sizeof(struct request_join); if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request join\n"); } return 0; } // Splits strings around spaces. std::vector<std::string> StringSplit(std::string input) { std::istringstream iss(input); std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}}; return result; } // Splits strings around spaces. std::vector<std::string> SplitString(char *input, char delimiter) { std::vector<std::string> result; std::string word = ""; size_t input_size = strlen(input); for (size_t i = 0; i < input_size; i++) { if (input[i] != delimiter) { word += input[i]; } else { result.push_back(word); word = ""; } } result.push_back(word); return result; } void StripChar(char *input, char c) { size_t size = strlen(input); for (size_t i = 0; i < size; i++) { if (input[i] == c) { input[i] = '\0'; } } } // Processes the input string to decide what type of command it is. bool ProcessInput(std::string input) { std::vector<std::string> inputs = StringSplit(input); bool result = true; if (inputs[0] == "/exit") { RequestLogout(); // cooked_mode(); result = false; } else if (inputs[0] == "/list") { } else if (inputs[0] == "/join") { } else if (inputs[0] == "/leave") { } else if (inputs[0] == "/who") { } else if (inputs[0] == "/switch") { } else { std::cout << "\n*Unknown command" << std::endl; } return result; } char inBuffer[SAY_MAX + 1]; char *bufPosition = inBuffer; char *NewInputString() { char c = getchar(); if (c == '\n') { *bufPosition ++= '\0'; bufPosition= inBuffer; printf("\n"); fflush(stdout); return inBuffer; } else if (((int) c) == 127) { // Check for backspace if (bufPosition > inBuffer) { --bufPosition; printf("\b"); fflush(stdout); } // Trap case where no more to delete } else if (bufPosition != inBuffer + SAY_MAX) { *bufPosition++ = c; printf("%c", c); fflush(stdout); return NULL; } return NULL; } int main(int argc, char *argv[]) { char *domain; char *port_str; int port_num; char *username; char *input; char tmp_buffer[SAY_MAX]; memset(&tmp_buffer, 0, SAY_MAX); // struct timeval timeout; fd_set read_set; // int file_desc = 0; int result; char receive_buffer[kBufferSize]; memset(&receive_buffer, 0, kBufferSize); char stdin_buffer[kBufferSize]; memset(&stdin_buffer, 0, kBufferSize); if (argc < 4) { Error("usage: client [server name] [port] [username]"); } domain = argv[1]; port_str = argv[2]; port_num = atoi(argv[2]); username = argv[3]; if (strlen(domain) > UNIX_PATH_MAX) { Error("client: server name must be less than 108 characters"); } if (port_num < 0 || port_num > 65535) { Error("client: port number must be between 0 and 65535"); } if (strlen(username) > USERNAME_MAX) { Error("client: username must be less than 32 characters"); } Connect(domain, port_str); RequestLogin(username); channel = (char *) "Common"; RequestJoin(channel); // TODO handle response from send if (raw_mode() != 0){ Error("client: error using raw mode"); } std::cout << ">" << std::flush; while (1) { FD_ZERO(&read_set); FD_SET(client_socket, &read_set); FD_SET(STDIN_FILENO, &read_set); if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) { Error("client: problem using select"); } if (result > 0) { if (FD_ISSET(STDIN_FILENO, &read_set)) { // char c = (char) getchar(); // *bufPosition++ = c; // printf("%c", c); // fflush(stdout); // int read_stdin_size = read(STDIN_FILENO, stdin_buffer, kBufferSize); input = NewInputString(); if (strlen(input) != 0) { if (input[0] == '/') { ProcessInput(input); } else { // Send chat messages // StripChar(stdin_buffer, '\n'); RequestSay(input); } } memset(&stdin_buffer, 0, kBufferSize); } // end of if STDIN_FILENO if (FD_ISSET(client_socket, &read_set)) { // Socket has data int read_size = read(client_socket, receive_buffer, kBufferSize); if (read_size != 0) { // TODO capture user input, store, clean input, then print buffer, afterward replace input struct text message; memcpy(&message, receive_buffer, sizeof(struct text)); text_t text_type = message.txt_type; switch (text_type) { case TXT_SAY: struct text_say say; memcpy(&say, receive_buffer, sizeof(struct text_say)); // std::cin.readsome(tmp_buffer, sizeof(tmp_buffer)); std::cout << "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"; std::cout << "[" << say.txt_channel << "]" << "[" << say.txt_username << "]: " << say.txt_text << std::endl; std::cout << ">" << tmp_buffer << std::flush; memset(&tmp_buffer, 0, SAY_MAX); break; default: break; } } memset(&receive_buffer, 0, SAY_MAX); } // end of if client_socket } // end of if result } // end of while return 0; }<commit_msg>NewInputString test 2<commit_after>#include <netdb.h> #include <unistd.h> #include <sys/fcntl.h> #include "client.h" #include "duckchat.h" #include "raw.h" // Variables struct sockaddr_in client_addr; struct sockaddr_in server_addr; int client_socket; struct addrinfo *server_info; char *channel; // Prints an error message and exits the program. void Error(const char *msg) { std::cerr << msg << std::endl; exit(1); } // Connects to the server at a the given port. void Connect(char *domain, const char *port) { std::cout << "Connecting to " << domain << std::endl; struct addrinfo hints; struct addrinfo *server_info_tmp; int status; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = 0; if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) { std::cerr << "client: unable to resolve address: " << gai_strerror(status) << std::endl; exit(1); } // getaddrinfo() returns a list of address structures into server_info_tmp. // Try each address until we successfully connect(). // If socket() (or connect()) fails, close the socket and try the next address. for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) { if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) { continue; } if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) { fcntl(client_socket, F_SETFL, O_NONBLOCK); break; // Success } close(client_socket); } if (server_info == NULL) { Error("client: all sockets failed to connect"); } } // Sends a message to all users in on the active channel. int RequestSay(const char *message) { struct request_say say; memset(&say, 0, sizeof(say)); say.req_type = REQ_SAY; strncpy(say.req_text, message, SAY_MAX); strncpy(say.req_channel, channel, CHANNEL_MAX); if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to send message\n"); } return 0; } // Sends login requests to the server. int RequestLogin(char *username) { struct request_login login; memset(&login, 0, sizeof(login)); login.req_type = REQ_LOGIN; strncpy(login.req_username, username, USERNAME_MAX); size_t message_size = sizeof(struct request_login); if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request login\n"); } return 0; } // Sends logout requests to the server. int RequestLogout() { struct request_logout logout; memset((char *) &logout, 0, sizeof(logout)); logout.req_type = REQ_LOGOUT; size_t message_size = sizeof(struct request_logout); if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request logout\n"); } return 0; } // Sends join requests to the server. int RequestJoin(char *channel) { struct request_join join; memset((char *) &join, 0, sizeof(join)); join.req_type = REQ_JOIN; strncpy(join.req_channel, channel, CHANNEL_MAX); size_t message_size = sizeof(struct request_join); if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request join\n"); } return 0; } // Splits strings around spaces. std::vector<std::string> StringSplit(std::string input) { std::istringstream iss(input); std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}}; return result; } // Splits strings around spaces. std::vector<std::string> SplitString(char *input, char delimiter) { std::vector<std::string> result; std::string word = ""; size_t input_size = strlen(input); for (size_t i = 0; i < input_size; i++) { if (input[i] != delimiter) { word += input[i]; } else { result.push_back(word); word = ""; } } result.push_back(word); return result; } void StripChar(char *input, char c) { size_t size = strlen(input); for (size_t i = 0; i < size; i++) { if (input[i] == c) { input[i] = '\0'; } } } // Processes the input string to decide what type of command it is. bool ProcessInput(std::string input) { std::vector<std::string> inputs = StringSplit(input); bool result = true; if (inputs[0] == "/exit") { RequestLogout(); // cooked_mode(); result = false; } else if (inputs[0] == "/list") { } else if (inputs[0] == "/join") { } else if (inputs[0] == "/leave") { } else if (inputs[0] == "/who") { } else if (inputs[0] == "/switch") { } else { std::cout << "\n*Unknown command" << std::endl; } return result; } char inBuffer[SAY_MAX + 1]; char *bufPosition = inBuffer; char *NewInputString() { char c = (char) getchar(); if (c == '\n') { *bufPosition ++= '\0'; bufPosition = inBuffer; printf("\n"); fflush(stdout); return inBuffer; } else if (((int) c) == 127) { // Check for backspace if (bufPosition > inBuffer) { --bufPosition; printf("\b"); fflush(stdout); } // Trap case where no more to delete } else if (bufPosition != inBuffer + SAY_MAX) { *bufPosition++ = c; printf("%c", c); fflush(stdout); return NULL; } return NULL; } int main(int argc, char *argv[]) { char *domain; char *port_str; int port_num; char *username; char *input; char tmp_buffer[SAY_MAX]; memset(&tmp_buffer, 0, SAY_MAX); // struct timeval timeout; fd_set read_set; // int file_desc = 0; int result; char receive_buffer[kBufferSize]; memset(&receive_buffer, 0, kBufferSize); char stdin_buffer[kBufferSize]; memset(&stdin_buffer, 0, kBufferSize); if (argc < 4) { Error("usage: client [server name] [port] [username]"); } domain = argv[1]; port_str = argv[2]; port_num = atoi(argv[2]); username = argv[3]; if (strlen(domain) > UNIX_PATH_MAX) { Error("client: server name must be less than 108 characters"); } if (port_num < 0 || port_num > 65535) { Error("client: port number must be between 0 and 65535"); } if (strlen(username) > USERNAME_MAX) { Error("client: username must be less than 32 characters"); } Connect(domain, port_str); RequestLogin(username); channel = (char *) "Common"; RequestJoin(channel); // TODO handle response from send if (raw_mode() != 0){ Error("client: error using raw mode"); } std::cout << ">" << std::flush; while (1) { FD_ZERO(&read_set); FD_SET(client_socket, &read_set); FD_SET(STDIN_FILENO, &read_set); if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) { Error("client: problem using select"); } if (result > 0) { if (FD_ISSET(STDIN_FILENO, &read_set)) { // char c = (char) getchar(); // *bufPosition++ = c; // printf("%c", c); // fflush(stdout); // int read_stdin_size = read(STDIN_FILENO, stdin_buffer, kBufferSize); input = NewInputString(); if (input[strlen(input)] == '\n') { if (input[0] == '/') { ProcessInput(input); } else { // Send chat messages // StripChar(stdin_buffer, '\n'); RequestSay(input); } } memset(&stdin_buffer, 0, kBufferSize); } // end of if STDIN_FILENO if (FD_ISSET(client_socket, &read_set)) { // Socket has data int read_size = read(client_socket, receive_buffer, kBufferSize); if (read_size != 0) { // TODO capture user input, store, clean input, then print buffer, afterward replace input struct text message; memcpy(&message, receive_buffer, sizeof(struct text)); text_t text_type = message.txt_type; switch (text_type) { case TXT_SAY: struct text_say say; memcpy(&say, receive_buffer, sizeof(struct text_say)); // std::cin.readsome(tmp_buffer, sizeof(tmp_buffer)); std::cout << "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"; std::cout << "[" << say.txt_channel << "]" << "[" << say.txt_username << "]: " << say.txt_text << std::endl; std::cout << ">" << tmp_buffer << std::flush; memset(&tmp_buffer, 0, SAY_MAX); break; default: break; } } memset(&receive_buffer, 0, SAY_MAX); } // end of if client_socket } // end of if result } // end of while return 0; }<|endoftext|>
<commit_before>#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <stdio.h> #include <iostream> #include <fstream> #include <boost/lexical_cast.hpp> #include "packet.h" #define BUFSIZE 121 #define FILENAME "Testfile" #define TEST_FILENAME "Testfile2" #define PORT 10038 #define PAKSIZE 128 #define ACK 0 #define NAK 1 using namespace std; bool gremlin(Packet * pack, int corruptProb, int lossProb); bool init(int argc, char** argv); bool loadFile(); bool sendFile(); bool getFile(); char * recvPkt(); bool isvpack(unsigned char * p); Packet createPacket(int index); bool sendPacket(); bool isAck(); void handleAck(); void handleNak(int& x); int seqNum; int s; int probCorrupt; int probLoss; string hs; short int port; char * file; unsigned char* window[16]; //packet window int windowBase; //used to determine position in window of arriving packets int length; struct sockaddr_in a; struct sockaddr_in sa; socklen_t salen; string fstr; bool dropPck; Packet p; int delayT; unsigned char b[BUFSIZE]; int main(int argc, char** argv) { if(!init(argc, argv)) return -1; if(sendto(s, "GET Testfile", BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) { cout << "Package sending failed. (socket s, server address sa, message m)" << endl; return false; } getFile(); return 0; } bool init(int argc, char** argv) { windowBase = 0; //initialize windowBase s = 0; hs = string("131.204.14.") + argv[1]; /* Needs to be updated? Might be a string like "tux175.engr.auburn.edu." */ port = 10038; /* Can be any port within 10038-10041, inclusive. */ char* delayTStr = argv[2]; delayT = boost::lexical_cast<int>(delayTStr); /*if(!loadFile()) { cout << "Loading file failed. (filename FILENAME)" << endl; return false; }*/ if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { cout << "Socket creation failed. (socket s)" << endl; return false; } memset((char *)&a, 0, sizeof(a)); a.sin_family = AF_INET; a.sin_addr.s_addr = htonl(INADDR_ANY); //why does this always give us 0? a.sin_port = htons(0); if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0){ cout << "Socket binding failed. (socket s, address a)" << endl; return false; } memset((char *)&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(port); inet_pton(AF_INET, hs.c_str(), &(sa.sin_addr)); cout << endl; cout << "Server address (inet mode): " << inet_ntoa(sa.sin_addr) << endl; cout << "Port: " << ntohs(sa.sin_port) << endl; cout << endl << endl; /*fstr = string(file); cout << "File: " << endl << fstr << endl << endl;*/ seqNum = 0; dropPck = false; return true; } bool loadFile() { ifstream is (FILENAME, ifstream::binary); if(is) { is.seekg(0, is.end); length = is.tellg(); is.seekg(0, is.beg); file = new char[length]; cout << "Reading " << length << " characters..." << endl; is.read(file, length); if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; } is.close(); } return true; } bool sendFile() { for(int x = 0; x <= length / BUFSIZE; x++) { p = createPacket(x); if(!sendPacket()) continue; if(isAck()) { handleAck(); } else { handleNak(x); } memset(b, 0, BUFSIZE); } return true; } Packet createPacket(int index){ cout << endl; cout << "=== TRANSMISSION START" << endl; string mstr = fstr.substr(index * BUFSIZE, BUFSIZE); if(index * BUFSIZE + BUFSIZE > length) { mstr[length - (index * BUFSIZE)] = '\0'; } return Packet (seqNum, mstr.c_str()); } bool sendPacket(){ int pc = probCorrupt; int pl = probLoss; if((dropPck = gremlin(&p, pc, pl)) == false){ if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) { cout << "Package sending failed. (socket s, server address sa, message m)" << endl; return false; } return true; } else return false; } bool isAck() { recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&sa, &salen); cout << endl << "=== SERVER RESPONSE TEST" << endl; cout << "Data: " << b << endl; if(b[6] == '0') return true; else return false; } void handleAck() { } void handleNak(int& x) { char * sns = new char[2]; memcpy(sns, &b[0], 1); sns[1] = '\0'; char * css = new char[5]; memcpy(css, &b[1], 5); char * db = new char[BUFSIZE + 1]; memcpy(db, &b[2], BUFSIZE); db[BUFSIZE] = '\0'; cout << "Sequence number: " << sns << endl; cout << "Checksum: " << css << endl; Packet pk (0, db); pk.setSequenceNum(boost::lexical_cast<int>(sns)); pk.setCheckSum(boost::lexical_cast<int>(css)); if(!pk.chksm()) x--; else x = (x - 2 > 0) ? x - 2 : 0; } bool gremlin(Packet * pack, int corruptProb, int lossProb){ bool dropPacket = false; int r = rand() % 100; cout << "Corruption probability: " << corruptProb << endl; cout << "Random number: " << r << endl; if(r <= (lossProb)){ dropPacket = true; cout << "Dropped!" << endl; } else if(r <= (corruptProb)){ cout << "Corrupted!" << endl; pack->loadDataBuffer((char*)"GREMLIN LOL"); } else seqNum = (seqNum) ? false : true; cout << "Seq. num: " << pack->getSequenceNum() << endl; cout << "Checksum: " << pack->getCheckSum() << endl; cout << "Message: " << pack->getDataBuffer() << endl; return dropPacket; } bool isvpack(unsigned char * p) { cout << endl << "=== IS VALID PACKET TESTING" << endl; char * sns = new char[2]; memcpy(sns, &p[0], 1); sns[1] = '\0'; char * css = new char[6]; memcpy(css, &p[1], 6); css[5] = '\0'; char * db = new char[121 + 1]; memcpy(db, &p[7], 121); db[121] = '\0'; cout << "Seq. num: " << sns << endl; cout << "Checksum: " << css << endl; cout << "Message: " << db << endl; int sn = boost::lexical_cast<int>(sns); int cs = boost::lexical_cast<int>(css); Packet pk (0, db); pk.setSequenceNum(sn); // change to validate based on checksum and sequence number if(sn == seqNum) return false; if(cs != pk.generateCheckSum()) return false; return true; } bool getFile(){ /* Loop forever, waiting for messages from a client. */ cout << "Waiting on port " << PORT << "..." << endl; ofstream file("Dumpfile"); int rlen; int ack; for (;;) { unsigned char packet[PAKSIZE + 1]; unsigned char dataPull[PAKSIZE - 7 + 1]; rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&sa, &salen); /* Begin Window Loading */ int tempSeqNum = boost::lexical_cast<int>(packet[0]); int properIndex = tempSeqNum - windowBase; window[properIndex] = packet; cout << "Packet loaded into window" << endl; char* tempTest = new char[6]; memcpy(tempTest, &window[1], 0); tempTest[5] = '\0'; cout << "The Checksum pulled from client window: " << tempTest[0] << endl; for(int x = 0; x < PAKSIZE - 7; x++) { dataPull[x] = packet[x + 7]; } dataPull[PAKSIZE - 7] = '\0'; packet[PAKSIZE] = '\0'; if (rlen > 0) { char * css = new char[6]; memcpy(css, &packet[1], 5); css[5] = '\0'; cout << endl << endl << "=== RECEIPT" << endl; cout << "Seq. num: " << packet[0] << endl; cout << "Checksum: " << css << endl; cout << "Received message: " << dataPull << endl; if(isvpack(packet)) { ack = ACK; if(boost::lexical_cast<int>(packet[0]) == windowBase) windowBase++; //increment base of window //FIXME file << dataPull; file.flush(); } else { ack = NAK; } cout << "Sent response: "; cout << ((ack == ACK) ? "ACK" : "NAK") << endl; if(packet[6] == '1') usleep(delayT*1000); if(sendto(s, boost::lexical_cast<char>(windowBase), PAKSIZE, 0, (struct sockaddr *)&sa, salen) < 0) { cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl; return 0; } delete css; } } file.close(); return true; } <commit_msg>Send windowBase on ACK<commit_after>#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <stdio.h> #include <iostream> #include <fstream> #include <boost/lexical_cast.hpp> #include "packet.h" #define BUFSIZE 121 #define FILENAME "Testfile" #define TEST_FILENAME "Testfile2" #define PORT 10038 #define PAKSIZE 128 #define ACK 0 #define NAK 1 using namespace std; bool gremlin(Packet * pack, int corruptProb, int lossProb); bool init(int argc, char** argv); bool loadFile(); bool sendFile(); bool getFile(); char * recvPkt(); bool isvpack(unsigned char * p); Packet createPacket(int index); bool sendPacket(); bool isAck(); void handleAck(); void handleNak(int& x); int seqNum; int s; int probCorrupt; int probLoss; string hs; short int port; char * file; unsigned char* window[16]; //packet window int windowBase; //used to determine position in window of arriving packets int length; struct sockaddr_in a; struct sockaddr_in sa; socklen_t salen; string fstr; bool dropPck; Packet p; int delayT; unsigned char b[BUFSIZE]; int main(int argc, char** argv) { if(!init(argc, argv)) return -1; if(sendto(s, "GET Testfile", BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) { cout << "Package sending failed. (socket s, server address sa, message m)" << endl; return false; } getFile(); return 0; } bool init(int argc, char** argv) { windowBase = 0; //initialize windowBase s = 0; hs = string("131.204.14.") + argv[1]; /* Needs to be updated? Might be a string like "tux175.engr.auburn.edu." */ port = 10038; /* Can be any port within 10038-10041, inclusive. */ char* delayTStr = argv[2]; delayT = boost::lexical_cast<int>(delayTStr); /*if(!loadFile()) { cout << "Loading file failed. (filename FILENAME)" << endl; return false; }*/ if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { cout << "Socket creation failed. (socket s)" << endl; return false; } memset((char *)&a, 0, sizeof(a)); a.sin_family = AF_INET; a.sin_addr.s_addr = htonl(INADDR_ANY); //why does this always give us 0? a.sin_port = htons(0); if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0){ cout << "Socket binding failed. (socket s, address a)" << endl; return false; } memset((char *)&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(port); inet_pton(AF_INET, hs.c_str(), &(sa.sin_addr)); cout << endl; cout << "Server address (inet mode): " << inet_ntoa(sa.sin_addr) << endl; cout << "Port: " << ntohs(sa.sin_port) << endl; cout << endl << endl; /*fstr = string(file); cout << "File: " << endl << fstr << endl << endl;*/ seqNum = 0; dropPck = false; return true; } bool loadFile() { ifstream is (FILENAME, ifstream::binary); if(is) { is.seekg(0, is.end); length = is.tellg(); is.seekg(0, is.beg); file = new char[length]; cout << "Reading " << length << " characters..." << endl; is.read(file, length); if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; } is.close(); } return true; } bool sendFile() { for(int x = 0; x <= length / BUFSIZE; x++) { p = createPacket(x); if(!sendPacket()) continue; if(isAck()) { handleAck(); } else { handleNak(x); } memset(b, 0, BUFSIZE); } return true; } Packet createPacket(int index){ cout << endl; cout << "=== TRANSMISSION START" << endl; string mstr = fstr.substr(index * BUFSIZE, BUFSIZE); if(index * BUFSIZE + BUFSIZE > length) { mstr[length - (index * BUFSIZE)] = '\0'; } return Packet (seqNum, mstr.c_str()); } bool sendPacket(){ int pc = probCorrupt; int pl = probLoss; if((dropPck = gremlin(&p, pc, pl)) == false){ if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) { cout << "Package sending failed. (socket s, server address sa, message m)" << endl; return false; } return true; } else return false; } bool isAck() { recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&sa, &salen); cout << endl << "=== SERVER RESPONSE TEST" << endl; cout << "Data: " << b << endl; if(b[6] == '0') return true; else return false; } void handleAck() { } void handleNak(int& x) { char * sns = new char[2]; memcpy(sns, &b[0], 1); sns[1] = '\0'; char * css = new char[5]; memcpy(css, &b[1], 5); char * db = new char[BUFSIZE + 1]; memcpy(db, &b[2], BUFSIZE); db[BUFSIZE] = '\0'; cout << "Sequence number: " << sns << endl; cout << "Checksum: " << css << endl; Packet pk (0, db); pk.setSequenceNum(boost::lexical_cast<int>(sns)); pk.setCheckSum(boost::lexical_cast<int>(css)); if(!pk.chksm()) x--; else x = (x - 2 > 0) ? x - 2 : 0; } bool gremlin(Packet * pack, int corruptProb, int lossProb){ bool dropPacket = false; int r = rand() % 100; cout << "Corruption probability: " << corruptProb << endl; cout << "Random number: " << r << endl; if(r <= (lossProb)){ dropPacket = true; cout << "Dropped!" << endl; } else if(r <= (corruptProb)){ cout << "Corrupted!" << endl; pack->loadDataBuffer((char*)"GREMLIN LOL"); } else seqNum = (seqNum) ? false : true; cout << "Seq. num: " << pack->getSequenceNum() << endl; cout << "Checksum: " << pack->getCheckSum() << endl; cout << "Message: " << pack->getDataBuffer() << endl; return dropPacket; } bool isvpack(unsigned char * p) { cout << endl << "=== IS VALID PACKET TESTING" << endl; char * sns = new char[2]; memcpy(sns, &p[0], 1); sns[1] = '\0'; char * css = new char[6]; memcpy(css, &p[1], 6); css[5] = '\0'; char * db = new char[121 + 1]; memcpy(db, &p[7], 121); db[121] = '\0'; cout << "Seq. num: " << sns << endl; cout << "Checksum: " << css << endl; cout << "Message: " << db << endl; int sn = boost::lexical_cast<int>(sns); int cs = boost::lexical_cast<int>(css); Packet pk (0, db); pk.setSequenceNum(sn); // change to validate based on checksum and sequence number if(sn == seqNum) return false; if(cs != pk.generateCheckSum()) return false; return true; } bool getFile(){ /* Loop forever, waiting for messages from a client. */ cout << "Waiting on port " << PORT << "..." << endl; ofstream file("Dumpfile"); int rlen; int ack; for (;;) { unsigned char packet[PAKSIZE + 1]; unsigned char dataPull[PAKSIZE - 7 + 1]; rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&sa, &salen); /* Begin Window Loading */ int tempSeqNum = boost::lexical_cast<int>(packet[0]); int properIndex = tempSeqNum - windowBase; window[properIndex] = packet; cout << "Packet loaded into window" << endl; char* tempTest = new char[6]; memcpy(tempTest, &window[1], 0); tempTest[5] = '\0'; cout << "The Checksum pulled from client window: " << tempTest[0] << endl; for(int x = 0; x < PAKSIZE - 7; x++) { dataPull[x] = packet[x + 7]; } dataPull[PAKSIZE - 7] = '\0'; packet[PAKSIZE] = '\0'; if (rlen > 0) { char * css = new char[6]; memcpy(css, &packet[1], 5); css[5] = '\0'; cout << endl << endl << "=== RECEIPT" << endl; cout << "Seq. num: " << packet[0] << endl; cout << "Checksum: " << css << endl; cout << "Received message: " << dataPull << endl; if(isvpack(packet)) { ack = ACK; if(boost::lexical_cast<int>(packet[0]) == windowBase) windowBase++; //increment base of window //FIXME file << dataPull; file.flush(); } else { ack = NAK; } cout << "Sent response: "; cout << ((ack == ACK) ? "ACK" : "NAK") << endl; if(packet[6] == '1') usleep(delayT*1000); char * ackval; itoa(windowBase, ackval, 10); if(sendto(s, ackval, PAKSIZE, 0, (struct sockaddr *)&sa, salen) < 0) { cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl; return 0; } delete css; } } file.close(); return true; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0xe59a202d585798e44c79618c8fd035f7be118ddf91d7937232d9df2113074569")); static const CCheckpointData data = { &mapCheckpoints, 1391410815, // * UNIX timestamp of last checkpoint block 3520, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 8000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1369685559, 37581, 300 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (fTestNet) return 0; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>Updates<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0xe59a202d585798e44c79618c8fd035f7be118ddf91d7937232d9df2113074569")); static const CCheckpointData data = { &mapCheckpoints, 1391410815, // * UNIX timestamp of last checkpoint block 3520, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 8000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70")); static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1369685559, 37581, 300 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (fTestNet) return 0; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0x5a6495b5f4e54e024c4c75bb6e14795249c3d2cff6326d33e3bb593b25d5e08e")) ( 1000, uint256("0x9d1854b2cc5a7735280324ae3fc5cbfcb3db7d4047be9b5dabfa60e084bab9d4")) ( 5000, uint256("0x4e1f070567e98780b14411ae1695b1a727e7ee827c810a80f01f952ad2c02a91")) ( 10000, uint256("0x795d482c18d4fb6f892177f333bb17668ef147dc87e522453431a88dd717dd47")) ( 20000, uint256("0xc71f39510ba6450c799b70d4c6d1ea3a5e26dc10fc9204eebfb13fcf8d99c0cc")) ( 30000, uint256("0xa61ee1ed671cfaf1b1e71401ed70dcfd448fef5953b9c37de5207d7c08bf5583")) ( 40000, uint256("0x11ac9605754d6adf8ca5400bb6faf0da282f4537c1a7cea89faed7bb2659f6cf")) ; static const CCheckpointData data = { &mapCheckpoints, //1395729444, // * UNIX timestamp of last checkpoint block //2, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) //8000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, //1369685559, //37581, //300 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (fTestNet) return 0; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>Update checkpoints.cpp<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0x5a6495b5f4e54e024c4c75bb6e14795249c3d2cff6326d33e3bb593b25d5e08e")) ( 1000, uint256("0x9d1854b2cc5a7735280324ae3fc5cbfcb3db7d4047be9b5dabfa60e084bab9d4")) ( 5000, uint256("0x4e1f070567e98780b14411ae1695b1a727e7ee827c810a80f01f952ad2c02a91")) ( 10000, uint256("0x795d482c18d4fb6f892177f333bb17668ef147dc87e522453431a88dd717dd47")) ( 20000, uint256("0xc71f39510ba6450c799b70d4c6d1ea3a5e26dc10fc9204eebfb13fcf8d99c0cc")) ( 30000, uint256("0xa61ee1ed671cfaf1b1e71401ed70dcfd448fef5953b9c37de5207d7c08bf5583")) ( 40000, uint256("0x11ac9605754d6adf8ca5400bb6faf0da282f4537c1a7cea89faed7bb2659f6cf")) ( 50000, uint256("0x93a6fbd8db56078d36a0f64b6d745c27c16bb41dbb832bac188f2d0e86fdf655")) ; static const CCheckpointData data = { &mapCheckpoints, //1395729444, // * UNIX timestamp of last checkpoint block //2, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) //8000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, //1369685559, //37581, //300 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (fTestNet) return 0; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before>#include <stan/version.hpp> #include <gtest/gtest.h> TEST(Stan, macro) { EXPECT_EQ(2, STAN_MAJOR); EXPECT_EQ(27, STAN_MINOR); EXPECT_EQ(0, STAN_PATCH); } TEST(Stan, version) { EXPECT_EQ("2", stan::MAJOR_VERSION); EXPECT_EQ("28", stan::MINOR_VERSION); EXPECT_EQ("0", stan::PATCH_VERSION); } <commit_msg>Fixed test version in test/unit/version_test.cpp<commit_after>#include <stan/version.hpp> #include <gtest/gtest.h> TEST(Stan, macro) { EXPECT_EQ(2, STAN_MAJOR); EXPECT_EQ(28, STAN_MINOR); EXPECT_EQ(0, STAN_PATCH); } TEST(Stan, version) { EXPECT_EQ("2", stan::MAJOR_VERSION); EXPECT_EQ("28", stan::MINOR_VERSION); EXPECT_EQ("0", stan::PATCH_VERSION); } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ; static const CCheckpointData data = { &mapCheckpoints, 1363044259, // * UNIX timestamp of last checkpoint block 14264869, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 60000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of // ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70")) ( 0, uint256("0x000076593090c316c69d80e990c770e7a0a511f7d2fc6f26caf8eb66a44d6c40")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1338180505, 16341, 300 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>Added checkpoint<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of (10000, uint256("0x00000000004fdae2eb3349512b6ac4044d96fa32e69855d342e998b20f6ecfce")) ; static const CCheckpointData data = { &mapCheckpoints, 1395464322, // * UNIX timestamp of last checkpoint block 71908, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 5136.3 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of (0, uint256("0x000076593090c316c69d80e990c770e7a0a511f7d2fc6f26caf8eb66a44d6c40")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1338180505, 16341, 300 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions // static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0xb477d9bc0721a1b96547495404583d68123f471fdd1d4058a9adff2fa7452298")) ( 30000, uint256("0xe333edb2a6052a29a0c9f471ec4de5b82a2f8e398fc295db499d2adb1f72b750")) ( 62000, uint256("0xc12547453d2a3995893890e0d73cf4b1fe68f1b6b68e0b407547d6050ba0352f")) ( 81000, uint256("0x08afecfd7028b3448ce283e236f8a0535da611c6f6942d2062e364fe8ca5f95c")) ( 100000, uint256("0x056386351ce37a32a5e6cf3edd90a4a6e4f41a6f1c58d3d4044dfcb762ceb274")) ( 133000, uint256("0x2c9ce87324212f2cba4a63840439c173bf16ba1e6ecf9bbf3e8702b828a8d87b")) ( 222222, uint256("0x9c732c3be5225afda793fc6e515e4d7c8fc50c76fb376497fb9cd238b320b5d3")) ( 333333, uint256("0x2240e1ace3526e5d58e37fd08f12d407bc12887fbebda22b9ff87b39c79abab3")) ( 505000, uint256("0xc989c1ec8ef4dabfd10922831826d27a0d2cc95947b2066e385e280b3bc512cb")) ( 1000000, uint256("0xdf496e3d3d525d330683d700649116a9b3b97868a35111203c662fff5107f4fe")) ; bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight); if (i == mapCheckpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { if (fTestNet) return 0; return mapCheckpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>New checkpoints for faster syncing™<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions // static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0xb477d9bc0721a1b96547495404583d68123f471fdd1d4058a9adff2fa7452298")) ( 30000, uint256("0xe333edb2a6052a29a0c9f471ec4de5b82a2f8e398fc295db499d2adb1f72b750")) ( 62000, uint256("0xc12547453d2a3995893890e0d73cf4b1fe68f1b6b68e0b407547d6050ba0352f")) ( 81000, uint256("0x08afecfd7028b3448ce283e236f8a0535da611c6f6942d2062e364fe8ca5f95c")) ( 100000, uint256("0x056386351ce37a32a5e6cf3edd90a4a6e4f41a6f1c58d3d4044dfcb762ceb274")) ( 133000, uint256("0x2c9ce87324212f2cba4a63840439c173bf16ba1e6ecf9bbf3e8702b828a8d87b")) ( 222222, uint256("0x9c732c3be5225afda793fc6e515e4d7c8fc50c76fb376497fb9cd238b320b5d3")) ( 333333, uint256("0x2240e1ace3526e5d58e37fd08f12d407bc12887fbebda22b9ff87b39c79abab3")) ( 505000, uint256("0xc989c1ec8ef4dabfd10922831826d27a0d2cc95947b2066e385e280b3bc512cb")) ( 1000000, uint256("0xdf496e3d3d525d330683d700649116a9b3b97868a35111203c662fff5107f4fe")) ( 2000000, uint256("0xd8ee546b11171d63f673cdd8f197fd8e474591dda230c4fd6ed64b89410c5058")) ( 3000000, uint256("0xa33706ed9d49a338c171eb9bae11c9dc6fefa41c8a47f5e44cd6e0887eb7e1c6")) ; bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight); if (i == mapCheckpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { if (fTestNet) return 0; return mapCheckpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before>//============================================================================= // // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.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 notice for more information. // // Copyright 2012 Sandia Corporation. // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // //============================================================================= #include "vtkActor.h" #include "vtkCellData.h" #include "vtkDaxMarchingCubes.h" #include "vtkImageData.h" #include "vtkImageMandelbrotSource.h" #include "vtkNew.h" #include "vtkPointData.h" #include "vtkPolyDataMapper.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" namespace { template<typename T> int RunVTKPipeline(T *t, int argc, char* argv[]) { vtkNew<vtkRenderer> ren; vtkNew<vtkRenderWindow> renWin; vtkNew<vtkRenderWindowInteractor> iren; renWin->AddRenderer(ren.GetPointer()); iren->SetRenderWindow(renWin.GetPointer()); vtkNew<vtkDaxMarchingCubes> cubes; cubes->SetInputConnection(t->GetOutputPort()); cubes->SetNumberOfContours(1); cubes->SetValue(0,50.5f); vtkNew<vtkPolyDataMapper> mapper; mapper->SetInputConnection(cubes->GetOutputPort()); vtkNew<vtkActor> actor; actor->SetMapper(mapper.GetPointer()); ren->AddActor(actor.GetPointer()); ren->ResetCamera(); renWin->Render(); int retVal = vtkRegressionTestImage(renWin.GetPointer()); if(retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); retVal = vtkRegressionTester::PASSED; } return (!retVal); } } // Anonymous namespace int TestDaxMarchingCubes(int argc, char* argv[]) { //create the sample grid vtkImageMandelbrotSource *src = vtkImageMandelbrotSource::New(); src->SetWholeExtent(0,250,0,250,0,250); src->Update(); //required so we can set the active scalars //set Iterations as the active scalar, otherwise we don't have an array //to contour on vtkImageData* data = vtkImageData::SafeDownCast(src->GetOutputDataObject(0)); if(data->GetPointData()->HasArray("Iterations") == 0) { //vtkImageMandelbrotSource has changed and this test needs updating return (!vtkRegressionTester::FAILED); //yeah it is weird, but the right way } //setting active scalars data->GetPointData()->SetActiveScalars("Iterations"); //run the pipeline return RunVTKPipeline(src,argc,argv); } <commit_msg>Correct memory leak in DaxMarchingCubes test.<commit_after>//============================================================================= // // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.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 notice for more information. // // Copyright 2012 Sandia Corporation. // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // //============================================================================= #include "vtkActor.h" #include "vtkCellData.h" #include "vtkDaxMarchingCubes.h" #include "vtkImageData.h" #include "vtkImageMandelbrotSource.h" #include "vtkNew.h" #include "vtkPointData.h" #include "vtkPolyDataMapper.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" namespace { template<typename T> int RunVTKPipeline(T *t, int argc, char* argv[]) { vtkNew<vtkRenderer> ren; vtkNew<vtkRenderWindow> renWin; vtkNew<vtkRenderWindowInteractor> iren; renWin->AddRenderer(ren.GetPointer()); iren->SetRenderWindow(renWin.GetPointer()); vtkNew<vtkDaxMarchingCubes> cubes; cubes->SetInputConnection(t->GetOutputPort()); cubes->SetNumberOfContours(1); cubes->SetValue(0,50.5f); vtkNew<vtkPolyDataMapper> mapper; mapper->SetInputConnection(cubes->GetOutputPort()); vtkNew<vtkActor> actor; actor->SetMapper(mapper.GetPointer()); ren->AddActor(actor.GetPointer()); ren->ResetCamera(); renWin->Render(); int retVal = vtkRegressionTestImage(renWin.GetPointer()); if(retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); retVal = vtkRegressionTester::PASSED; } return (!retVal); } } // Anonymous namespace int TestDaxMarchingCubes(int argc, char* argv[]) { //create the sample grid vtkNew<vtkImageMandelbrotSource> src; src->SetWholeExtent(0,250,0,250,0,250); src->Update(); //required so we can set the active scalars //set Iterations as the active scalar, otherwise we don't have an array //to contour on vtkImageData* data = vtkImageData::SafeDownCast(src->GetOutputDataObject(0)); if(data->GetPointData()->HasArray("Iterations") == 0) { //vtkImageMandelbrotSource has changed and this test needs updating return (!vtkRegressionTester::FAILED); //yeah it is weird, but the right way } //setting active scalars data->GetPointData()->SetActiveScalars("Iterations"); //run the pipeline return RunVTKPipeline(src.GetPointer(),argc,argv); } <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <sstream> #include <fstream> #include <vector> #include <string> #include <cstring> #include <stdio.h> #include <stdlib.h> #include "testdriverconfig.h" // SRC and BIN dir definitions #include "specification.h" // parsing spec files #include "common/common.h" #include <zorba/zorba.h> #include <zorba/error_handler.h> #include <zorba/exception.h> #include <zorba/util/file.h> #include <zorbautils/strutil.h> #include <simplestore/simplestore.h> void printFile(std::ostream& os, std::string aInFile, std::string message) { std::cout << message << " " << aInFile << ":" << std::endl; std::ifstream lInFileStream(aInFile.c_str()); if (!lInFileStream) { std::cout << "Error: could not open " << aInFile << std::endl; assert(false); } os << lInFileStream.rdbuf() << std::endl; } // print parts of a file // starting at aStartPos with the length of aLen void printPart(std::ostream& os, std::string aInFile, int aStartPos, int aLen) { char* buffer = new char [aLen]; try { std::ifstream lIn(aInFile.c_str()); lIn.seekg(aStartPos); int lCharsRead = lIn.readsome (buffer, aLen); os.write (buffer, lCharsRead); os.flush(); delete[] buffer; } catch (...) { delete[] buffer; } return; } bool isErrorExpected(zorba::ZorbaException& e, State* aState) { if ( aState->hasErrors) { std::vector<std::string>::const_iterator lIter = aState->theErrors.begin(); std::vector<std::string>::const_iterator lEnd = aState->theErrors.end(); zorba::String lError = zorba::ZorbaException::getErrorCodeAsString(e.getErrorCode()); for(;lIter!=lEnd;++lIter) { zorba::String lSpecError = *lIter; if (lError.compare(lSpecError) == 0) { return true; } } } return false; } Zorba_CompilerHints getCompilerHints() { Zorba_CompilerHints lHints; // ZORBA_OPTLEVEL=O0 | O1 char* lOptLevel = getenv("ZORBA_OPTLEVEL"); if ( lOptLevel != NULL && strcmp(lOptLevel, "O0") == 0 ) { lHints.opt_level = ZORBA_OPT_LEVEL_O0; std::cout << "testdriver is using optimization level O0" << std::endl; } else { lHints.opt_level = ZORBA_OPT_LEVEL_O1; std::cout << "testdriver is using optimization level O1" << std::endl; } return lHints; } // set a variable in the dynamic context // inlineFile specifies whether the given parameter is a file and it's value should // be inlined or not void set_var (bool inlineFile, std::string name, std::string val, zorba::DynamicContext* dctx) { zorba::str_replace_all(val, "$UPDATE_SRC_DIR", zorba::UPDATE_SRC_DIR); zorba::ItemFactory* lFactory = zorba::Zorba::getInstance(NULL)->getItemFactory(); if (!inlineFile) { zorba::Item lItem = lFactory->createString(val); if(name != ".") dctx->setVariable (name, lItem); else dctx->setContextItem (lItem); } else { std::ifstream* is = new std::ifstream(val.c_str ()); assert (*is); if(name != ".") dctx->setVariableAsDocument (name, val.c_str(), std::auto_ptr<std::istream>(is)); else dctx->setContextItemAsDocument (val.c_str(), std::auto_ptr<std::istream>(is)); } } // return false if the files are not equal // aLine contains the line number in which the first difference occurs // aCol contains the column number in which the first difference occurs // aPos is the character number off the first difference in the file // -1 is returned for aLine, aCol, and aPos if the files are equal bool isEqual(zorba::file aRefFile, zorba::file aResFile, int& aLine, int& aCol, int& aPos) { std::ifstream li(aRefFile.get_path().c_str()); std::ifstream ri(aResFile.get_path().c_str()); std::string lLine, rLine; aLine = 1; aCol = 0; aPos = -1; while (! li.eof() ) { if ( ri.eof() ) { std::getline(li, lLine); if (li.peek() == -1) // ignore end-of-line in the ref result return true; else return false; } std::getline(li, lLine); std::getline(ri, rLine); ++aLine; if ( (aCol = lLine.compare(rLine)) != 0) { return false; } } return true; } int #ifdef _WIN32_WCE _tmain(int argc, _TCHAR* argv[]) #else main(int argc, char** argv) #endif { Specification lSpec; int flags = zorba::file::CONVERT_SLASHES | zorba::file::RESOLVE; if (argc != 2) { std::cout << "\nusage: testdriver [testfile]" << std::endl; return 1; } std::string lSpecFileString = zorba::UPDATE_SRC_DIR +"/Queries/" + argv[1]; zorba::file lSpecFile (lSpecFileString, flags); zorba::filesystem_path lSpecPath (lSpecFile.branch_path()); std::string lSpecWithoutSuffix = std::string(argv[1]).substr( 0, std::string(argv[1]).size()-5 ); std::cout << "test " << lSpecWithoutSuffix << std::endl; zorba::file lResultFile (zorba::UPDATE_BINARY_DIR +"/QueryResults/" + lSpecWithoutSuffix + ".res", flags); zorba::file lRefFile (zorba::UPDATE_SRC_DIR +"/ExpectedTestResults/" + lSpecWithoutSuffix +".xml.res", flags); zorba::filesystem_path lRefPath (lRefFile.branch_path()); if ( (! lSpecFile.exists ()) || lSpecFile.is_directory () ) { std::cout << "\n spec file " << lSpecFile.get_path() << " does not exist or is not a file" << std::endl; return 2; } if ( ! lResultFile.exists () ) lResultFile.deep_mkdir (); // read the xargs and errors if the spec file exists lSpec.parseFile(lSpecFile.get_path()); zorba::Zorba* engine = zorba::Zorba::getInstance(zorba::simplestore::SimpleStoreManager::getStore()); std::vector<zorba::XQuery_t> lQueries; Zorba_SerializerOptions lSerOptions; lSerOptions.omit_xml_declaration = ZORBA_OMIT_XML_DECLARATION_YES; // create and compile the query { std::vector<State*>::const_iterator lIter = lSpec.statesBegin(); std::vector<State*>::const_iterator lEnd = lSpec.statesEnd(); int lRun = 0; for(;lIter!=lEnd;++lIter) { State* lState = *lIter; zorba::filesystem_path lQueryFile (lSpecPath, zorba::filesystem_path ((*lIter)->theName + ".xq", zorba::file::CONVERT_SLASHES)); std::cout << std::endl << "Query (Run " << ++lRun << "):" << std::endl; printFile(std::cout, lQueryFile, "Query file"); std::cout << std::endl; std::ifstream lQueryStream(lQueryFile.c_str()); try { lQueries.push_back(engine->compileQuery(lQueryStream, getCompilerHints())); } catch (zorba::ZorbaException &e) { if (isErrorExpected(e, lState)) { std::cout << "Expected compiler error:\n" << e << std::endl; return 0; } else { std::cout << "Unexpected compiler error:\n" << e << std::endl; return 3; } } zorba::DynamicContext* lDynCtx = lQueries.back()->getDynamicContext(); if (lState->hasDate) { std::string lDateTime = lState->theDate; if (lDateTime.find("T") == std::string::npos) { lDateTime += "T00:00:00"; } lDynCtx->setCurrentDateTime(engine->getItemFactory()->createDateTime(lDateTime)); } std::vector<Variable*>::const_iterator lVarIter = (*lIter)->varsBegin(); std::vector<Variable*>::const_iterator lVarEnd = (*lIter)->varsEnd(); for(;lVarIter!=lVarEnd;++lVarIter) { Variable* lVar = *lVarIter; set_var(lVar->theInline, lVar->theName, lVar->theValue, lDynCtx); } try { if (lQueries.back()->isUpdateQuery()) { lQueries.back()->applyUpdates(); std::cout << "Updating Query -> no Result" << std::endl; } else { if ( lResultFile.exists ()) { lResultFile.remove (); } std::ofstream lResFileStream(lResultFile.get_path().c_str()); lQueries.back()->serialize(lResFileStream, lSerOptions); lResFileStream.flush(); printFile(std::cout, lResultFile.get_path(), "Result "); if (lState->hasCompare) { bool lRes = false; ulong numRefs = lState->theCompares.size(); for (ulong i = 0; i < numRefs && !lRes; i++) { zorba::filesystem_path lRefFile (lRefPath, zorba::filesystem_path (lState->theCompares[i], zorba::file::CONVERT_SLASHES)); int lLine, lCol, lPos; lRes = isEqual(lRefFile, lResultFile, lLine, lCol, lPos); if (!lRes) { printFile(std::cout, lRefFile.get_path(), "Result does not match expected result"); std::cout << std::endl; std::cout << "See line " << lLine << ", col " << lCol << " of expected result. " << std::endl; std::cout << "Got: " << std::endl; printPart(std::cout, lResultFile.get_path(), lPos, 15); std::cout << std::endl << "Expected "; printPart(std::cout, lRefFile.get_path(), lPos, 15); std::cout << std::endl; } } if (!lRes) { std::cout << std::endl << "Result does not match any of the expected results" << std::endl; return 4; } } else if (lState->hasErrors) { std::cout << "Query must throw an error!" << std::endl; return 5; } else { std::cout << "Query returns result but no expected result defined!" << std::endl; } } } catch (zorba::ZorbaException &e) { if (isErrorExpected(e, lState)) { std::cout << "Expected execution error:\n" << e std::endl; continue; } else { std::cout << "Unexpected execution error:\n" << e << std::endl; return 6; } } } } std::cout << "updtestdriver: success" << std::endl; return 0; } <commit_msg>Fixed syntax error<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <sstream> #include <fstream> #include <vector> #include <string> #include <cstring> #include <stdio.h> #include <stdlib.h> #include "testdriverconfig.h" // SRC and BIN dir definitions #include "specification.h" // parsing spec files #include "common/common.h" #include <zorba/zorba.h> #include <zorba/error_handler.h> #include <zorba/exception.h> #include <zorba/util/file.h> #include <zorbautils/strutil.h> #include <simplestore/simplestore.h> void printFile(std::ostream& os, std::string aInFile, std::string message) { std::cout << message << " " << aInFile << ":" << std::endl; std::ifstream lInFileStream(aInFile.c_str()); if (!lInFileStream) { std::cout << "Error: could not open " << aInFile << std::endl; assert(false); } os << lInFileStream.rdbuf() << std::endl; } // print parts of a file // starting at aStartPos with the length of aLen void printPart(std::ostream& os, std::string aInFile, int aStartPos, int aLen) { char* buffer = new char [aLen]; try { std::ifstream lIn(aInFile.c_str()); lIn.seekg(aStartPos); int lCharsRead = lIn.readsome (buffer, aLen); os.write (buffer, lCharsRead); os.flush(); delete[] buffer; } catch (...) { delete[] buffer; } return; } bool isErrorExpected(zorba::ZorbaException& e, State* aState) { if ( aState->hasErrors) { std::vector<std::string>::const_iterator lIter = aState->theErrors.begin(); std::vector<std::string>::const_iterator lEnd = aState->theErrors.end(); zorba::String lError = zorba::ZorbaException::getErrorCodeAsString(e.getErrorCode()); for(;lIter!=lEnd;++lIter) { zorba::String lSpecError = *lIter; if (lError.compare(lSpecError) == 0) { return true; } } } return false; } Zorba_CompilerHints getCompilerHints() { Zorba_CompilerHints lHints; // ZORBA_OPTLEVEL=O0 | O1 char* lOptLevel = getenv("ZORBA_OPTLEVEL"); if ( lOptLevel != NULL && strcmp(lOptLevel, "O0") == 0 ) { lHints.opt_level = ZORBA_OPT_LEVEL_O0; std::cout << "testdriver is using optimization level O0" << std::endl; } else { lHints.opt_level = ZORBA_OPT_LEVEL_O1; std::cout << "testdriver is using optimization level O1" << std::endl; } return lHints; } // set a variable in the dynamic context // inlineFile specifies whether the given parameter is a file and it's value should // be inlined or not void set_var (bool inlineFile, std::string name, std::string val, zorba::DynamicContext* dctx) { zorba::str_replace_all(val, "$UPDATE_SRC_DIR", zorba::UPDATE_SRC_DIR); zorba::ItemFactory* lFactory = zorba::Zorba::getInstance(NULL)->getItemFactory(); if (!inlineFile) { zorba::Item lItem = lFactory->createString(val); if(name != ".") dctx->setVariable (name, lItem); else dctx->setContextItem (lItem); } else { std::ifstream* is = new std::ifstream(val.c_str ()); assert (*is); if(name != ".") dctx->setVariableAsDocument (name, val.c_str(), std::auto_ptr<std::istream>(is)); else dctx->setContextItemAsDocument (val.c_str(), std::auto_ptr<std::istream>(is)); } } // return false if the files are not equal // aLine contains the line number in which the first difference occurs // aCol contains the column number in which the first difference occurs // aPos is the character number off the first difference in the file // -1 is returned for aLine, aCol, and aPos if the files are equal bool isEqual(zorba::file aRefFile, zorba::file aResFile, int& aLine, int& aCol, int& aPos) { std::ifstream li(aRefFile.get_path().c_str()); std::ifstream ri(aResFile.get_path().c_str()); std::string lLine, rLine; aLine = 1; aCol = 0; aPos = -1; while (! li.eof() ) { if ( ri.eof() ) { std::getline(li, lLine); if (li.peek() == -1) // ignore end-of-line in the ref result return true; else return false; } std::getline(li, lLine); std::getline(ri, rLine); ++aLine; if ( (aCol = lLine.compare(rLine)) != 0) { return false; } } return true; } int #ifdef _WIN32_WCE _tmain(int argc, _TCHAR* argv[]) #else main(int argc, char** argv) #endif { Specification lSpec; int flags = zorba::file::CONVERT_SLASHES | zorba::file::RESOLVE; if (argc != 2) { std::cout << "\nusage: testdriver [testfile]" << std::endl; return 1; } std::string lSpecFileString = zorba::UPDATE_SRC_DIR +"/Queries/" + argv[1]; zorba::file lSpecFile (lSpecFileString, flags); zorba::filesystem_path lSpecPath (lSpecFile.branch_path()); std::string lSpecWithoutSuffix = std::string(argv[1]).substr( 0, std::string(argv[1]).size()-5 ); std::cout << "test " << lSpecWithoutSuffix << std::endl; zorba::file lResultFile (zorba::UPDATE_BINARY_DIR +"/QueryResults/" + lSpecWithoutSuffix + ".res", flags); zorba::file lRefFile (zorba::UPDATE_SRC_DIR +"/ExpectedTestResults/" + lSpecWithoutSuffix +".xml.res", flags); zorba::filesystem_path lRefPath (lRefFile.branch_path()); if ( (! lSpecFile.exists ()) || lSpecFile.is_directory () ) { std::cout << "\n spec file " << lSpecFile.get_path() << " does not exist or is not a file" << std::endl; return 2; } if ( ! lResultFile.exists () ) lResultFile.deep_mkdir (); // read the xargs and errors if the spec file exists lSpec.parseFile(lSpecFile.get_path()); zorba::Zorba* engine = zorba::Zorba::getInstance(zorba::simplestore::SimpleStoreManager::getStore()); std::vector<zorba::XQuery_t> lQueries; Zorba_SerializerOptions lSerOptions; lSerOptions.omit_xml_declaration = ZORBA_OMIT_XML_DECLARATION_YES; // create and compile the query { std::vector<State*>::const_iterator lIter = lSpec.statesBegin(); std::vector<State*>::const_iterator lEnd = lSpec.statesEnd(); int lRun = 0; for(;lIter!=lEnd;++lIter) { State* lState = *lIter; zorba::filesystem_path lQueryFile (lSpecPath, zorba::filesystem_path ((*lIter)->theName + ".xq", zorba::file::CONVERT_SLASHES)); std::cout << std::endl << "Query (Run " << ++lRun << "):" << std::endl; printFile(std::cout, lQueryFile, "Query file"); std::cout << std::endl; std::ifstream lQueryStream(lQueryFile.c_str()); try { lQueries.push_back(engine->compileQuery(lQueryStream, getCompilerHints())); } catch (zorba::ZorbaException &e) { if (isErrorExpected(e, lState)) { std::cout << "Expected compiler error:\n" << e << std::endl; return 0; } else { std::cout << "Unexpected compiler error:\n" << e << std::endl; return 3; } } zorba::DynamicContext* lDynCtx = lQueries.back()->getDynamicContext(); if (lState->hasDate) { std::string lDateTime = lState->theDate; if (lDateTime.find("T") == std::string::npos) { lDateTime += "T00:00:00"; } lDynCtx->setCurrentDateTime(engine->getItemFactory()->createDateTime(lDateTime)); } std::vector<Variable*>::const_iterator lVarIter = (*lIter)->varsBegin(); std::vector<Variable*>::const_iterator lVarEnd = (*lIter)->varsEnd(); for(;lVarIter!=lVarEnd;++lVarIter) { Variable* lVar = *lVarIter; set_var(lVar->theInline, lVar->theName, lVar->theValue, lDynCtx); } try { if (lQueries.back()->isUpdateQuery()) { lQueries.back()->applyUpdates(); std::cout << "Updating Query -> no Result" << std::endl; } else { if ( lResultFile.exists ()) { lResultFile.remove (); } std::ofstream lResFileStream(lResultFile.get_path().c_str()); lQueries.back()->serialize(lResFileStream, lSerOptions); lResFileStream.flush(); printFile(std::cout, lResultFile.get_path(), "Result "); if (lState->hasCompare) { bool lRes = false; ulong numRefs = lState->theCompares.size(); for (ulong i = 0; i < numRefs && !lRes; i++) { zorba::filesystem_path lRefFile (lRefPath, zorba::filesystem_path (lState->theCompares[i], zorba::file::CONVERT_SLASHES)); int lLine, lCol, lPos; lRes = isEqual(lRefFile, lResultFile, lLine, lCol, lPos); if (!lRes) { printFile(std::cout, lRefFile.get_path(), "Result does not match expected result"); std::cout << std::endl; std::cout << "See line " << lLine << ", col " << lCol << " of expected result. " << std::endl; std::cout << "Got: " << std::endl; printPart(std::cout, lResultFile.get_path(), lPos, 15); std::cout << std::endl << "Expected "; printPart(std::cout, lRefFile.get_path(), lPos, 15); std::cout << std::endl; } } if (!lRes) { std::cout << std::endl << "Result does not match any of the expected results" << std::endl; return 4; } } else if (lState->hasErrors) { std::cout << "Query must throw an error!" << std::endl; return 5; } else { std::cout << "Query returns result but no expected result defined!" << std::endl; } } } catch (zorba::ZorbaException &e) { if (isErrorExpected(e, lState)) { std::cout << "Expected execution error:\n" << e << std::endl; continue; } else { std::cout << "Unexpected execution error:\n" << e << std::endl; return 6; } } } } std::cout << "updtestdriver: success" << std::endl; return 0; } <|endoftext|>
<commit_before>/* * opencog/atoms/reduct/ArithmeticLink.cc * * Copyright (C) 2015 Linas Vepstas * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <limits> #include <opencog/atoms/base/atom_types.h> #include <opencog/atoms/base/ClassServer.h> #include <opencog/atoms/NumberNode.h> #include "ArithmeticLink.h" using namespace opencog; ArithmeticLink::ArithmeticLink(const HandleSeq& oset, TruthValuePtr tv, AttentionValuePtr av) : FoldLink(ARITHMETIC_LINK, oset, tv, av) { init(); } ArithmeticLink::ArithmeticLink(Type t, const HandleSeq& oset, TruthValuePtr tv, AttentionValuePtr av) : FoldLink(t, oset, tv, av) { if (not classserver().isA(t, ARITHMETIC_LINK)) throw InvalidParamException(TRACE_INFO, "Expecting a ArithmeticLink"); init(); } ArithmeticLink::ArithmeticLink(Type t, const Handle& a, const Handle& b, TruthValuePtr tv, AttentionValuePtr av) : FoldLink(t, a, b, tv, av) { if (not classserver().isA(t, ARITHMETIC_LINK)) throw InvalidParamException(TRACE_INFO, "Expecting a ArithmeticLink"); init(); } ArithmeticLink::ArithmeticLink(Link& l) : FoldLink(l) { Type tscope = l.getType(); if (not classserver().isA(tscope, ARITHMETIC_LINK)) throw InvalidParamException(TRACE_INFO, "Expecting a ArithmeticLink"); init(); } void ArithmeticLink::init(void) { knild = std::numeric_limits<double>::quiet_NaN(); } // =========================================================== /// reduce() -- reduce the expression by summing constants, etc. /// /// No actual black-box evaluation or execution is performed. Only /// clearbox reductions are performed. /// /// Examples: the reduct of (PlusLink (NumberNode 2) (NumberNode 2)) /// is (NumberNode 4) -- its just a constant. /// /// The reduct of (PlusLink (VariableNode "$x") (NumberNode 0)) is /// (VariableNode "$x"), because adding zero to anything yeilds the /// thing itself. Handle ArithmeticLink::reduce(void) { Handle road(reorder()); ArithmeticLinkPtr alp(ArithmeticLinkCast(road)); Handle red(alp->FoldLink::reduce()); alp = ArithmeticLinkCast(red); if (NULL == alp) return red; return alp->reorder(); } // ============================================================ /// re-order the contents of an ArithmeticLink into "lexicographic" order. /// /// The goal of the re-ordering is to simplify the reduction code, /// by placing atoms where they are easily found. For now, this /// means: /// first, all of the variables, /// next, all compound expressions, /// last, all number nodes /// We do not currently sort the variables, but maybe we should...? /// Sorting by variable names would hold consilidate them... /// The FoldLink::reduce() method already returns expressions that are /// almost in the correct order. Handle ArithmeticLink::reorder(void) { HandleSeq vars; HandleSeq exprs; HandleSeq numbers; for (const Handle& h : _outgoing) { if (h->getType() == VARIABLE_NODE) vars.push_back(h); else if (h->getType() == NUMBER_NODE) numbers.push_back(h); else exprs.push_back(h); } HandleSeq result; for (const Handle& h : vars) result.push_back(h); for (const Handle& h : exprs) result.push_back(h); for (const Handle& h : numbers) result.push_back(h); Handle h(FoldLink::factory(getType(), result)); if (NULL == _atomTable) return h; return _atomTable->getAtomSpace()->add_atom(h); } // =========================================================== /// execute() -- Execute the expression, returning a number /// /// Similar to reduce(), above, except that this can only work /// on fully grounded (closed) sentences: after executation, /// everything must be a number, and there can be no variables /// in sight. static inline double get_double(AtomSpace *as, Handle h) { NumberNodePtr nnn(NumberNodeCast(h)); if (nnn == NULL) throw RuntimeException(TRACE_INFO, "Expecting a NumberNode, got %s", classserver().getTypeName(h->getType()).c_str()); return nnn->get_value(); } NumberNodePtr ArithmeticLink::unwrap_set(Handle h) const { FunctionLinkPtr flp(FunctionLinkCast(h)); if (flp) h = flp->execute(); // Pattern matching hack. The pattern matcher returns sets of atoms; // if that set contains numbers or something numeric, then unwrap it. if (SET_LINK == h->getType()) { LinkPtr lp(LinkCast(h)); if (1 != lp->getArity()) throw SyntaxException(TRACE_INFO, "Don't know how to do arithmetic with this: %s", h->toString().c_str()); h = lp->getOutgoingAtom(0); } NumberNodePtr na(NumberNodeCast(h)); if (nullptr == na) throw SyntaxException(TRACE_INFO, "Don't know how to do arithmetic with this: %s", h->toString().c_str()); return na; } Handle ArithmeticLink::execute(AtomSpace* as) const { // Pattern matching hack. The pattern matcher returns sets of atoms; // if that set contains numbers or something numeric, then unwrap it. if (1 == _outgoing.size()) { Handle arg = _outgoing[0]; FunctionLinkPtr flp(FunctionLinkCast(arg)); if (flp) arg = flp->execute(); if (SET_LINK == arg->getType()) { LinkPtr lp(LinkCast(arg)); return do_execute(as, lp->getOutgoingSet()); } HandleSeq o; o.emplace_back(arg); return do_execute(as, o); } return do_execute(as, _outgoing); } Handle ArithmeticLink::do_execute(AtomSpace* as, const HandleSeq& oset) const { double sum = knild; for (Handle h: oset) { h = unwrap_set(h); sum = konsd(sum, get_double(as, h)); } if (as) return as->add_atom(createNumberNode(sum)); return Handle(createNumberNode(sum)); } // =========================================================== <commit_msg>Ooops, missed an argument<commit_after>/* * opencog/atoms/reduct/ArithmeticLink.cc * * Copyright (C) 2015 Linas Vepstas * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <limits> #include <opencog/atoms/base/atom_types.h> #include <opencog/atoms/base/ClassServer.h> #include <opencog/atoms/NumberNode.h> #include "ArithmeticLink.h" using namespace opencog; ArithmeticLink::ArithmeticLink(const HandleSeq& oset, TruthValuePtr tv, AttentionValuePtr av) : FoldLink(ARITHMETIC_LINK, oset, tv, av) { init(); } ArithmeticLink::ArithmeticLink(Type t, const HandleSeq& oset, TruthValuePtr tv, AttentionValuePtr av) : FoldLink(t, oset, tv, av) { if (not classserver().isA(t, ARITHMETIC_LINK)) throw InvalidParamException(TRACE_INFO, "Expecting a ArithmeticLink"); init(); } ArithmeticLink::ArithmeticLink(Type t, const Handle& a, const Handle& b, TruthValuePtr tv, AttentionValuePtr av) : FoldLink(t, a, b, tv, av) { if (not classserver().isA(t, ARITHMETIC_LINK)) throw InvalidParamException(TRACE_INFO, "Expecting a ArithmeticLink"); init(); } ArithmeticLink::ArithmeticLink(Link& l) : FoldLink(l) { Type tscope = l.getType(); if (not classserver().isA(tscope, ARITHMETIC_LINK)) throw InvalidParamException(TRACE_INFO, "Expecting a ArithmeticLink"); init(); } void ArithmeticLink::init(void) { knild = std::numeric_limits<double>::quiet_NaN(); } // =========================================================== /// reduce() -- reduce the expression by summing constants, etc. /// /// No actual black-box evaluation or execution is performed. Only /// clearbox reductions are performed. /// /// Examples: the reduct of (PlusLink (NumberNode 2) (NumberNode 2)) /// is (NumberNode 4) -- its just a constant. /// /// The reduct of (PlusLink (VariableNode "$x") (NumberNode 0)) is /// (VariableNode "$x"), because adding zero to anything yeilds the /// thing itself. Handle ArithmeticLink::reduce(void) { Handle road(reorder()); ArithmeticLinkPtr alp(ArithmeticLinkCast(road)); Handle red(alp->FoldLink::reduce()); alp = ArithmeticLinkCast(red); if (NULL == alp) return red; return alp->reorder(); } // ============================================================ /// re-order the contents of an ArithmeticLink into "lexicographic" order. /// /// The goal of the re-ordering is to simplify the reduction code, /// by placing atoms where they are easily found. For now, this /// means: /// first, all of the variables, /// next, all compound expressions, /// last, all number nodes /// We do not currently sort the variables, but maybe we should...? /// Sorting by variable names would hold consilidate them... /// The FoldLink::reduce() method already returns expressions that are /// almost in the correct order. Handle ArithmeticLink::reorder(void) { HandleSeq vars; HandleSeq exprs; HandleSeq numbers; for (const Handle& h : _outgoing) { if (h->getType() == VARIABLE_NODE) vars.push_back(h); else if (h->getType() == NUMBER_NODE) numbers.push_back(h); else exprs.push_back(h); } HandleSeq result; for (const Handle& h : vars) result.push_back(h); for (const Handle& h : exprs) result.push_back(h); for (const Handle& h : numbers) result.push_back(h); Handle h(FoldLink::factory(getType(), result)); if (NULL == _atomTable) return h; return _atomTable->getAtomSpace()->add_atom(h); } // =========================================================== /// execute() -- Execute the expression, returning a number /// /// Similar to reduce(), above, except that this can only work /// on fully grounded (closed) sentences: after executation, /// everything must be a number, and there can be no variables /// in sight. static inline double get_double(AtomSpace *as, Handle h) { NumberNodePtr nnn(NumberNodeCast(h)); if (nnn == NULL) throw RuntimeException(TRACE_INFO, "Expecting a NumberNode, got %s", classserver().getTypeName(h->getType()).c_str()); return nnn->get_value(); } NumberNodePtr ArithmeticLink::unwrap_set(Handle h) const { FunctionLinkPtr flp(FunctionLinkCast(h)); if (flp) h = flp->execute(); // Pattern matching hack. The pattern matcher returns sets of atoms; // if that set contains numbers or something numeric, then unwrap it. if (SET_LINK == h->getType()) { LinkPtr lp(LinkCast(h)); if (1 != lp->getArity()) throw SyntaxException(TRACE_INFO, "Don't know how to do arithmetic with this: %s", h->toString().c_str()); h = lp->getOutgoingAtom(0); } NumberNodePtr na(NumberNodeCast(h)); if (nullptr == na) throw SyntaxException(TRACE_INFO, "Don't know how to do arithmetic with this: %s", h->toString().c_str()); return na; } Handle ArithmeticLink::execute(AtomSpace* as) const { // Pattern matching hack. The pattern matcher returns sets of atoms; // if that set contains numbers or something numeric, then unwrap it. if (1 == _outgoing.size()) { Handle arg = _outgoing[0]; FunctionLinkPtr flp(FunctionLinkCast(arg)); if (flp) arg = flp->execute(as); if (SET_LINK == arg->getType()) { LinkPtr lp(LinkCast(arg)); return do_execute(as, lp->getOutgoingSet()); } HandleSeq o; o.emplace_back(arg); return do_execute(as, o); } return do_execute(as, _outgoing); } Handle ArithmeticLink::do_execute(AtomSpace* as, const HandleSeq& oset) const { double sum = knild; for (Handle h: oset) { h = unwrap_set(h); sum = konsd(sum, get_double(as, h)); } if (as) return as->add_atom(createNumberNode(sum)); return Handle(createNumberNode(sum)); } // =========================================================== <|endoftext|>
<commit_before>/* * DefaultPatternMatchCB.cc * * Copyright (C) 2008,2009,2014 Linas Vepstas * * Author: Linas Vepstas <[email protected]> February 2008 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/atoms/execution/EvaluationLink.h> #include <opencog/atomutils/PatternUtils.h> #include "DefaultPatternMatchCB.h" #include "PatternMatchEngine.h" using namespace opencog; // Uncomment below to enable debug print #define DEBUG #ifdef DEBUG #define dbgprt(f, varargs...) printf(f, ##varargs) #else #define dbgprt(f, varargs...) #endif /* ======================================================== */ // Find a good place to start the search. // // The handle h points to a clause. In principle, it is enough to // simply find a constant in the clause, and just start there. In // practice, this can be an awful way to do things. So, for example, // most "typical" clauses will be of the form // // EvaluationLink // PredicateNode "blah" // ListLink // VariableNode $var // ConceptNode "item" // // Typically, the incoming set to "blah" will be huge, so starting the // search there would be a poor choice. Typically, the incoming set to // "item" will be much smaller, and so makes a better choice. The code // below tries to pass over "blah" and pick "item" instead. It does so // by comparing the size of the incoming sets of the two constants, and // picking the one with the smaller ("thinner") incoming set. Note that // this is a form of "greedy" search. // // Note that the algo performs a full-depth search to find this. That's // OK, because typeical clauses are never very deep. // // Note that the size of the incoming set really is a better measure, // and not the depth. So, for example, if "item" has a huge incoming // set, but "blah" does not, then "blah" is a much better place to // start. // // size_t& depth will be set to the depth of the thinnest constant found. // Handle& start will be set to the link containing that constant. // size_t& width will be set to the incoming-set size of the thinnest // constant found. // The returned value will be the constant at which to start the search. // If no constant is found, then the returned value is the undefnied // handle. // Handle DefaultPatternMatchCB::find_starter(Handle h, size_t& depth, Handle& start, size_t& width) { // If its a node, then we are done. Don't modify either depth or // start. Type t = h->getType(); if (classserver().isNode(t)) { if (t != VARIABLE_NODE) { width = h->getIncomingSetSize(); return h; } return Handle::UNDEFINED; } size_t deepest = depth; start = Handle::UNDEFINED; Handle hdeepest(Handle::UNDEFINED); size_t thinnest = SIZE_MAX; // Iterate over all the handles in the outgoing set. // Find the deepest one that contains a constant, and start // the search there. If there are two at the same depth, // then start with the skinnier one. LinkPtr ll(LinkCast(h)); const std::vector<Handle> &vh = ll->getOutgoingSet(); for (size_t i = 0; i < vh.size(); i++) { size_t brdepth = depth + 1; size_t brwid = SIZE_MAX; Handle sbr(h); // Blow past the QuoteLinks, since they just screw up the search start. Handle hunt(vh[i]); if (QUOTE_LINK == vh[i]->getType()) hunt = LinkCast(hunt)->getOutgoingAtom(0); Handle s(find_starter(hunt, brdepth, sbr, brwid)); if (s != Handle::UNDEFINED and (brwid < thinnest or (brwid == thinnest and deepest < brdepth))) { deepest = brdepth; hdeepest = s; start = sbr; thinnest = brwid; } } depth = deepest; width = thinnest; return hdeepest; } // Look at all the clauses, to find the "thinnest" one. Handle DefaultPatternMatchCB::find_thinnest(const std::vector<Handle>& clauses, Handle& starter_pred, size_t& bestclause) { size_t thinnest = SIZE_MAX; size_t deepest = 0; bestclause = 0; Handle best_start(Handle::UNDEFINED); starter_pred = Handle::UNDEFINED; size_t nc = clauses.size(); for (size_t i=0; i < nc; i++) { Handle h(clauses[i]); size_t depth = 0; size_t width = SIZE_MAX; Handle pred(Handle::UNDEFINED); Handle start(find_starter(h, depth, pred, width)); if (start != Handle::UNDEFINED and (width < thinnest or (width == thinnest and depth > deepest))) { thinnest = width; deepest = depth; bestclause = i; best_start = start; starter_pred = pred; } } return best_start; } /** * Search for solutions/groundings over all of the AtomSpace, using * some "reasonable" assumptions for what might be searched for. Or, * to put it bluntly, this search method *might* miss some possible * solutions, for certain "unusual" search types. The trade-off is * that this search algo should really be quite fast for "normal" * search types. * * This search algo makes the following (important) assumptions: * * 1) If none of the clauses have any variables in them, (that is, if * all of the clauses are "constant" clauses) then the search will * begin by looping over all links in the atomspace that have the * same link type as the first clause. This will fail to examine * all possible solutions if the link_match() callback is leniant, * and accepts a broader range of types than just this one. This * seems like a reasonable limitation: trying to search all-possible * link-types would be a huge performance impact, especially if the * link_match() callback was not interested in this broadened search. * * At any rate, this limitation doesn't even apply, because the * current PatternMatch::do_match() method completely removes * constant clauses anyway. (It needs to do this in order to * simplify handling of connected graphs, so that virtual atoms are * properly handled. This is based on the assumption that support * for virtual atoms is more important than support for unusual * link_match() callbacks. * * 2) Search will begin at the first non-variable node in the "thinnest" * clause. The thinnest clause is chosen, so as to improve performance; * but this has no effect on the thoroughness of the search. The search * will proceed by exploring the entire incoming-set for this node. * The search will NOT examine other non-variable node types. * If the node_match() callback is willing to accept a broader range * of node matches, esp. for this initial node, then many possible * solutions will be missed. This seems like a reasonable limitation: * if you really want a very lenient node_match(), then use variables. * Or you can implement your own perform_search() callback. * * 3) If the clauses consist entirely of variables, then the search * will start by looking for all links that are of the same type as * the type of the first clause. This can fail to find all possible * matches, if the link_match() callback is willing to accept a larger * set of types. This is a reasonable limitation: anything looser * would very seriously degrade performance; if you really need a * very lenient link_match(), then use variables. Or you can * implement your own perform_search() callback. * * The above describes the limits to the "typical" search that this * algo can do well. In particular, if the constraint of 2) can be met, * then the search can be quite rapid, since incoming sets are often * quite small; and assumption 2) limits the search to "nearby", * connected atoms. * * Note that the default implementation of node_match() and link_match() * in this class does satisfy both 2) and 3), so this algo will work * correctly if these two methods are not overloaded with more callbacks * that are lenient about matching types. * * If you overload node_match(), and do so in a way that breaks * assumption 2), then you will scratch your head, thinking * "why did my search fail to find this obvious solution?" The answer * will be for you to create a new search algo, in a new class, that * overloads this one, and does what you want it to. This class should * probably *not* be modified, since it is quite efficient for the * "normal" case. */ void DefaultPatternMatchCB::perform_search(PatternMatchEngine *pme, const std::set<Handle> &vars, const std::vector<Handle> &clauses, const std::vector<Handle> &negations) { // In principle, we could start our search at some node, any node, // that is not a variable. In practice, the search begins by // iterating over the incoming set of the node, and so, if it is // large, a huge amount of effort might be wasted exploring // dead-ends. Thus, it pays off to start the search on the // node with the smallest ("narrowest" or "thinnest") incoming set // possible. Thus, we look at all the clauses, to find the // "thinnest" one. // // Note also: the user is allowed to specify patterns that have // no constants in them at all. In this case, the search is // performed by looping over all links of the given types. size_t bestclause; Handle best_start = find_thinnest(clauses, _starter_pred, bestclause); if ((Handle::UNDEFINED != best_start) // and (Handle::UNDEFINED != _starter_pred) // and (not vars.empty())) ) { _root = clauses[bestclause]; dbgprt("Search start node: %s\n", best_start->toShortString().c_str()); dbgprt("Start pred is: %s\n", _starter_pred->toShortString().c_str()); // This should be calling the over-loaded virtual method // get_incoming_set(), so that, e.g. it gets sorted by attentional // focus in the AttentionalFocusCB class... IncomingSet iset = get_incoming_set(best_start); size_t sz = iset.size(); for (size_t i = 0; i < sz; i++) { Handle h(iset[i]); dbgprt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n"); dbgprt("Loop candidate (%lu/%lu): %s\n", i, sz, h->toShortString().c_str()); bool rc = pme->do_candidate(_root, _starter_pred, h); if (rc) break; } // If we are here, we are done. return; } // If we are here, then we could not find a clause at which to start, // as, apparently, the clauses consist entirely of variables!! So, // basically, we must search the entire!! atomspace, in this case. // Yes, this hurts. full_search(pme, clauses); } /// The defualt search tries to optimize by making some reasonable /// assumptions about what is being looked for. But not every problem /// fits those assumptions, so this method provides an exhaustive /// search. Note that exhaustive searches can be exhaustingly long, /// so watch out! void DefaultPatternMatchCB::full_search(PatternMatchEngine *pme, const std::vector<Handle> &clauses) { _root = clauses[0]; _starter_pred = _root; dbgprt("Start pred is: %s\n", _starter_pred->toShortString().c_str()); // Get type of the first item in the predicate list. Type ptype = _root->getType(); // Plunge into the deep end - start looking at all viable // candidates in the AtomSpace. // XXX TODO -- as a performance optimization, we should try all // the different clauses, and find the one with the smallest number // of atoms of that type, or otherwise try to find a small ("thin") // incoming set to search over. // // If ptype is a VariableNode, then basically, the pattern says // "Search all of the atomspace." Literally. So this will blow up // if the atomspace is large. std::list<Handle> handle_set; if (VARIABLE_NODE != ptype) _as->getHandlesByType(back_inserter(handle_set), ptype); else _as->getHandlesByType(back_inserter(handle_set), ATOM, true); size_t handle_set_size = handle_set.size(), i = 0; for (const Handle& h : handle_set) { dbgprt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n"); dbgprt("Loop candidate (%lu/%lu): %s\n", i++, handle_set_size, h->toShortString().c_str()); bool rc = pme->do_candidate(_root, _starter_pred, h); if (rc) break; } } /* ======================================================== */ bool DefaultPatternMatchCB::virtual_link_match(const Handle& virt, const Handle& gargs) { // At this time, we expect all virutal links to be in one of two // forms: either EvaluationLink's or GreaterThanLink's. The // EvaluationLinks should have the structure // // EvaluationLink // GroundedPredicateNode "scm:blah" // ListLink // Arg1Atom // Arg2Atom // // The GreaterThanLink's should have the "obvious" structure // // GreaterThanLink // Arg1Atom // Arg2Atom // // XXX TODO as discussed on the mailing list, we should perhaps first // see if the following can be found in the atomspace: // // EvaluationLink // PredicateNode "blah" ; not Grounded any more, and scm: stripped // ListLink // Arg1Atom // Arg2Atom // // If it does, we should declare a match. If not, only then run the // do_evaluate callback. Alternately, perhaps the // EvaluationLink::do_evaluate() method should do this ??? Its a toss-up. TruthValuePtr tvp(EvaluationLink::do_evaluate(_as, gargs)); // XXX FIXME: we are making a crsip-logic go/no-go decision // based on the TV strength. Perhaps something more subtle might be // wanted, here. bool relation_holds = tvp->getMean() > 0.5; return relation_holds; } /* ===================== END OF FILE ===================== */ <commit_msg>Disable DEBUG print in DefaultPatternMatchCB<commit_after>/* * DefaultPatternMatchCB.cc * * Copyright (C) 2008,2009,2014 Linas Vepstas * * Author: Linas Vepstas <[email protected]> February 2008 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/atoms/execution/EvaluationLink.h> #include <opencog/atomutils/PatternUtils.h> #include "DefaultPatternMatchCB.h" #include "PatternMatchEngine.h" using namespace opencog; // Uncomment below to enable debug print // #define DEBUG #ifdef DEBUG #define dbgprt(f, varargs...) printf(f, ##varargs) #else #define dbgprt(f, varargs...) #endif /* ======================================================== */ // Find a good place to start the search. // // The handle h points to a clause. In principle, it is enough to // simply find a constant in the clause, and just start there. In // practice, this can be an awful way to do things. So, for example, // most "typical" clauses will be of the form // // EvaluationLink // PredicateNode "blah" // ListLink // VariableNode $var // ConceptNode "item" // // Typically, the incoming set to "blah" will be huge, so starting the // search there would be a poor choice. Typically, the incoming set to // "item" will be much smaller, and so makes a better choice. The code // below tries to pass over "blah" and pick "item" instead. It does so // by comparing the size of the incoming sets of the two constants, and // picking the one with the smaller ("thinner") incoming set. Note that // this is a form of "greedy" search. // // Note that the algo performs a full-depth search to find this. That's // OK, because typeical clauses are never very deep. // // Note that the size of the incoming set really is a better measure, // and not the depth. So, for example, if "item" has a huge incoming // set, but "blah" does not, then "blah" is a much better place to // start. // // size_t& depth will be set to the depth of the thinnest constant found. // Handle& start will be set to the link containing that constant. // size_t& width will be set to the incoming-set size of the thinnest // constant found. // The returned value will be the constant at which to start the search. // If no constant is found, then the returned value is the undefnied // handle. // Handle DefaultPatternMatchCB::find_starter(Handle h, size_t& depth, Handle& start, size_t& width) { // If its a node, then we are done. Don't modify either depth or // start. Type t = h->getType(); if (classserver().isNode(t)) { if (t != VARIABLE_NODE) { width = h->getIncomingSetSize(); return h; } return Handle::UNDEFINED; } size_t deepest = depth; start = Handle::UNDEFINED; Handle hdeepest(Handle::UNDEFINED); size_t thinnest = SIZE_MAX; // Iterate over all the handles in the outgoing set. // Find the deepest one that contains a constant, and start // the search there. If there are two at the same depth, // then start with the skinnier one. LinkPtr ll(LinkCast(h)); const std::vector<Handle> &vh = ll->getOutgoingSet(); for (size_t i = 0; i < vh.size(); i++) { size_t brdepth = depth + 1; size_t brwid = SIZE_MAX; Handle sbr(h); // Blow past the QuoteLinks, since they just screw up the search start. Handle hunt(vh[i]); if (QUOTE_LINK == vh[i]->getType()) hunt = LinkCast(hunt)->getOutgoingAtom(0); Handle s(find_starter(hunt, brdepth, sbr, brwid)); if (s != Handle::UNDEFINED and (brwid < thinnest or (brwid == thinnest and deepest < brdepth))) { deepest = brdepth; hdeepest = s; start = sbr; thinnest = brwid; } } depth = deepest; width = thinnest; return hdeepest; } // Look at all the clauses, to find the "thinnest" one. Handle DefaultPatternMatchCB::find_thinnest(const std::vector<Handle>& clauses, Handle& starter_pred, size_t& bestclause) { size_t thinnest = SIZE_MAX; size_t deepest = 0; bestclause = 0; Handle best_start(Handle::UNDEFINED); starter_pred = Handle::UNDEFINED; size_t nc = clauses.size(); for (size_t i=0; i < nc; i++) { Handle h(clauses[i]); size_t depth = 0; size_t width = SIZE_MAX; Handle pred(Handle::UNDEFINED); Handle start(find_starter(h, depth, pred, width)); if (start != Handle::UNDEFINED and (width < thinnest or (width == thinnest and depth > deepest))) { thinnest = width; deepest = depth; bestclause = i; best_start = start; starter_pred = pred; } } return best_start; } /** * Search for solutions/groundings over all of the AtomSpace, using * some "reasonable" assumptions for what might be searched for. Or, * to put it bluntly, this search method *might* miss some possible * solutions, for certain "unusual" search types. The trade-off is * that this search algo should really be quite fast for "normal" * search types. * * This search algo makes the following (important) assumptions: * * 1) If none of the clauses have any variables in them, (that is, if * all of the clauses are "constant" clauses) then the search will * begin by looping over all links in the atomspace that have the * same link type as the first clause. This will fail to examine * all possible solutions if the link_match() callback is leniant, * and accepts a broader range of types than just this one. This * seems like a reasonable limitation: trying to search all-possible * link-types would be a huge performance impact, especially if the * link_match() callback was not interested in this broadened search. * * At any rate, this limitation doesn't even apply, because the * current PatternMatch::do_match() method completely removes * constant clauses anyway. (It needs to do this in order to * simplify handling of connected graphs, so that virtual atoms are * properly handled. This is based on the assumption that support * for virtual atoms is more important than support for unusual * link_match() callbacks. * * 2) Search will begin at the first non-variable node in the "thinnest" * clause. The thinnest clause is chosen, so as to improve performance; * but this has no effect on the thoroughness of the search. The search * will proceed by exploring the entire incoming-set for this node. * The search will NOT examine other non-variable node types. * If the node_match() callback is willing to accept a broader range * of node matches, esp. for this initial node, then many possible * solutions will be missed. This seems like a reasonable limitation: * if you really want a very lenient node_match(), then use variables. * Or you can implement your own perform_search() callback. * * 3) If the clauses consist entirely of variables, then the search * will start by looking for all links that are of the same type as * the type of the first clause. This can fail to find all possible * matches, if the link_match() callback is willing to accept a larger * set of types. This is a reasonable limitation: anything looser * would very seriously degrade performance; if you really need a * very lenient link_match(), then use variables. Or you can * implement your own perform_search() callback. * * The above describes the limits to the "typical" search that this * algo can do well. In particular, if the constraint of 2) can be met, * then the search can be quite rapid, since incoming sets are often * quite small; and assumption 2) limits the search to "nearby", * connected atoms. * * Note that the default implementation of node_match() and link_match() * in this class does satisfy both 2) and 3), so this algo will work * correctly if these two methods are not overloaded with more callbacks * that are lenient about matching types. * * If you overload node_match(), and do so in a way that breaks * assumption 2), then you will scratch your head, thinking * "why did my search fail to find this obvious solution?" The answer * will be for you to create a new search algo, in a new class, that * overloads this one, and does what you want it to. This class should * probably *not* be modified, since it is quite efficient for the * "normal" case. */ void DefaultPatternMatchCB::perform_search(PatternMatchEngine *pme, const std::set<Handle> &vars, const std::vector<Handle> &clauses, const std::vector<Handle> &negations) { // In principle, we could start our search at some node, any node, // that is not a variable. In practice, the search begins by // iterating over the incoming set of the node, and so, if it is // large, a huge amount of effort might be wasted exploring // dead-ends. Thus, it pays off to start the search on the // node with the smallest ("narrowest" or "thinnest") incoming set // possible. Thus, we look at all the clauses, to find the // "thinnest" one. // // Note also: the user is allowed to specify patterns that have // no constants in them at all. In this case, the search is // performed by looping over all links of the given types. size_t bestclause; Handle best_start = find_thinnest(clauses, _starter_pred, bestclause); if ((Handle::UNDEFINED != best_start) // and (Handle::UNDEFINED != _starter_pred) // and (not vars.empty())) ) { _root = clauses[bestclause]; dbgprt("Search start node: %s\n", best_start->toShortString().c_str()); dbgprt("Start pred is: %s\n", _starter_pred->toShortString().c_str()); // This should be calling the over-loaded virtual method // get_incoming_set(), so that, e.g. it gets sorted by attentional // focus in the AttentionalFocusCB class... IncomingSet iset = get_incoming_set(best_start); size_t sz = iset.size(); for (size_t i = 0; i < sz; i++) { Handle h(iset[i]); dbgprt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n"); dbgprt("Loop candidate (%lu/%lu): %s\n", i, sz, h->toShortString().c_str()); bool rc = pme->do_candidate(_root, _starter_pred, h); if (rc) break; } // If we are here, we are done. return; } // If we are here, then we could not find a clause at which to start, // as, apparently, the clauses consist entirely of variables!! So, // basically, we must search the entire!! atomspace, in this case. // Yes, this hurts. full_search(pme, clauses); } /// The defualt search tries to optimize by making some reasonable /// assumptions about what is being looked for. But not every problem /// fits those assumptions, so this method provides an exhaustive /// search. Note that exhaustive searches can be exhaustingly long, /// so watch out! void DefaultPatternMatchCB::full_search(PatternMatchEngine *pme, const std::vector<Handle> &clauses) { _root = clauses[0]; _starter_pred = _root; dbgprt("Start pred is: %s\n", _starter_pred->toShortString().c_str()); // Get type of the first item in the predicate list. Type ptype = _root->getType(); // Plunge into the deep end - start looking at all viable // candidates in the AtomSpace. // XXX TODO -- as a performance optimization, we should try all // the different clauses, and find the one with the smallest number // of atoms of that type, or otherwise try to find a small ("thin") // incoming set to search over. // // If ptype is a VariableNode, then basically, the pattern says // "Search all of the atomspace." Literally. So this will blow up // if the atomspace is large. std::list<Handle> handle_set; if (VARIABLE_NODE != ptype) _as->getHandlesByType(back_inserter(handle_set), ptype); else _as->getHandlesByType(back_inserter(handle_set), ATOM, true); size_t handle_set_size = handle_set.size(), i = 0; for (const Handle& h : handle_set) { dbgprt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n"); dbgprt("Loop candidate (%lu/%lu): %s\n", i++, handle_set_size, h->toShortString().c_str()); bool rc = pme->do_candidate(_root, _starter_pred, h); if (rc) break; } } /* ======================================================== */ bool DefaultPatternMatchCB::virtual_link_match(const Handle& virt, const Handle& gargs) { // At this time, we expect all virutal links to be in one of two // forms: either EvaluationLink's or GreaterThanLink's. The // EvaluationLinks should have the structure // // EvaluationLink // GroundedPredicateNode "scm:blah" // ListLink // Arg1Atom // Arg2Atom // // The GreaterThanLink's should have the "obvious" structure // // GreaterThanLink // Arg1Atom // Arg2Atom // // XXX TODO as discussed on the mailing list, we should perhaps first // see if the following can be found in the atomspace: // // EvaluationLink // PredicateNode "blah" ; not Grounded any more, and scm: stripped // ListLink // Arg1Atom // Arg2Atom // // If it does, we should declare a match. If not, only then run the // do_evaluate callback. Alternately, perhaps the // EvaluationLink::do_evaluate() method should do this ??? Its a toss-up. TruthValuePtr tvp(EvaluationLink::do_evaluate(_as, gargs)); // XXX FIXME: we are making a crsip-logic go/no-go decision // based on the TV strength. Perhaps something more subtle might be // wanted, here. bool relation_holds = tvp->getMean() > 0.5; return relation_holds; } /* ===================== END OF FILE ===================== */ <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010 Couchbase, 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 "config.h" #include "priority.h" // Priorities for Read-only IO tasks const Priority Priority::BgFetcherPriority(BGFETCHER_ID, 0); const Priority Priority::BgFetcherGetMetaPriority(BGFETCHER_GET_META_ID, 1); const Priority Priority::WarmupPriority(WARMUP_ID, 0); const Priority Priority::VKeyStatBgFetcherPriority(VKEY_STAT_BGFETCHER_ID, 3); // Priorities for Auxiliary IO tasks const Priority Priority::TapBgFetcherPriority(TAP_BGFETCHER_ID, 1); const Priority Priority::AccessScannerPriority(ACCESS_SCANNER_ID, 3); const Priority Priority::BackfillTaskPriority(BACKFILL_TASK_ID, 8); // Priorities for Read-Write IO tasks const Priority Priority::VBucketDeletionPriority(VBUCKET_DELETION_ID, 1); const Priority Priority::CompactorPriority(COMPACTOR_ID, 2); const Priority Priority::VBucketPersistHighPriority(VBUCKET_PERSIST_HIGH_ID, 2); const Priority Priority::FlushAllPriority(FLUSHALL_ID, 3); const Priority Priority::FlusherPriority(FLUSHER_ID, 5); const Priority Priority::VBucketPersistLowPriority(VBUCKET_PERSIST_LOW_ID, 9); const Priority Priority::StatSnapPriority(STAT_SNAP_ID, 9); const Priority Priority::MutationLogCompactorPriority(MUTATION_LOG_COMPACTOR_ID, 9); // Priorities for NON-IO tasks const Priority Priority::PendingOpsPriority(PENDING_OPS_ID, 0); const Priority Priority::TapConnNotificationPriority(TAP_CONN_NOTIFICATION_ID, 5); const Priority Priority::CheckpointRemoverPriority(CHECKPOINT_REMOVER_ID, 6); const Priority Priority::TapConnectionReaperPriority(TAP_CONNECTION_REAPER_ID, 6); const Priority Priority::VBMemoryDeletionPriority(VB_MEMORY_DELETION_ID, 6); const Priority Priority::CheckpointStatsPriority(CHECKPOINT_STATS_ID, 7); const Priority Priority::ItemPagerPriority(ITEM_PAGER_ID, 7); const Priority Priority::DefragmenterTaskPriority(DEFRAGMENTER_ID, 7); const Priority Priority::TapConnMgrPriority(TAP_CONN_MGR_ID, 8); const Priority Priority::WorkLoadMonitorPriority(WORKLOAD_MONITOR_TASK_ID, 10); const Priority Priority::HTResizePriority(HT_RESIZER_ID, 211); const Priority Priority::TapResumePriority(TAP_RESUME_ID, 316); const Priority Priority::ActiveStreamCheckpointProcessor(ACTIVE_STREAM_CHKPT_PROCESSOR_ID, 5); const char *Priority::getTypeName(const type_id_t i) { switch (i) { case BGFETCHER_ID: return "bg_fetcher_tasks"; case BGFETCHER_GET_META_ID: return "bg_fetcher_meta_tasks"; case TAP_BGFETCHER_ID: return "tap_bg_fetcher_tasks"; case VKEY_STAT_BGFETCHER_ID: return "vkey_stat_bg_fetcher_tasks"; case WARMUP_ID: return "warmup_tasks"; case VBUCKET_PERSIST_HIGH_ID: return "vbucket_persist_high_tasks"; case VBUCKET_DELETION_ID: return "vbucket_deletion_tasks"; case FLUSHER_ID: return "flusher_tasks"; case FLUSHALL_ID: return "flush_all_tasks"; case COMPACTOR_ID: return "compactor_tasks"; case VBUCKET_PERSIST_LOW_ID: return "vbucket_persist_low_tasks"; case STAT_SNAP_ID: return "statsnap_tasks"; case MUTATION_LOG_COMPACTOR_ID: return "mutation_log_compactor_tasks"; case ACCESS_SCANNER_ID: return "access_scanner_tasks"; case TAP_CONN_NOTIFICATION_ID: return "conn_notification_tasks"; case CHECKPOINT_REMOVER_ID: return "checkpoint_remover_tasks"; case VB_MEMORY_DELETION_ID: return "vb_memory_deletion_tasks"; case CHECKPOINT_STATS_ID: return "checkpoint_stats_tasks"; case ITEM_PAGER_ID: return "item_pager_tasks"; case BACKFILL_TASK_ID: return "backfill_tasks"; case WORKLOAD_MONITOR_TASK_ID: return "workload_monitor_tasks"; case TAP_RESUME_ID: return "tap_resume_tasks"; case TAP_CONNECTION_REAPER_ID: return "tapconnection_reaper_tasks"; case HT_RESIZER_ID: return "hashtable_resize_tasks"; case PENDING_OPS_ID: return "pending_ops_tasks"; case TAP_CONN_MGR_ID: return "conn_manager_tasks"; case DEFRAGMENTER_ID: return "defragmenter_tasks"; case ACTIVE_STREAM_CHKPT_PROCESSOR_ID: return "activestream_chkpt_processor_tasks"; default: break; } return "error"; } <commit_msg>Group AUXIO tasks while listing their priorities<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010 Couchbase, 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 "config.h" #include "priority.h" // Priorities for Read-only IO tasks const Priority Priority::BgFetcherPriority(BGFETCHER_ID, 0); const Priority Priority::BgFetcherGetMetaPriority(BGFETCHER_GET_META_ID, 1); const Priority Priority::WarmupPriority(WARMUP_ID, 0); const Priority Priority::VKeyStatBgFetcherPriority(VKEY_STAT_BGFETCHER_ID, 3); // Priorities for Auxiliary IO tasks const Priority Priority::TapBgFetcherPriority(TAP_BGFETCHER_ID, 1); const Priority Priority::AccessScannerPriority(ACCESS_SCANNER_ID, 3); const Priority Priority::ActiveStreamCheckpointProcessor(ACTIVE_STREAM_CHKPT_PROCESSOR_ID, 5); const Priority Priority::BackfillTaskPriority(BACKFILL_TASK_ID, 8); // Priorities for Read-Write IO tasks const Priority Priority::VBucketDeletionPriority(VBUCKET_DELETION_ID, 1); const Priority Priority::CompactorPriority(COMPACTOR_ID, 2); const Priority Priority::VBucketPersistHighPriority(VBUCKET_PERSIST_HIGH_ID, 2); const Priority Priority::FlushAllPriority(FLUSHALL_ID, 3); const Priority Priority::FlusherPriority(FLUSHER_ID, 5); const Priority Priority::VBucketPersistLowPriority(VBUCKET_PERSIST_LOW_ID, 9); const Priority Priority::StatSnapPriority(STAT_SNAP_ID, 9); const Priority Priority::MutationLogCompactorPriority(MUTATION_LOG_COMPACTOR_ID, 9); // Priorities for NON-IO tasks const Priority Priority::PendingOpsPriority(PENDING_OPS_ID, 0); const Priority Priority::TapConnNotificationPriority(TAP_CONN_NOTIFICATION_ID, 5); const Priority Priority::CheckpointRemoverPriority(CHECKPOINT_REMOVER_ID, 6); const Priority Priority::TapConnectionReaperPriority(TAP_CONNECTION_REAPER_ID, 6); const Priority Priority::VBMemoryDeletionPriority(VB_MEMORY_DELETION_ID, 6); const Priority Priority::CheckpointStatsPriority(CHECKPOINT_STATS_ID, 7); const Priority Priority::ItemPagerPriority(ITEM_PAGER_ID, 7); const Priority Priority::DefragmenterTaskPriority(DEFRAGMENTER_ID, 7); const Priority Priority::TapConnMgrPriority(TAP_CONN_MGR_ID, 8); const Priority Priority::WorkLoadMonitorPriority(WORKLOAD_MONITOR_TASK_ID, 10); const Priority Priority::HTResizePriority(HT_RESIZER_ID, 211); const Priority Priority::TapResumePriority(TAP_RESUME_ID, 316); const char *Priority::getTypeName(const type_id_t i) { switch (i) { case BGFETCHER_ID: return "bg_fetcher_tasks"; case BGFETCHER_GET_META_ID: return "bg_fetcher_meta_tasks"; case TAP_BGFETCHER_ID: return "tap_bg_fetcher_tasks"; case VKEY_STAT_BGFETCHER_ID: return "vkey_stat_bg_fetcher_tasks"; case WARMUP_ID: return "warmup_tasks"; case VBUCKET_PERSIST_HIGH_ID: return "vbucket_persist_high_tasks"; case VBUCKET_DELETION_ID: return "vbucket_deletion_tasks"; case FLUSHER_ID: return "flusher_tasks"; case FLUSHALL_ID: return "flush_all_tasks"; case COMPACTOR_ID: return "compactor_tasks"; case VBUCKET_PERSIST_LOW_ID: return "vbucket_persist_low_tasks"; case STAT_SNAP_ID: return "statsnap_tasks"; case MUTATION_LOG_COMPACTOR_ID: return "mutation_log_compactor_tasks"; case ACCESS_SCANNER_ID: return "access_scanner_tasks"; case TAP_CONN_NOTIFICATION_ID: return "conn_notification_tasks"; case CHECKPOINT_REMOVER_ID: return "checkpoint_remover_tasks"; case VB_MEMORY_DELETION_ID: return "vb_memory_deletion_tasks"; case CHECKPOINT_STATS_ID: return "checkpoint_stats_tasks"; case ITEM_PAGER_ID: return "item_pager_tasks"; case BACKFILL_TASK_ID: return "backfill_tasks"; case WORKLOAD_MONITOR_TASK_ID: return "workload_monitor_tasks"; case TAP_RESUME_ID: return "tap_resume_tasks"; case TAP_CONNECTION_REAPER_ID: return "tapconnection_reaper_tasks"; case HT_RESIZER_ID: return "hashtable_resize_tasks"; case PENDING_OPS_ID: return "pending_ops_tasks"; case TAP_CONN_MGR_ID: return "conn_manager_tasks"; case DEFRAGMENTER_ID: return "defragmenter_tasks"; case ACTIVE_STREAM_CHKPT_PROCESSOR_ID: return "activestream_chkpt_processor_tasks"; default: break; } return "error"; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012, Dennis Hedback * 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 <iostream> #include <iterator> #include <set> #include <string> #include <vector> typedef std::set<std::string> Set; typedef std::vector<std::string> Tuple; typedef std::set<Tuple> Product; typedef std::vector<Set> Generator; Generator read_sets(void) { Generator gen; Set current_set; std::string current_elem; for (std::istreambuf_iterator<char> it(std::cin), end; it != end; it++) { char c = *it; if (c == ',' || c == '\n') { current_set.insert(current_elem); current_elem.clear(); if (c == '\n') { gen.push_back(current_set); current_set.clear(); } } else { current_elem += c; } } return gen; } unsigned int product_cardinality(Generator gen) { unsigned int cardinality = 1; for (Generator::iterator it = gen.begin(); it != gen.end(); it++) cardinality *= (*it).size(); return cardinality; } Product cartesian_product(Generator gen) { Product prod; unsigned int counters[gen.size()]; for (unsigned int i = 0; i < gen.size(); i++) counters[i] = 0; for (unsigned int i = 0; i < product_cardinality(gen); i++) { Tuple current_tuple; for (unsigned int j = 0; j < gen.size(); j++) { Set current_set = gen[j]; unsigned int k = 0; for (Set::iterator it = current_set.begin(); it != current_set.end(); k++, it++) if (k == counters[j]) current_tuple.push_back(*it); } prod.insert(current_tuple); for (unsigned int j = 0; j < gen.size(); j++) { counters[j]++; if (counters[j] > gen[j].size() - 1) counters[j] = 0; else break; } } return prod; } void print_product(Product prod) { for (Product::iterator pi = prod.begin(); pi != prod.end(); pi++) { for (Tuple::const_iterator ti = (*pi).begin(); ti != (*pi).end(); ti++) { std::cout << *ti; if (++ti != (*pi).end()) std::cout << ','; ti--; } std::cout << std::endl; } } int main(int argc, char *argv[]) { Generator gen = read_sets(); Product prod = cartesian_product(gen); print_product(prod); return 0; } <commit_msg>Ditched int counters in favor of iterators. Benchmark went from ~1m15s to ~8.5s<commit_after>/* * Copyright (c) 2012, Dennis Hedback * 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 <iostream> #include <iterator> #include <set> #include <string> #include <vector> typedef std::set<std::string> Set; typedef std::vector<std::string> Tuple; typedef std::set<Tuple> Product; typedef std::vector<Set> Generator; Generator read_sets(void) { Generator gen; Set current_set; std::string current_elem; for (std::istreambuf_iterator<char> it(std::cin), end; it != end; it++) { char c = *it; if (c == ',' || c == '\n') { current_set.insert(current_elem); current_elem.clear(); if (c == '\n') { gen.push_back(current_set); current_set.clear(); } } else { current_elem += c; } } return gen; } void print_tuple(Tuple &tup) { for (Tuple::const_iterator ti = tup.begin(); ti != tup.end(); ti++) { std::cout << *ti; if (++ti != tup.end()) std::cout << ','; ti--; } std::cout << '\n'; } struct Counter { Set::const_iterator begin; Set::const_iterator end; Set::const_iterator current; }; typedef std::vector<Counter> Counters; void init_counters(Counters &ctrs, Generator &gen) { for (Generator::const_iterator set = gen.begin(); set != gen.end(); set++) { Counter ctr = { set->begin(), set->end(), set->begin() }; ctrs.push_back(ctr); } } void populate_tuple(Tuple &tup, Counters &ctrs) { for(Counters::const_iterator ctr = ctrs.begin(); ctr != ctrs.end(); ctr++) { tup.push_back(*(ctr->current)); } } int increment_counters(Counters &ctrs) { for (Counters::iterator ctr = ctrs.begin(); ; ) { (ctr->current)++; if (ctr->current == ctr->end) { if (ctr+1 == ctrs.end()) { return 1; } else { ctr->current = ctr->begin; ctr++; } } else { break; } } return 0; } void cartesian_product(Generator &gen) { Counters ctrs; init_counters(ctrs, gen); while (true) { Tuple tup; populate_tuple(tup, ctrs); print_tuple(tup); if (increment_counters(ctrs) != 0) return; } } int main(int argc, char *argv[]) { Generator gen = read_sets(); cartesian_product(gen); return 0; } <|endoftext|>
<commit_before>//wglGetCurrentContext, wglGetCurrentDC #include <GL/glut.h> #include "OpenCLManager.h" #include <boost/scoped_ptr.hpp> #include <boost/thread/condition.hpp> //OCL #include <opencv2/core/ocl.hpp> #include <CL/cl_gl.h> #include <CL/cl_d3d11_ext.h> #include <log4cpp/Category.hh> // get loggers static log4cpp::Category& logger( log4cpp::Category::getInstance( "Ubitrack.Vision.OpenCLManager" ) ); namespace Ubitrack { namespace Vision { static boost::scoped_ptr< OpenCLManager > g_pOpenCLManager; OpenCLManager& OpenCLManager::singleton() { static boost::mutex singletonMutex; LOG4CPP_INFO( logger, "singleton()"); boost::mutex::scoped_lock l( singletonMutex ); //create a new singleton if necessary if( !g_pOpenCLManager ){ LOG4CPP_INFO( logger, "singleton(): allocating a new"); g_pOpenCLManager.reset( new OpenCLManager ); cv::ocl::setUseOpenCL(true); } LOG4CPP_INFO( logger, "singleton(): return"); return *g_pOpenCLManager; } void OpenCLManager::destroyOpenCLManager() { g_pOpenCLManager.reset( 0 ); } void notifyOpenCLState(const char *errinfo, const void *private_info, size_t cb, void *user_data) { LOG4CPP_INFO( logger, "notifyOpenCLState"); } bool OpenCLManager::isInitialized() const { return m_isInitialized; } OpenCLManager::OpenCLManager() : m_isInitialized(false) {} void OpenCLManager::initializeDirectX(ID3D11Device* pD3D11Device) { if(m_isInitialized){ return; } //Get all Platforms and select a GPU one cl_uint numPlatforms; clGetPlatformIDs (65536, NULL, &numPlatforms); LOG4CPP_INFO( logger, "DX: Platforms detected: " << numPlatforms ); std::vector<cl_platform_id> platforms(numPlatforms); /*cl_platform_id* platformIDs; platformIDs = new cl_platform_id[numPlatforms];*/ cl_int err = clGetPlatformIDs(numPlatforms, platforms.data(), NULL); if(err != CL_SUCCESS) { LOG4CPP_INFO( logger, "DX: error at clGetPlatformIDs :" << err ); m_isInitialized = false; } int found = -1; cl_device_id device = NULL; cl_uint numDevices = 0; cl_context context = NULL; clGetDeviceIDsFromD3D11NV_fn clGetDeviceIDsFromD3D11NV = (clGetDeviceIDsFromD3D11NV_fn) clGetExtensionFunctionAddress("clGetDeviceIDsFromD3D11NV"); for (int i = 0; i < (int)numPlatforms; i++) { if (!clGetDeviceIDsFromD3D11NV) break; device = NULL; numDevices = 0; err = clGetDeviceIDsFromD3D11NV(platforms[i], CL_D3D11_DEVICE_NV, pD3D11Device, CL_PREFERRED_DEVICES_FOR_D3D11_NV, 1, &device, &numDevices); if (err != CL_SUCCESS) continue; if (numDevices > 0) { cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platforms[i], CL_CONTEXT_D3D11_DEVICE_NV, (cl_context_properties)(pD3D11Device), NULL, NULL }; m_clContext = clCreateContext(properties, 1, &device, NULL, NULL, &err); if(!m_clContext || err!= CL_SUCCESS) { LOG4CPP_INFO( logger, "error at clCreateContext :" << err ); } else { found = i; break; } } } if (found < 0) { LOG4CPP_ERROR(logger, "OpenCL: no preferred D3D11_NV device found. Trying" << "now all devices context for DirectX interop"); // try with CL_ALL_DEVICES_FOR_D3D11_KHR for (int i = 0; i < (int)numPlatforms; i++) { if (!clGetDeviceIDsFromD3D11NV) continue; device = NULL; numDevices = 0; err = clGetDeviceIDsFromD3D11NV(platforms[i], CL_D3D11_DEVICE_NV, pD3D11Device, CL_ALL_DEVICES_FOR_D3D11_NV, 1, &device, &numDevices); if (err != CL_SUCCESS) continue; if (numDevices > 0) { cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platforms[i], CL_CONTEXT_D3D11_DEVICE_NV, (cl_context_properties)(pD3D11Device), NULL, NULL }; m_clContext = clCreateContext(properties, 1, &device, NULL, NULL, &err); if(!m_clContext || err != CL_SUCCESS) { LOG4CPP_INFO( logger, "error at clCreateContext :" << err ); } else { found = i; break; } } } if (found < 0){ LOG4CPP_ERROR(logger, "OpenCL: Can't create context for DirectX interop"); m_isInitialized = false; return; } } cl_device_id selectedDeviceID; //Select a GPU device err = clGetDeviceIDs(platforms[found], CL_DEVICE_TYPE_GPU, 1, &selectedDeviceID, NULL); if(err != CL_SUCCESS) { LOG4CPP_INFO( logger, "DX: error at clGetDeviceIDs :" << err ); return; } char cDeviceNameBuffer[1024]; clGetDeviceInfo (selectedDeviceID, CL_DEVICE_NAME, sizeof(char) * 1024, cDeviceNameBuffer, NULL); LOG4CPP_INFO( logger, ": DX: Device Name: " << cDeviceNameBuffer ); //cl_platform_id selectedPlatformID = platformIDs[selectedPlatform]; //delete[] platformIDs; // //cl_device_id selectedDeviceID; ////Select a GPU device //err = clGetDeviceIDs(selectedPlatformID, CL_DEVICE_TYPE_GPU, 1, &selectedDeviceID, NULL); //if(err != CL_SUCCESS) //{ // LOG4CPP_INFO( logger, "DX: error at clGetDeviceIDs :" << err ); //} //char cDeviceNameBuffer[1024]; //clGetDeviceInfo (selectedDeviceID, CL_DEVICE_NAME, sizeof(char) * 1024, cDeviceNameBuffer, NULL); //LOG4CPP_INFO( logger, ": DX: Device Name: " << cDeviceNameBuffer ); //cl_context_properties properties[] = { // CL_CONTEXT_PLATFORM, (cl_context_properties)selectedPlatformID, // CL_CONTEXT_D3D11_DEVICE_NV, (cl_context_properties)(pD3D11Device) //}; // m_clContext = clCreateContext(properties, 1, &selectedDeviceID, NULL, NULL, &err); // //if(!m_clContext || err!= CL_SUCCESS) //{ // LOG4CPP_INFO( logger, "DX: error at clCreateContext :" << err ); //} m_clCommandQueue = clCreateCommandQueue(m_clContext, selectedDeviceID, 0, &err); if(!m_clCommandQueue || err!= CL_SUCCESS) { LOG4CPP_INFO( logger, "DX: error at clCreateCommandQueue :" << err ); return; } cv::ocl::Context& oclContext = cv::ocl::Context::getDefault(false); oclContext.initContextFromHandle(platforms[found], m_clContext, selectedDeviceID); m_isInitialized = true; LOG4CPP_INFO( logger, "initialized OpenCL: " << isInitialized()); } void OpenCLManager::initializeOpenGL() { if(m_isInitialized){ return; } //Get all Platforms and select a GPU one cl_uint numPlatforms; clGetPlatformIDs (65536, NULL, &numPlatforms); LOG4CPP_INFO( logger, "Platforms detected: " << numPlatforms ); cl_platform_id* platformIDs; platformIDs = new cl_platform_id[numPlatforms]; cl_int err = clGetPlatformIDs(numPlatforms, platformIDs, NULL); if(err != CL_SUCCESS) { LOG4CPP_INFO( logger, "error at clGetPlatformIDs :" << err ); } cl_uint selectedPlatform =0; cl_platform_id selectedPlatformID = platformIDs[selectedPlatform]; delete[] platformIDs; cl_device_id selectedDeviceID; //Select a GPU device err = clGetDeviceIDs(selectedPlatformID, CL_DEVICE_TYPE_GPU, 1, &selectedDeviceID, NULL); if(err != CL_SUCCESS) { LOG4CPP_INFO( logger, "error at clGetDeviceIDs :" << err ); } char cDeviceNameBuffer[1024]; clGetDeviceInfo (selectedDeviceID, CL_DEVICE_NAME, sizeof(char) * 1024, cDeviceNameBuffer, NULL); LOG4CPP_INFO( logger, ": Device Name: " << cDeviceNameBuffer ); //Get a context with OpenGL connection cl_context_properties props[] = { CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(), CL_WGL_HDC_KHR, (cl_context_properties) wglGetCurrentDC(), CL_CONTEXT_PLATFORM, (cl_context_properties) selectedPlatformID, 0}; cl_int status = 0; m_clContext = clCreateContextFromType(props, CL_DEVICE_TYPE_GPU, NULL, NULL, &err); //m_clContext = clCreateContext(props,1, &selectedDeviceID, NULL, NULL, &err); if(!m_clContext || err!= CL_SUCCESS) { LOG4CPP_INFO( logger, "error at clCreateContext :" << err ); } m_clCommandQueue = clCreateCommandQueue(m_clContext, selectedDeviceID, 0,&err); if(!m_clCommandQueue || err!= CL_SUCCESS) { LOG4CPP_INFO( logger, "error at clCreateCommandQueue :" << err ); } cv::ocl::Context& oclContext = cv::ocl::Context::getDefault(false); oclContext.initContextFromHandle(selectedPlatformID, m_clContext, selectedDeviceID); cl_bool temp = CL_FALSE; size_t sz = 0; bool unifiedmemory = clGetDeviceInfo(selectedDeviceID, CL_DEVICE_HOST_UNIFIED_MEMORY, sizeof(temp), &temp, &sz) == CL_SUCCESS && sz == sizeof(temp) ? temp != 0 : false; LOG4CPP_INFO( logger, "Host Unified Memory: " << unifiedmemory); m_isInitialized = true; LOG4CPP_INFO( logger, "initialized OpenCL: " << isInitialized()); } cl_context OpenCLManager::getContext() const { return m_clContext; } cl_command_queue OpenCLManager::getCommandQueue() const { return m_clCommandQueue; } OpenCLManager::~OpenCLManager(void) { } }}<commit_msg>removed debug outputs in opencl manager<commit_after>//wglGetCurrentContext, wglGetCurrentDC #include <GL/glut.h> #include "OpenCLManager.h" #include <boost/scoped_ptr.hpp> #include <boost/thread/condition.hpp> //OCL #include <opencv2/core/ocl.hpp> #include <CL/cl_gl.h> #include <CL/cl_d3d11_ext.h> #include <log4cpp/Category.hh> // get loggers static log4cpp::Category& logger( log4cpp::Category::getInstance( "Ubitrack.Vision.OpenCLManager" ) ); namespace Ubitrack { namespace Vision { static boost::scoped_ptr< OpenCLManager > g_pOpenCLManager; OpenCLManager& OpenCLManager::singleton() { static boost::mutex singletonMutex; boost::mutex::scoped_lock l( singletonMutex ); //create a new singleton if necessary if( !g_pOpenCLManager ){ g_pOpenCLManager.reset( new OpenCLManager ); cv::ocl::setUseOpenCL(true); } return *g_pOpenCLManager; } void OpenCLManager::destroyOpenCLManager() { g_pOpenCLManager.reset( 0 ); } void notifyOpenCLState(const char *errinfo, const void *private_info, size_t cb, void *user_data) { LOG4CPP_INFO( logger, "notifyOpenCLState"); } bool OpenCLManager::isInitialized() const { return m_isInitialized; } OpenCLManager::OpenCLManager() : m_isInitialized(false) {} void OpenCLManager::initializeDirectX(ID3D11Device* pD3D11Device) { if(m_isInitialized){ return; } //Get all Platforms and select a GPU one cl_uint numPlatforms; clGetPlatformIDs (65536, NULL, &numPlatforms); LOG4CPP_INFO( logger, "DX: Platforms detected: " << numPlatforms ); std::vector<cl_platform_id> platforms(numPlatforms); /*cl_platform_id* platformIDs; platformIDs = new cl_platform_id[numPlatforms];*/ cl_int err = clGetPlatformIDs(numPlatforms, platforms.data(), NULL); if(err != CL_SUCCESS) { LOG4CPP_INFO( logger, "DX: error at clGetPlatformIDs :" << err ); m_isInitialized = false; } int found = -1; cl_device_id device = NULL; cl_uint numDevices = 0; cl_context context = NULL; clGetDeviceIDsFromD3D11NV_fn clGetDeviceIDsFromD3D11NV = (clGetDeviceIDsFromD3D11NV_fn) clGetExtensionFunctionAddress("clGetDeviceIDsFromD3D11NV"); for (int i = 0; i < (int)numPlatforms; i++) { if (!clGetDeviceIDsFromD3D11NV) break; device = NULL; numDevices = 0; err = clGetDeviceIDsFromD3D11NV(platforms[i], CL_D3D11_DEVICE_NV, pD3D11Device, CL_PREFERRED_DEVICES_FOR_D3D11_NV, 1, &device, &numDevices); if (err != CL_SUCCESS) continue; if (numDevices > 0) { cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platforms[i], CL_CONTEXT_D3D11_DEVICE_NV, (cl_context_properties)(pD3D11Device), NULL, NULL }; m_clContext = clCreateContext(properties, 1, &device, NULL, NULL, &err); if(!m_clContext || err!= CL_SUCCESS) { LOG4CPP_INFO( logger, "error at clCreateContext :" << err ); } else { found = i; break; } } } if (found < 0) { LOG4CPP_ERROR(logger, "OpenCL: no preferred D3D11_NV device found. Trying" << "now all devices context for DirectX interop"); // try with CL_ALL_DEVICES_FOR_D3D11_KHR for (int i = 0; i < (int)numPlatforms; i++) { if (!clGetDeviceIDsFromD3D11NV) continue; device = NULL; numDevices = 0; err = clGetDeviceIDsFromD3D11NV(platforms[i], CL_D3D11_DEVICE_NV, pD3D11Device, CL_ALL_DEVICES_FOR_D3D11_NV, 1, &device, &numDevices); if (err != CL_SUCCESS) continue; if (numDevices > 0) { cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platforms[i], CL_CONTEXT_D3D11_DEVICE_NV, (cl_context_properties)(pD3D11Device), NULL, NULL }; m_clContext = clCreateContext(properties, 1, &device, NULL, NULL, &err); if(!m_clContext || err != CL_SUCCESS) { LOG4CPP_INFO( logger, "error at clCreateContext :" << err ); } else { found = i; break; } } } if (found < 0){ LOG4CPP_ERROR(logger, "OpenCL: Can't create context for DirectX interop"); m_isInitialized = false; return; } } cl_device_id selectedDeviceID; //Select a GPU device err = clGetDeviceIDs(platforms[found], CL_DEVICE_TYPE_GPU, 1, &selectedDeviceID, NULL); if(err != CL_SUCCESS) { LOG4CPP_INFO( logger, "DX: error at clGetDeviceIDs :" << err ); return; } char cDeviceNameBuffer[1024]; clGetDeviceInfo (selectedDeviceID, CL_DEVICE_NAME, sizeof(char) * 1024, cDeviceNameBuffer, NULL); LOG4CPP_INFO( logger, ": DX: Device Name: " << cDeviceNameBuffer ); //cl_platform_id selectedPlatformID = platformIDs[selectedPlatform]; //delete[] platformIDs; // //cl_device_id selectedDeviceID; ////Select a GPU device //err = clGetDeviceIDs(selectedPlatformID, CL_DEVICE_TYPE_GPU, 1, &selectedDeviceID, NULL); //if(err != CL_SUCCESS) //{ // LOG4CPP_INFO( logger, "DX: error at clGetDeviceIDs :" << err ); //} //char cDeviceNameBuffer[1024]; //clGetDeviceInfo (selectedDeviceID, CL_DEVICE_NAME, sizeof(char) * 1024, cDeviceNameBuffer, NULL); //LOG4CPP_INFO( logger, ": DX: Device Name: " << cDeviceNameBuffer ); //cl_context_properties properties[] = { // CL_CONTEXT_PLATFORM, (cl_context_properties)selectedPlatformID, // CL_CONTEXT_D3D11_DEVICE_NV, (cl_context_properties)(pD3D11Device) //}; // m_clContext = clCreateContext(properties, 1, &selectedDeviceID, NULL, NULL, &err); // //if(!m_clContext || err!= CL_SUCCESS) //{ // LOG4CPP_INFO( logger, "DX: error at clCreateContext :" << err ); //} m_clCommandQueue = clCreateCommandQueue(m_clContext, selectedDeviceID, 0, &err); if(!m_clCommandQueue || err!= CL_SUCCESS) { LOG4CPP_INFO( logger, "DX: error at clCreateCommandQueue :" << err ); return; } cv::ocl::Context& oclContext = cv::ocl::Context::getDefault(false); oclContext.initContextFromHandle(platforms[found], m_clContext, selectedDeviceID); m_isInitialized = true; LOG4CPP_INFO( logger, "initialized OpenCL: " << isInitialized()); } void OpenCLManager::initializeOpenGL() { if(m_isInitialized){ return; } //Get all Platforms and select a GPU one cl_uint numPlatforms; clGetPlatformIDs (65536, NULL, &numPlatforms); LOG4CPP_INFO( logger, "Platforms detected: " << numPlatforms ); cl_platform_id* platformIDs; platformIDs = new cl_platform_id[numPlatforms]; cl_int err = clGetPlatformIDs(numPlatforms, platformIDs, NULL); if(err != CL_SUCCESS) { LOG4CPP_INFO( logger, "error at clGetPlatformIDs :" << err ); } cl_uint selectedPlatform =0; cl_platform_id selectedPlatformID = platformIDs[selectedPlatform]; delete[] platformIDs; cl_device_id selectedDeviceID; //Select a GPU device err = clGetDeviceIDs(selectedPlatformID, CL_DEVICE_TYPE_GPU, 1, &selectedDeviceID, NULL); if(err != CL_SUCCESS) { LOG4CPP_INFO( logger, "error at clGetDeviceIDs :" << err ); } char cDeviceNameBuffer[1024]; clGetDeviceInfo (selectedDeviceID, CL_DEVICE_NAME, sizeof(char) * 1024, cDeviceNameBuffer, NULL); LOG4CPP_INFO( logger, ": Device Name: " << cDeviceNameBuffer ); //Get a context with OpenGL connection cl_context_properties props[] = { CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(), CL_WGL_HDC_KHR, (cl_context_properties) wglGetCurrentDC(), CL_CONTEXT_PLATFORM, (cl_context_properties) selectedPlatformID, 0}; cl_int status = 0; m_clContext = clCreateContextFromType(props, CL_DEVICE_TYPE_GPU, NULL, NULL, &err); //m_clContext = clCreateContext(props,1, &selectedDeviceID, NULL, NULL, &err); if(!m_clContext || err!= CL_SUCCESS) { LOG4CPP_INFO( logger, "error at clCreateContext :" << err ); } m_clCommandQueue = clCreateCommandQueue(m_clContext, selectedDeviceID, 0,&err); if(!m_clCommandQueue || err!= CL_SUCCESS) { LOG4CPP_INFO( logger, "error at clCreateCommandQueue :" << err ); } cv::ocl::Context& oclContext = cv::ocl::Context::getDefault(false); oclContext.initContextFromHandle(selectedPlatformID, m_clContext, selectedDeviceID); cl_bool temp = CL_FALSE; size_t sz = 0; bool unifiedmemory = clGetDeviceInfo(selectedDeviceID, CL_DEVICE_HOST_UNIFIED_MEMORY, sizeof(temp), &temp, &sz) == CL_SUCCESS && sz == sizeof(temp) ? temp != 0 : false; LOG4CPP_INFO( logger, "Host Unified Memory: " << unifiedmemory); m_isInitialized = true; LOG4CPP_INFO( logger, "initialized OpenCL: " << isInitialized()); } cl_context OpenCLManager::getContext() const { return m_clContext; } cl_command_queue OpenCLManager::getCommandQueue() const { return m_clCommandQueue; } OpenCLManager::~OpenCLManager(void) { } }}<|endoftext|>
<commit_before>#include <iostream> #include <string> using namespace std; int main() { string s,s1; int n; cin>>n; for(int k=0;k<n;k++) { cin>>s; s1=""; for(int i=s.size()-1;i>=0;i--) { s1 += s[i]; } cout<<s1<<endl; } return 0; }<commit_msg>edits<commit_after>/* Problem Link: https://www.hackerearth.com/code-monk-array-strings/algorithm/terrible-chandu/ */ #include <iostream> #include <string> using namespace std; int main() { string s,s1; int n; cin>>n; for(int k=0;k<n;k++) { cin>>s; s1=""; for(int i=s.size()-1;i>=0;i--) { s1 += s[i]; } cout<<s1<<endl; } return 0; }<|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkColourImageProcessingView.h" #include "ui_QmitkColourImageProcessingViewControls.h" #include "mitkColourImageProcessor.h" #include "mitkDataNodeObject.h" #include "mitkTransferFunction.h" #include "mitkTransferFunctionProperty.h" #include "QmitkColorTransferFunctionCanvas.h" #include "QmitkPiecewiseFunctionCanvas.h" #include <berryISelectionProvider.h> #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> #include <QColor> #include <QColorDialog> #include <QComboBox> #include <QMessageBox> const std::string QmitkColourImageProcessingView::VIEW_ID = "org.mitk.views.colourimageprocessing"; QmitkColourImageProcessingView::QmitkColourImageProcessingView() : m_Controls(nullptr) { m_Color[0] = 255; m_Color[1] = 0; m_Color[2] = 0; } void QmitkColourImageProcessingView::SetFocus() { m_Controls->m_ConvertImageToRGBA->setFocus(); } void QmitkColourImageProcessingView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { m_Controls = new Ui::QmitkColourImageProcessingViewControls; m_Controls->setupUi(parent); connect(m_Controls->m_ConvertImageToRGBA, SIGNAL(clicked(bool)), this, SLOT(OnConvertToRGBAImage())); connect(m_Controls->m_ConvertImageMaskToRGBA, SIGNAL(clicked(bool)), this, SLOT(OnConvertToRGBAImage())); connect(m_Controls->m_ConvertImageMaskColorToRGBA, SIGNAL(clicked(bool)), this, SLOT(OnConvertImageMaskColorToRGBAImage())); connect(m_Controls->m_ColorButton, SIGNAL(clicked(bool)), this, SLOT(OnChangeColor())); connect(m_Controls->m_CombineRGBAButton, SIGNAL(clicked(bool)), this, SLOT(OnCombineRGBA())); m_Controls->m_ImageSelectedLabel->hide(); m_Controls->m_NoImageSelectedLabel->show(); } } void QmitkColourImageProcessingView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList<mitk::DataNode::Pointer> &nodes) { if (!nodes.isEmpty()) { QList<mitk::DataNode::Pointer> selectedNodes; foreach (const mitk::DataNode::Pointer node, nodes) { if (node.IsNotNull()) { mitk::Image *image = dynamic_cast<mitk::Image *>(node->GetData()); if (image->GetDimension() >= 3) { selectedNodes.push_back(node); } } } mitk::DataNode::Pointer node; if (selectedNodes.size() > 0) { node = selectedNodes[0]; m_SelectedNode = node; m_Controls->m_NoImageSelectedLabel->hide(); m_Controls->m_ImageSelectedLabel->show(); std::string infoText = std::string("Selected Image: ") + node->GetName(); if (selectedNodes.size() > 1) { mitk::DataNode::Pointer node2; node2 = selectedNodes[1]; m_SelectedNode2 = node2; infoText = infoText + " and " + node2->GetName(); } else { m_SelectedNode2 = nullptr; } m_Controls->m_ImageSelectedLabel->setText(QString(infoText.c_str())); } else { m_Controls->m_ImageSelectedLabel->hide(); m_Controls->m_NoImageSelectedLabel->show(); m_SelectedNode = nullptr; m_SelectedNode2 = nullptr; } } } void QmitkColourImageProcessingView::OnConvertToRGBAImage() { if (m_SelectedNode.IsExpired()) return; auto selectedNode = m_SelectedNode.Lock(); mitk::TransferFunctionProperty::Pointer transferFunctionProp = dynamic_cast<mitk::TransferFunctionProperty *>(selectedNode->GetProperty("TransferFunction")); if (transferFunctionProp.IsNull()) return; mitk::TransferFunction::Pointer tf = transferFunctionProp->GetValue(); if (tf.IsNull()) return; mitk::mitkColourImageProcessor CImageProcessor; mitk::Image::Pointer RGBAImageResult; if (!m_SelectedNode2.IsExpired()) { RGBAImageResult = CImageProcessor.convertWithBinaryToRGBAImage(dynamic_cast<mitk::Image *>(selectedNode->GetData()), dynamic_cast<mitk::Image *>(selectedNode2.Lock()->GetData()), tf); } else { RGBAImageResult = CImageProcessor.convertToRGBAImage(dynamic_cast<mitk::Image *>(selectedNode->GetData()), tf); } if (!RGBAImageResult) { QMessageBox::warning(nullptr, "Warning", QString("Unsupported pixeltype")); return; } mitk::DataNode::Pointer dtn = mitk::DataNode::New(); dtn->SetData(RGBAImageResult); dtn->SetName(selectedNode->GetName() + "_RGBA"); this->GetDataStorage()->Add(dtn); // add as a child, because the segmentation "derives" from the original MITK_INFO << "convertToRGBAImage finish"; } void QmitkColourImageProcessingView::OnConvertImageMaskColorToRGBAImage() { if (m_SelectedNode.IsExpired()) return; auto selectedNode = m_SelectedNode.Lock(); mitk::TransferFunctionProperty::Pointer transferFunctionProp = dynamic_cast<mitk::TransferFunctionProperty *>(selectedNode->GetProperty("TransferFunction")); if (transferFunctionProp.IsNull()) return; mitk::TransferFunction::Pointer tf = transferFunctionProp->GetValue(); if (tf.IsNull()) return; mitk::mitkColourImageProcessor CImageProcessor; mitk::Image::Pointer RGBAImageResult; if (!m_SelectedNode2.IsExpired()) { RGBAImageResult = CImageProcessor.convertWithBinaryAndColorToRGBAImage(dynamic_cast<mitk::Image *>(selectedNode->GetData()), dynamic_cast<mitk::Image *>(m_SelectedNode2.Lock()->GetData()), tf, m_Color); } else { RGBAImageResult = CImageProcessor.convertToRGBAImage(dynamic_cast<mitk::Image *>(selectedNode->GetData()), tf); } if (!RGBAImageResult) { QMessageBox::warning(nullptr, "Warning", QString("Unsupported pixeltype")); return; } mitk::DataNode::Pointer dtn = mitk::DataNode::New(); dtn->SetData(RGBAImageResult); dtn->SetName(selectedNode->GetName() + "_RGBA"); this->GetDataStorage()->Add(dtn); // add as a child, because the segmentation "derives" from the original } void QmitkColourImageProcessingView::OnChangeColor() { QColor color = QColorDialog::getColor(); if (color.spec() == 0) { color.setRed(255); color.setGreen(0); color.setBlue(0); } m_Color[0] = color.red(); m_Color[1] = color.green(); m_Color[2] = color.blue(); m_Controls->m_ColorButton->setStyleSheet( QString("background-color:rgb(%1,%2, %3)").arg(color.red()).arg(color.green()).arg(color.blue())); } void QmitkColourImageProcessingView::OnCombineRGBA() { if (m_SelectedNode.IsExpired()) return; if (m_SelectedNode2.IsExpired()) return; mitk::mitkColourImageProcessor CImageProcessor; mitk::Image::Pointer RGBAImageResult; RGBAImageResult = CImageProcessor.combineRGBAImage(dynamic_cast<mitk::Image *>(m_SelectedNode.Lock()->GetData()), dynamic_cast<mitk::Image *>(m_SelectedNode2.Lock()->GetData())); MITK_INFO << "RGBAImage Result"; mitk::DataNode::Pointer dtn = mitk::DataNode::New(); dtn->SetData(RGBAImageResult); this->GetDataStorage()->Add(dtn); // add as a child, because the segmentation "derives" from the original } <commit_msg>Fix typo in reference to member variable<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 "QmitkColourImageProcessingView.h" #include "ui_QmitkColourImageProcessingViewControls.h" #include "mitkColourImageProcessor.h" #include "mitkDataNodeObject.h" #include "mitkTransferFunction.h" #include "mitkTransferFunctionProperty.h" #include "QmitkColorTransferFunctionCanvas.h" #include "QmitkPiecewiseFunctionCanvas.h" #include <berryISelectionProvider.h> #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> #include <QColor> #include <QColorDialog> #include <QComboBox> #include <QMessageBox> const std::string QmitkColourImageProcessingView::VIEW_ID = "org.mitk.views.colourimageprocessing"; QmitkColourImageProcessingView::QmitkColourImageProcessingView() : m_Controls(nullptr) { m_Color[0] = 255; m_Color[1] = 0; m_Color[2] = 0; } void QmitkColourImageProcessingView::SetFocus() { m_Controls->m_ConvertImageToRGBA->setFocus(); } void QmitkColourImageProcessingView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { m_Controls = new Ui::QmitkColourImageProcessingViewControls; m_Controls->setupUi(parent); connect(m_Controls->m_ConvertImageToRGBA, SIGNAL(clicked(bool)), this, SLOT(OnConvertToRGBAImage())); connect(m_Controls->m_ConvertImageMaskToRGBA, SIGNAL(clicked(bool)), this, SLOT(OnConvertToRGBAImage())); connect(m_Controls->m_ConvertImageMaskColorToRGBA, SIGNAL(clicked(bool)), this, SLOT(OnConvertImageMaskColorToRGBAImage())); connect(m_Controls->m_ColorButton, SIGNAL(clicked(bool)), this, SLOT(OnChangeColor())); connect(m_Controls->m_CombineRGBAButton, SIGNAL(clicked(bool)), this, SLOT(OnCombineRGBA())); m_Controls->m_ImageSelectedLabel->hide(); m_Controls->m_NoImageSelectedLabel->show(); } } void QmitkColourImageProcessingView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList<mitk::DataNode::Pointer> &nodes) { if (!nodes.isEmpty()) { QList<mitk::DataNode::Pointer> selectedNodes; foreach (const mitk::DataNode::Pointer node, nodes) { if (node.IsNotNull()) { mitk::Image *image = dynamic_cast<mitk::Image *>(node->GetData()); if (image->GetDimension() >= 3) { selectedNodes.push_back(node); } } } mitk::DataNode::Pointer node; if (selectedNodes.size() > 0) { node = selectedNodes[0]; m_SelectedNode = node; m_Controls->m_NoImageSelectedLabel->hide(); m_Controls->m_ImageSelectedLabel->show(); std::string infoText = std::string("Selected Image: ") + node->GetName(); if (selectedNodes.size() > 1) { mitk::DataNode::Pointer node2; node2 = selectedNodes[1]; m_SelectedNode2 = node2; infoText = infoText + " and " + node2->GetName(); } else { m_SelectedNode2 = nullptr; } m_Controls->m_ImageSelectedLabel->setText(QString(infoText.c_str())); } else { m_Controls->m_ImageSelectedLabel->hide(); m_Controls->m_NoImageSelectedLabel->show(); m_SelectedNode = nullptr; m_SelectedNode2 = nullptr; } } } void QmitkColourImageProcessingView::OnConvertToRGBAImage() { if (m_SelectedNode.IsExpired()) return; auto selectedNode = m_SelectedNode.Lock(); mitk::TransferFunctionProperty::Pointer transferFunctionProp = dynamic_cast<mitk::TransferFunctionProperty *>(selectedNode->GetProperty("TransferFunction")); if (transferFunctionProp.IsNull()) return; mitk::TransferFunction::Pointer tf = transferFunctionProp->GetValue(); if (tf.IsNull()) return; mitk::mitkColourImageProcessor CImageProcessor; mitk::Image::Pointer RGBAImageResult; if (!m_SelectedNode2.IsExpired()) { RGBAImageResult = CImageProcessor.convertWithBinaryToRGBAImage(dynamic_cast<mitk::Image *>(selectedNode->GetData()), dynamic_cast<mitk::Image *>(m_SelectedNode2.Lock()->GetData()), tf); } else { RGBAImageResult = CImageProcessor.convertToRGBAImage(dynamic_cast<mitk::Image *>(selectedNode->GetData()), tf); } if (!RGBAImageResult) { QMessageBox::warning(nullptr, "Warning", QString("Unsupported pixeltype")); return; } mitk::DataNode::Pointer dtn = mitk::DataNode::New(); dtn->SetData(RGBAImageResult); dtn->SetName(selectedNode->GetName() + "_RGBA"); this->GetDataStorage()->Add(dtn); // add as a child, because the segmentation "derives" from the original MITK_INFO << "convertToRGBAImage finish"; } void QmitkColourImageProcessingView::OnConvertImageMaskColorToRGBAImage() { if (m_SelectedNode.IsExpired()) return; auto selectedNode = m_SelectedNode.Lock(); mitk::TransferFunctionProperty::Pointer transferFunctionProp = dynamic_cast<mitk::TransferFunctionProperty *>(selectedNode->GetProperty("TransferFunction")); if (transferFunctionProp.IsNull()) return; mitk::TransferFunction::Pointer tf = transferFunctionProp->GetValue(); if (tf.IsNull()) return; mitk::mitkColourImageProcessor CImageProcessor; mitk::Image::Pointer RGBAImageResult; if (!m_SelectedNode2.IsExpired()) { RGBAImageResult = CImageProcessor.convertWithBinaryAndColorToRGBAImage(dynamic_cast<mitk::Image *>(selectedNode->GetData()), dynamic_cast<mitk::Image *>(m_SelectedNode2.Lock()->GetData()), tf, m_Color); } else { RGBAImageResult = CImageProcessor.convertToRGBAImage(dynamic_cast<mitk::Image *>(selectedNode->GetData()), tf); } if (!RGBAImageResult) { QMessageBox::warning(nullptr, "Warning", QString("Unsupported pixeltype")); return; } mitk::DataNode::Pointer dtn = mitk::DataNode::New(); dtn->SetData(RGBAImageResult); dtn->SetName(selectedNode->GetName() + "_RGBA"); this->GetDataStorage()->Add(dtn); // add as a child, because the segmentation "derives" from the original } void QmitkColourImageProcessingView::OnChangeColor() { QColor color = QColorDialog::getColor(); if (color.spec() == 0) { color.setRed(255); color.setGreen(0); color.setBlue(0); } m_Color[0] = color.red(); m_Color[1] = color.green(); m_Color[2] = color.blue(); m_Controls->m_ColorButton->setStyleSheet( QString("background-color:rgb(%1,%2, %3)").arg(color.red()).arg(color.green()).arg(color.blue())); } void QmitkColourImageProcessingView::OnCombineRGBA() { if (m_SelectedNode.IsExpired()) return; if (m_SelectedNode2.IsExpired()) return; mitk::mitkColourImageProcessor CImageProcessor; mitk::Image::Pointer RGBAImageResult; RGBAImageResult = CImageProcessor.combineRGBAImage(dynamic_cast<mitk::Image *>(m_SelectedNode.Lock()->GetData()), dynamic_cast<mitk::Image *>(m_SelectedNode2.Lock()->GetData())); MITK_INFO << "RGBAImage Result"; mitk::DataNode::Pointer dtn = mitk::DataNode::New(); dtn->SetData(RGBAImageResult); this->GetDataStorage()->Add(dtn); // add as a child, because the segmentation "derives" from the original } <|endoftext|>
<commit_before>#include <string.h> #include "command.h" #include "../CmdHandler.h" #include "../option.h" #include "../sed.h" #include "../stringparse.h" #define ON 1 #define OFF 2 /* full name of the command */ CMDNAME("editcom"); /* description of the command */ CMDDESCR("modify a custom command"); /* command usage synopsis */ CMDUSAGE("$editcom [-A on|off] [-a] [-c CD] [-r] [-s SEDCMD] CMD [RESPONSE]"); /* rename flag usage */ static const char *RUSAGE = "$editcom -r OLD NEW"; /* whether to append to existing response */ static int app; /* active setting */ static int set; /* command cooldown */ time_t cooldown; static int edit(char *out, CustomHandler *cch, struct command *c); static int rename(char *out, CustomHandler *cch, struct command *c); static int cmdsed(char *out, CustomHandler *cch, struct command *c, const char *sedcmd); static void outputmsg(char *out, struct command *c, char *resp); /* editcom: modify a custom command */ int CmdHandler::editcom(char *out, struct command *c) { int ren, sed, status; char sedcmd[MAX_MSG]; int opt; static struct l_option long_opts[] = { { "active", REQ_ARG, 'A'}, { "append", NO_ARG, 'a'}, { "cooldown", REQ_ARG, 'c'}, { "help", NO_ARG, 'h' }, { "rename", NO_ARG, 'r' }, { "sed", REQ_ARG, 's' }, { 0, 0, 0 } }; if (!P_ALMOD(c->privileges)) { PERM_DENIED(out, c->nick, c->argv[0]); return EXIT_FAILURE; } if (!m_customCmds->isActive()) { _sprintf(out, MAX_MSG, "%s: custom commands are currently " "disabled", c->argv[0]); return EXIT_FAILURE; } opt_init(); cooldown = -1; set = ren = app = sed = 0; status = EXIT_SUCCESS; while ((opt = l_getopt_long(c->argc, c->argv, "A:ac:rs:", long_opts)) != EOF) { switch (opt) { case 'A': if (strcmp(l_optarg, "on") == 0) { set = ON; } else if (strcmp(l_optarg, "off") == 0) { set = OFF; } else { _sprintf(out, MAX_MSG, "%s: -A setting must " "be on/off", c->argv[0]); return EXIT_FAILURE; } break; case 'a': app = 1; break; case 'c': /* user provided a cooldown */ if (!parsenum(l_optarg, &cooldown)) { _sprintf(out, MAX_MSG, "%s: invalid number: %s", c->argv[0], l_optarg); return EXIT_FAILURE; } if (cooldown < 0) { _sprintf(out, MAX_MSG, "%s: cooldown cannot be " "negative", c->argv[0]); return EXIT_FAILURE; } break; case 'h': HELPMSG(out, CMDNAME, CMDUSAGE, CMDDESCR); return EXIT_SUCCESS; case 'r': ren = 1; break; case 's': sed = 1; strcpy(sedcmd, l_optarg); break; case '?': _sprintf(out, MAX_MSG, "%s", l_opterr()); return EXIT_FAILURE; default: return EXIT_FAILURE; } } if (l_optind == c->argc) { USAGEMSG(out, CMDNAME, CMDUSAGE); return EXIT_FAILURE; } if (sed) { if (app || ren) { _sprintf(out, MAX_MSG, "%s: cannot use -a or -r " "with -s", c->argv[0]); status = EXIT_FAILURE; } else if (l_optind != c->argc - 1) { _sprintf(out, MAX_MSG, "%s: cannot provide reponse" "with -s flag", c->argv[0]); status = EXIT_FAILURE; } else { status = cmdsed(out, m_customCmds, c, sedcmd); } } else if (ren) { if (app || cooldown != -1 || set || sed) { _sprintf(out, MAX_MSG, "%s: cannot use other flags " "with -r", c->argv[0]); status = EXIT_FAILURE; } else { status = rename(out, m_customCmds, c); } } else { status = edit(out, m_customCmds, c); } return status; } /* edit: edit a custom command */ static int edit(char *out, CustomHandler *cch, struct command *c) { int resp; char response[MAX_MSG]; char buf[MAX_MSG]; Json::Value *com; /* determine which parts are being changed */ resp = l_optind != c->argc - 1; argvcat(response, c->argc, c->argv, l_optind + 1, 1); if (app) { if ((com = cch->getcom(c->argv[l_optind]))->empty()) { _sprintf(out, MAX_MSG, "%s: not a command: $%s", c->argv[0], c->argv[l_optind]); return EXIT_FAILURE; } strcpy(buf, response); _sprintf(response, MAX_MSG, "%s %s", (*com)["response"].asCString(), buf); } if (!cch->editcom(c->argv[l_optind], response, cooldown)) { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], cch->error().c_str()); return EXIT_FAILURE; } if (cooldown == -1 && !resp && !set) { _sprintf(out, MAX_MSG, "@%s, command $%s was unchanged", c->nick, c->argv[l_optind]); return EXIT_SUCCESS; } if (set == ON && !cch->activate(c->argv[l_optind])) { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], cch->error().c_str()); return EXIT_FAILURE; } else if (set == OFF) { cch->deactivate(c->argv[l_optind]); } outputmsg(out, c, resp ? response : NULL); return EXIT_SUCCESS; } /* rename: rename a custom command */ static int rename(char *out, CustomHandler *cch, struct command *c) { int status; if (l_optind != c->argc - 2) { USAGEMSG(out, CMDNAME, RUSAGE); status = EXIT_FAILURE; } else if (!cch->rename(c->argv[l_optind], c->argv[l_optind + 1])) { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], cch->error().c_str()); status = EXIT_FAILURE; } else { _sprintf(out, MAX_MSG, "@%s, command $%s has been renamed " "to $%s", c->nick, c->argv[l_optind], c->argv[l_optind + 1]); status = EXIT_SUCCESS; } return status; } /* cmdsed: perform a sed operation on command response */ static int cmdsed(char *out, CustomHandler *cch, struct command *c, const char *sedcmd) { Json::Value *com; char buf[MAX_MSG]; if ((com = cch->getcom(c->argv[l_optind]))->empty()) { _sprintf(out, MAX_MSG, "%s: not a command: $%s", c->argv[0], c->argv[l_optind]); return EXIT_FAILURE; } if (!sed(buf, MAX_MSG, (*com)["response"].asCString(), sedcmd)) { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], buf); return EXIT_FAILURE; } if (!cch->editcom(c->argv[l_optind], buf, cooldown)) { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], cch->error().c_str()); return EXIT_FAILURE; } if (set == ON && !cch->activate(c->argv[l_optind])) { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], cch->error().c_str()); return EXIT_FAILURE; } else if (set == OFF) { cch->deactivate(c->argv[l_optind]); } outputmsg(out, c, buf); return EXIT_SUCCESS; } /* outputmsg: write a message to out detailing command changes */ static void outputmsg(char *out, struct command *c, char *resp) { int cd; cd = cooldown != -1; _sprintf(out, MAX_MSG, "@%s, command $%s has been", c->nick, c->argv[l_optind]); if (set == ON) strcat(out, " activated"); else if (set == OFF) strcat(out, " deactivated"); if (resp || cd) { if (set) strcat(out, " and"); strcat(out, " changed to "); out = strchr(out, '\0'); if (resp) { _sprintf(out, MAX_MSG, "\"%s\"%s", resp, cd ? ", with " : ""); out = strchr(out, '\0'); } if (cd) { _sprintf(out, MAX_MSG, "a %lds cooldown", cooldown); } } strcat(out, "."); } <commit_msg>editcom: make cooldown static<commit_after>#include <string.h> #include "command.h" #include "../CmdHandler.h" #include "../option.h" #include "../sed.h" #include "../stringparse.h" #define ON 1 #define OFF 2 /* full name of the command */ CMDNAME("editcom"); /* description of the command */ CMDDESCR("modify a custom command"); /* command usage synopsis */ CMDUSAGE("$editcom [-A on|off] [-a] [-c CD] [-r] [-s SEDCMD] CMD [RESPONSE]"); /* rename flag usage */ static const char *RUSAGE = "$editcom -r OLD NEW"; /* whether to append to existing response */ static int app; /* active setting */ static int set; /* command cooldown */ static time_t cooldown; static int edit(char *out, CustomHandler *cch, struct command *c); static int rename(char *out, CustomHandler *cch, struct command *c); static int cmdsed(char *out, CustomHandler *cch, struct command *c, const char *sedcmd); static void outputmsg(char *out, struct command *c, char *resp); /* editcom: modify a custom command */ int CmdHandler::editcom(char *out, struct command *c) { int ren, sed, status; char sedcmd[MAX_MSG]; int opt; static struct l_option long_opts[] = { { "active", REQ_ARG, 'A'}, { "append", NO_ARG, 'a'}, { "cooldown", REQ_ARG, 'c'}, { "help", NO_ARG, 'h' }, { "rename", NO_ARG, 'r' }, { "sed", REQ_ARG, 's' }, { 0, 0, 0 } }; if (!P_ALMOD(c->privileges)) { PERM_DENIED(out, c->nick, c->argv[0]); return EXIT_FAILURE; } if (!m_customCmds->isActive()) { _sprintf(out, MAX_MSG, "%s: custom commands are currently " "disabled", c->argv[0]); return EXIT_FAILURE; } opt_init(); cooldown = -1; set = ren = app = sed = 0; status = EXIT_SUCCESS; while ((opt = l_getopt_long(c->argc, c->argv, "A:ac:rs:", long_opts)) != EOF) { switch (opt) { case 'A': if (strcmp(l_optarg, "on") == 0) { set = ON; } else if (strcmp(l_optarg, "off") == 0) { set = OFF; } else { _sprintf(out, MAX_MSG, "%s: -A setting must " "be on/off", c->argv[0]); return EXIT_FAILURE; } break; case 'a': app = 1; break; case 'c': /* user provided a cooldown */ if (!parsenum(l_optarg, &cooldown)) { _sprintf(out, MAX_MSG, "%s: invalid number: %s", c->argv[0], l_optarg); return EXIT_FAILURE; } if (cooldown < 0) { _sprintf(out, MAX_MSG, "%s: cooldown cannot be " "negative", c->argv[0]); return EXIT_FAILURE; } break; case 'h': HELPMSG(out, CMDNAME, CMDUSAGE, CMDDESCR); return EXIT_SUCCESS; case 'r': ren = 1; break; case 's': sed = 1; strcpy(sedcmd, l_optarg); break; case '?': _sprintf(out, MAX_MSG, "%s", l_opterr()); return EXIT_FAILURE; default: return EXIT_FAILURE; } } if (l_optind == c->argc) { USAGEMSG(out, CMDNAME, CMDUSAGE); return EXIT_FAILURE; } if (sed) { if (app || ren) { _sprintf(out, MAX_MSG, "%s: cannot use -a or -r " "with -s", c->argv[0]); status = EXIT_FAILURE; } else if (l_optind != c->argc - 1) { _sprintf(out, MAX_MSG, "%s: cannot provide reponse" "with -s flag", c->argv[0]); status = EXIT_FAILURE; } else { status = cmdsed(out, m_customCmds, c, sedcmd); } } else if (ren) { if (app || cooldown != -1 || set || sed) { _sprintf(out, MAX_MSG, "%s: cannot use other flags " "with -r", c->argv[0]); status = EXIT_FAILURE; } else { status = rename(out, m_customCmds, c); } } else { status = edit(out, m_customCmds, c); } return status; } /* edit: edit a custom command */ static int edit(char *out, CustomHandler *cch, struct command *c) { int resp; char response[MAX_MSG]; char buf[MAX_MSG]; Json::Value *com; /* determine which parts are being changed */ resp = l_optind != c->argc - 1; argvcat(response, c->argc, c->argv, l_optind + 1, 1); if (app) { if ((com = cch->getcom(c->argv[l_optind]))->empty()) { _sprintf(out, MAX_MSG, "%s: not a command: $%s", c->argv[0], c->argv[l_optind]); return EXIT_FAILURE; } strcpy(buf, response); _sprintf(response, MAX_MSG, "%s %s", (*com)["response"].asCString(), buf); } if (!cch->editcom(c->argv[l_optind], response, cooldown)) { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], cch->error().c_str()); return EXIT_FAILURE; } if (cooldown == -1 && !resp && !set) { _sprintf(out, MAX_MSG, "@%s, command $%s was unchanged", c->nick, c->argv[l_optind]); return EXIT_SUCCESS; } if (set == ON && !cch->activate(c->argv[l_optind])) { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], cch->error().c_str()); return EXIT_FAILURE; } else if (set == OFF) { cch->deactivate(c->argv[l_optind]); } outputmsg(out, c, resp ? response : NULL); return EXIT_SUCCESS; } /* rename: rename a custom command */ static int rename(char *out, CustomHandler *cch, struct command *c) { int status; if (l_optind != c->argc - 2) { USAGEMSG(out, CMDNAME, RUSAGE); status = EXIT_FAILURE; } else if (!cch->rename(c->argv[l_optind], c->argv[l_optind + 1])) { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], cch->error().c_str()); status = EXIT_FAILURE; } else { _sprintf(out, MAX_MSG, "@%s, command $%s has been renamed " "to $%s", c->nick, c->argv[l_optind], c->argv[l_optind + 1]); status = EXIT_SUCCESS; } return status; } /* cmdsed: perform a sed operation on command response */ static int cmdsed(char *out, CustomHandler *cch, struct command *c, const char *sedcmd) { Json::Value *com; char buf[MAX_MSG]; if ((com = cch->getcom(c->argv[l_optind]))->empty()) { _sprintf(out, MAX_MSG, "%s: not a command: $%s", c->argv[0], c->argv[l_optind]); return EXIT_FAILURE; } if (!sed(buf, MAX_MSG, (*com)["response"].asCString(), sedcmd)) { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], buf); return EXIT_FAILURE; } if (!cch->editcom(c->argv[l_optind], buf, cooldown)) { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], cch->error().c_str()); return EXIT_FAILURE; } if (set == ON && !cch->activate(c->argv[l_optind])) { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], cch->error().c_str()); return EXIT_FAILURE; } else if (set == OFF) { cch->deactivate(c->argv[l_optind]); } outputmsg(out, c, buf); return EXIT_SUCCESS; } /* outputmsg: write a message to out detailing command changes */ static void outputmsg(char *out, struct command *c, char *resp) { int cd; cd = cooldown != -1; _sprintf(out, MAX_MSG, "@%s, command $%s has been", c->nick, c->argv[l_optind]); if (set == ON) strcat(out, " activated"); else if (set == OFF) strcat(out, " deactivated"); if (resp || cd) { if (set) strcat(out, " and"); strcat(out, " changed to "); out = strchr(out, '\0'); if (resp) { _sprintf(out, MAX_MSG, "\"%s\"%s", resp, cd ? ", with " : ""); out = strchr(out, '\0'); } if (cd) { _sprintf(out, MAX_MSG, "a %lds cooldown", cooldown); } } strcat(out, "."); } <|endoftext|>
<commit_before>#ifndef __SIMULATEDANNEALING__ #define __SIMULATEDANNEALING__ #include <iostream> #include <vector> #include <cmath> #include <cfloat> #include <TRandom.h> namespace RAT { class Minimizable { public: virtual double operator()(double *args) = 0; }; template <int D> class SimulatedAnnealing { protected: double temp; Minimizable *funk; double simplex[D+1][D], val[D+1]; double global_best_pt[D], global_best_val; public: SimulatedAnnealing(Minimizable *funk_) : funk(funk_) { } ~SimulatedAnnealing() { } void SetSimplexPoint(size_t pt, std::vector<double> &point) { for (size_t j = 0; j < D; j++) { simplex[pt][j] = point[j]; } val[pt] = (*funk)(simplex[pt]); } void Anneal(double temp0, size_t nAnneal, size_t nEval, double alpha) { global_best_val = DBL_MAX; for (size_t cycle = 0; cycle < nAnneal; cycle++) { temp = temp0*pow(1-(double)cycle/nAnneal,alpha); int iter = nEval; amoeba(&iter); } } void GetBestPoint(std::vector<double> &point) { for (size_t j = 0; j < D; j++) { point[j] = global_best_pt[j]; } } protected: inline double replace_project(const double (&offset)[D], const double (&by)[D], const double factor, double (&into)[D]) { for (size_t j = 0; j < D; j++) { into[j] = offset[j] + factor*by[j]; } double val_try = (*funk)(into); if (val_try < global_best_val) { global_best_val = val_try; for (size_t j = 0; j < D; j++) { global_best_pt[j] = into[j]; } } return val_try; } void amoeba(int *iter) { //best, worst, and next worst points size_t i_best, i_worst, i_nextworst; double val_best, val_worst, val_nextworst; const double alpha = 1.0; const double gamma = 2.0; const double rho =-0.5; const double sigma = 0.5; double centroid[D]; //centroid of all but worst double dworst[D]; //vector from worst to centroid double try_pt[D]; //temporary vector for test point //std::cout << "*******************************\n"; for ( ; *iter > 0; ) { //find best, worst, nextworst (can optomize a lot of this later) i_best = i_worst = i_nextworst = -1; val_best = DBL_MAX, val_worst = val_nextworst = -DBL_MAX; for (size_t i = 0; i <= D; i++) { const double val_thermal = val[i] - temp*log(gRandom->Rndm()); //std::cout << val[i] << ' '; if (val_thermal < val_best) { i_best = i; val_best = val_thermal; } if (val_thermal > val_worst) { i_nextworst = i_worst; val_nextworst = val_worst; i_worst = i; val_worst = val_thermal; } else if (val_thermal > val_nextworst) { i_nextworst = i; val_nextworst = val_thermal; } } //std::cout << "~ " << i_best << '/' << i_nextworst << '/' << i_worst << " & "; //std::cout << val_best << '/' << val_nextworst << '/' << val_worst << "\n"; //update centroid, dworst for (size_t j = 0; j < D; j++) { centroid[j] = 0.0; for (size_t i = 0; i <= D; i++) { if (i == i_worst) continue; centroid[j] += simplex[i][j]; } centroid[j] /= D; dworst[j] = centroid[j] - simplex[i_worst][j]; } //std::cout << "+++++++++++\n"; //definitely replacing the worst point, try with reflecting val[i_worst] = replace_project(centroid,dworst,alpha,simplex[i_worst]); const double val_ref_therm = val[i_worst] + temp*log(gRandom->Rndm()); //std::cout << "\tRef: " << val_ref_therm << "\n"; (*iter)--; if (val_ref_therm < val_nextworst && val_ref_therm >= val_best) { // reflected point was better than the two worst and replaced // the worst point, so continue //std::cout << "reflected (okay)" << std::endl; continue; } else if (val_ref_therm < val_best) { // reflecting was really good, try further const double val_try = replace_project(centroid,dworst,gamma,try_pt) ; //std::cout << "\tExp: " << val_try << "\n"; if (val_try + temp*log(gRandom->Rndm()) < val_ref_therm) { //further is better, replace for (size_t j = 0; j < D; j++) { simplex[i_worst][j] = try_pt[j]; } val[i_worst] = val_try; //std::cout << "expanded" << std::endl; } else { //std::cout << "reflected (best)" << std::endl; } (*iter)--; } else { // reflection didn't work so well, try contracting const double val_con = replace_project(centroid,dworst,rho,simplex[i_worst]); val[i_worst] = val_con; //std::cout << "\tCon: " << val_con << "\n"; if (val_con + temp*log(gRandom->Rndm()) >= val_worst) { // contracting didn't replace worst // we're near the minimum, so shrink towards best for (size_t i = 0; i <= D; i++) { if (i == i_best) continue; for (size_t j = 0; j < D; j++) { simplex[i][j] = (1.0 - sigma)*simplex[i_best][j] + sigma*simplex[i][j]; } val[i] = (*funk)(simplex[i]); //std::cout << "\tShr: " << val[i] << "\n"; } //std::cout << "shrink" << std::endl; } else { //std::cout << "contracted" << std::endl; } (*iter)--; } } } }; } //namespace RAT #endif <commit_msg>Style changes.<commit_after>#ifndef __RAT_SimulatedAnnealing__ #define __RAT_SimulatedAnnealing__ #include <iostream> #include <vector> #include <cmath> #include <cfloat> #include <TRandom.h> namespace RAT { class Minimizable { public: virtual double operator()(double *args) = 0; }; template <int D> class SimulatedAnnealing { protected: double temp; Minimizable *funk; double simplex[D+1][D], val[D+1]; double global_best_pt[D], global_best_val; public: SimulatedAnnealing(Minimizable *funk_) : funk(funk_) { } ~SimulatedAnnealing() { } void SetSimplexPoint(size_t pt, std::vector<double> &point) { for (size_t j = 0; j < D; j++) { simplex[pt][j] = point[j]; } val[pt] = (*funk)(simplex[pt]); } void Anneal(double temp0, size_t nAnneal, size_t nEval, double alpha) { global_best_val = DBL_MAX; for (size_t cycle = 0; cycle < nAnneal; cycle++) { temp = temp0*pow(1-(double)cycle/nAnneal,alpha); int iter = nEval; amoeba(&iter); } } void GetBestPoint(std::vector<double> &point) { for (size_t j = 0; j < D; j++) { point[j] = global_best_pt[j]; } } protected: inline double replace_project(const double (&offset)[D], const double (&by)[D], const double factor, double (&into)[D]) { for (size_t j = 0; j < D; j++) { into[j] = offset[j] + factor*by[j]; } double val_try = (*funk)(into); if (val_try < global_best_val) { global_best_val = val_try; for (size_t j = 0; j < D; j++) { global_best_pt[j] = into[j]; } } return val_try; } void amoeba(int *iter) { //best, worst, and next worst points size_t i_best, i_worst, i_nextworst; double val_best, val_worst, val_nextworst; const double alpha = 1.0; const double gamma = 2.0; const double rho =-0.5; const double sigma = 0.5; double centroid[D]; //centroid of all but worst double dworst[D]; //vector from worst to centroid double try_pt[D]; //temporary vector for test point //std::cout << "*******************************\n"; for ( ; *iter > 0; ) { //find best, worst, nextworst (can optomize a lot of this later) i_best = i_worst = i_nextworst = -1; val_best = DBL_MAX, val_worst = val_nextworst = -DBL_MAX; for (size_t i = 0; i <= D; i++) { const double val_thermal = val[i] - temp*log(gRandom->Rndm()); //std::cout << val[i] << ' '; if (val_thermal < val_best) { i_best = i; val_best = val_thermal; } if (val_thermal > val_worst) { i_nextworst = i_worst; val_nextworst = val_worst; i_worst = i; val_worst = val_thermal; } else if (val_thermal > val_nextworst) { i_nextworst = i; val_nextworst = val_thermal; } } //std::cout << "~ " << i_best << '/' << i_nextworst << '/' << i_worst << " & "; //std::cout << val_best << '/' << val_nextworst << '/' << val_worst << "\n"; //update centroid, dworst for (size_t j = 0; j < D; j++) { centroid[j] = 0.0; for (size_t i = 0; i <= D; i++) { if (i == i_worst) continue; centroid[j] += simplex[i][j]; } centroid[j] /= D; dworst[j] = centroid[j] - simplex[i_worst][j]; } //std::cout << "+++++++++++\n"; //definitely replacing the worst point, try with reflecting val[i_worst] = replace_project(centroid,dworst,alpha,simplex[i_worst]); const double val_ref_therm = val[i_worst] + temp*log(gRandom->Rndm()); //std::cout << "\tRef: " << val_ref_therm << "\n"; (*iter)--; if (val_ref_therm < val_nextworst && val_ref_therm >= val_best) { // reflected point was better than the two worst and replaced // the worst point, so continue //std::cout << "reflected (okay)" << std::endl; continue; } else if (val_ref_therm < val_best) { // reflecting was really good, try further const double val_try = replace_project(centroid,dworst,gamma,try_pt) ; //std::cout << "\tExp: " << val_try << "\n"; if (val_try + temp*log(gRandom->Rndm()) < val_ref_therm) { //further is better, replace for (size_t j = 0; j < D; j++) { simplex[i_worst][j] = try_pt[j]; } val[i_worst] = val_try; //std::cout << "expanded" << std::endl; } else { //std::cout << "reflected (best)" << std::endl; } (*iter)--; } else { // reflection didn't work so well, try contracting const double val_con = replace_project(centroid,dworst,rho,simplex[i_worst]); val[i_worst] = val_con; //std::cout << "\tCon: " << val_con << "\n"; if (val_con + temp*log(gRandom->Rndm()) >= val_worst) { // contracting didn't replace worst // we're near the minimum, so shrink towards best for (size_t i = 0; i <= D; i++) { if (i == i_best) continue; for (size_t j = 0; j < D; j++) { simplex[i][j] = (1.0 - sigma)*simplex[i_best][j] + sigma*simplex[i][j]; } val[i] = (*funk)(simplex[i]); //std::cout << "\tShr: " << val[i] << "\n"; } //std::cout << "shrink" << std::endl; } else { //std::cout << "contracted" << std::endl; } (*iter)--; } } } }; } //namespace RAT #endif <|endoftext|>
<commit_before>#pragma once #include <common.hpp> #include <complex> #include <algorithm> // for std::min, max namespace rack { /** Supplemental `<cmath>` functions and types */ namespace math { //////////////////// // basic integer functions //////////////////// /** Returns true if `x` is odd. */ inline bool isEven(int x) { return x % 2 == 0; } /** Returns true if `x` is odd. */ inline bool isOdd(int x) { return x % 2 != 0; } /** Limits `x` between `a` and `b`. If `b < a`, returns a. */ inline int clamp(int x, int a, int b) { return std::max(std::min(x, b), a); } /** Limits `x` between `a` and `b`. If `b < a`, switches the two values. */ inline int clampSafe(int x, int a, int b) { return (a <= b) ? clamp(x, a, b) : clamp(x, b, a); } /** Euclidean modulus. Always returns `0 <= mod < b`. `b` must be positive. See https://en.wikipedia.org/wiki/Euclidean_division */ inline int eucMod(int a, int b) { int mod = a % b; if (mod < 0) { mod += b; } return mod; } /** Euclidean division. `b` must be positive. */ inline int eucDiv(int a, int b) { int div = a / b; int mod = a % b; if (mod < 0) { div -= 1; } return div; } inline void eucDivMod(int a, int b, int* div, int* mod) { *div = a / b; *mod = a % b; if (*mod < 0) { *div -= 1; *mod += b; } } /** Returns `floor(log_2(n))`, or 0 if `n == 1`. */ inline int log2(int n) { int i = 0; while (n >>= 1) { i++; } return i; } /** Returns whether `n` is a power of 2. */ inline bool isPow2(int n) { return n > 0 && (n & (n - 1)) == 0; } //////////////////// // basic float functions //////////////////// /** Limits `x` between `a` and `b`. If `b < a`, returns a. */ inline float clamp(float x, float a, float b) { return std::fmax(std::fmin(x, b), a); } /** Limits `x` between `a` and `b`. If `b < a`, switches the two values. */ inline float clampSafe(float x, float a, float b) { return (a <= b) ? clamp(x, a, b) : clamp(x, b, a); } /** Returns 1 for positive numbers, -1 for negative numbers, and 0 for zero. See https://en.wikipedia.org/wiki/Sign_function. */ inline float sgn(float x) { return x > 0.f ? 1.f : (x < 0.f ? -1.f : 0.f); } /** Converts -0.f to 0.f. Leaves all other values unchanged. */ inline float normalizeZero(float x) { return x + 0.f; } /** Euclidean modulus. Always returns `0 <= mod < b`. See https://en.wikipedia.org/wiki/Euclidean_division. */ inline float eucMod(float a, float b) { float mod = std::fmod(a, b); if (mod < 0.f) { mod += b; } return mod; } /** Returns whether `a` is within epsilon distance from `b`. */ inline bool isNear(float a, float b, float epsilon = 1e-6f) { return std::fabs(a - b) <= epsilon; } /** If the magnitude of `x` if less than epsilon, return 0. */ inline float chop(float x, float epsilon = 1e-6f) { return std::fabs(x) <= epsilon ? 0.f : x; } inline float rescale(float x, float xMin, float xMax, float yMin, float yMax) { return yMin + (x - xMin) / (xMax - xMin) * (yMax - yMin); } inline float crossfade(float a, float b, float p) { return a + (b - a) * p; } /** Linearly interpolates an array `p` with index `x`. Assumes that the array at `p` is of length at least `floor(x) + 1`. */ inline float interpolateLinear(const float* p, float x) { int xi = x; float xf = x - xi; return crossfade(p[xi], p[xi + 1], xf); } /** Complex multiplication `c = a * b`. Arguments may be the same pointers. Example: cmultf(ar, ai, br, bi, &ar, &ai); */ inline void complexMult(float ar, float ai, float br, float bi, float* cr, float* ci) { *cr = ar * br - ai * bi; *ci = ar * bi + ai * br; } //////////////////// // 2D vector and rectangle //////////////////// struct Rect; struct Vec { float x = 0.f; float y = 0.f; Vec() {} Vec(float x, float y) : x(x), y(y) {} /** Negates the vector. Equivalent to a reflection across the `y = -x` line. */ Vec neg() const { return Vec(-x, -y); } Vec plus(Vec b) const { return Vec(x + b.x, y + b.y); } Vec minus(Vec b) const { return Vec(x - b.x, y - b.y); } Vec mult(float s) const { return Vec(x * s, y * s); } Vec mult(Vec b) const { return Vec(x * b.x, y * b.y); } Vec div(float s) const { return Vec(x / s, y / s); } Vec div(Vec b) const { return Vec(x / b.x, y / b.y); } float dot(Vec b) const { return x * b.x + y * b.y; } float arg() const { return std::atan2(y, x); } float norm() const { return std::hypot(x, y); } Vec normalize() const { return div(norm()); } float square() const { return x * x + y * y; } /** Rotates counterclockwise in radians. */ Vec rotate(float angle) { float sin = std::sin(angle); float cos = std::cos(angle); return Vec(x * cos - y * sin, x * sin + y * cos); } /** Swaps the coordinates. Equivalent to a reflection across the `y = x` line. */ Vec flip() const { return Vec(y, x); } Vec min(Vec b) const { return Vec(std::fmin(x, b.x), std::fmin(y, b.y)); } Vec max(Vec b) const { return Vec(std::fmax(x, b.x), std::fmax(y, b.y)); } Vec abs() const { return Vec(std::fabs(x), std::fabs(y)); } Vec round() const { return Vec(std::round(x), std::round(y)); } Vec floor() const { return Vec(std::floor(x), std::floor(y)); } Vec ceil() const { return Vec(std::ceil(x), std::ceil(y)); } bool isEqual(Vec b) const { return x == b.x && y == b.y; } bool isZero() const { return x == 0.f && y == 0.f; } bool isFinite() const { return std::isfinite(x) && std::isfinite(y); } Vec clamp(Rect bound) const; Vec clampSafe(Rect bound) const; Vec crossfade(Vec b, float p) { return this->plus(b.minus(*this).mult(p)); } }; struct Rect { Vec pos; Vec size; Rect() {} Rect(Vec pos, Vec size) : pos(pos), size(size) {} Rect(float posX, float posY, float sizeX, float sizeY) : pos(math::Vec(posX, posY)), size(math::Vec(sizeX, sizeY)) {} /** Constructs a Rect from the upper-left position `a` and lower-right pos `b`. */ static Rect fromMinMax(Vec a, Vec b) { return Rect(a, b.minus(a)); } /** Returns whether this Rect contains an entire point, inclusive on the top/left, non-inclusive on the bottom/right. */ bool isContaining(Vec v) const { return pos.x <= v.x && v.x < pos.x + size.x && pos.y <= v.y && v.y < pos.y + size.y; } /** Returns whether this Rect contains an entire Rect. */ bool isContaining(Rect r) const { return pos.x <= r.pos.x && r.pos.x + r.size.x <= pos.x + size.x && pos.y <= r.pos.y && r.pos.y + r.size.y <= pos.y + size.y; } /** Returns whether this Rect overlaps with another Rect. */ bool isIntersecting(Rect r) const { return (pos.x + size.x > r.pos.x && r.pos.x + r.size.x > pos.x) && (pos.y + size.y > r.pos.y && r.pos.y + r.size.y > pos.y); } bool isEqual(Rect r) const { return pos.isEqual(r.pos) && size.isEqual(r.size); } float getRight() const { return pos.x + size.x; } float getBottom() const { return pos.y + size.y; } Vec getCenter() const { return pos.plus(size.mult(0.5f)); } Vec getTopLeft() const { return pos; } Vec getTopRight() const { return pos.plus(Vec(size.x, 0.f)); } Vec getBottomLeft() const { return pos.plus(Vec(0.f, size.y)); } Vec getBottomRight() const { return pos.plus(size); } /** Clamps the edges of the rectangle to fit within a bound. */ Rect clamp(Rect bound) const { Rect r; r.pos.x = math::clampSafe(pos.x, bound.pos.x, bound.pos.x + bound.size.x); r.pos.y = math::clampSafe(pos.y, bound.pos.y, bound.pos.y + bound.size.y); r.size.x = math::clamp(pos.x + size.x, bound.pos.x, bound.pos.x + bound.size.x) - r.pos.x; r.size.y = math::clamp(pos.y + size.y, bound.pos.y, bound.pos.y + bound.size.y) - r.pos.y; return r; } /** Nudges the position to fix inside a bounding box. */ Rect nudge(Rect bound) const { Rect r; r.size = size; r.pos.x = math::clampSafe(pos.x, bound.pos.x, bound.pos.x + bound.size.x - size.x); r.pos.y = math::clampSafe(pos.y, bound.pos.y, bound.pos.y + bound.size.y - size.y); return r; } /** Returns the bounding box of the union of `this` and `b`. */ Rect expand(Rect b) const { Rect r; r.pos.x = std::fmin(pos.x, b.pos.x); r.pos.y = std::fmin(pos.y, b.pos.y); r.size.x = std::fmax(pos.x + size.x, b.pos.x + b.size.x) - r.pos.x; r.size.y = std::fmax(pos.y + size.y, b.pos.y + b.size.y) - r.pos.y; return r; } /** Returns the intersection of `this` and `b`. */ Rect intersect(Rect b) const { Rect r; r.pos.x = std::fmax(pos.x, b.pos.x); r.pos.y = std::fmax(pos.y, b.pos.y); r.size.x = std::fmin(pos.x + size.x, b.pos.x + b.size.x) - r.pos.x; r.size.y = std::fmin(pos.y + size.y, b.pos.y + b.size.y) - r.pos.y; return r; } /** Returns a Rect with its position set to zero. */ Rect zeroPos() const { return Rect(Vec(), size); } /** Expands each corner. Use a negative delta to shrink. */ Rect grow(Vec delta) const { Rect r; r.pos = pos.minus(delta); r.size = size.plus(delta.mult(2.f)); return r; } DEPRECATED bool contains(Vec v) const { return isContaining(v); } DEPRECATED bool contains(Rect r) const { return isContaining(r); } DEPRECATED bool intersects(Rect r) const { return isIntersecting(r); } }; inline Vec Vec::clamp(Rect bound) const { return Vec( math::clamp(x, bound.pos.x, bound.pos.x + bound.size.x), math::clamp(y, bound.pos.y, bound.pos.y + bound.size.y)); } inline Vec Vec::clampSafe(Rect bound) const { return Vec( math::clampSafe(x, bound.pos.x, bound.pos.x + bound.size.x), math::clampSafe(y, bound.pos.y, bound.pos.y + bound.size.y)); } /** Expands a Vec and Rect into a comma-separated list. Useful for print debugging. printf("(%f %f) (%f %f %f %f)", VEC_ARGS(v), RECT_ARGS(r)); Or passing the values to a C function. nvgRect(vg, RECT_ARGS(r)); */ #define VEC_ARGS(v) (v).x, (v).y #define RECT_ARGS(r) (r).pos.x, (r).pos.y, (r).size.x, (r).size.y } // namespace math } // namespace rack <commit_msg>Correct documentation for math::interpolateLinear.<commit_after>#pragma once #include <common.hpp> #include <complex> #include <algorithm> // for std::min, max namespace rack { /** Supplemental `<cmath>` functions and types */ namespace math { //////////////////// // basic integer functions //////////////////// /** Returns true if `x` is odd. */ inline bool isEven(int x) { return x % 2 == 0; } /** Returns true if `x` is odd. */ inline bool isOdd(int x) { return x % 2 != 0; } /** Limits `x` between `a` and `b`. If `b < a`, returns a. */ inline int clamp(int x, int a, int b) { return std::max(std::min(x, b), a); } /** Limits `x` between `a` and `b`. If `b < a`, switches the two values. */ inline int clampSafe(int x, int a, int b) { return (a <= b) ? clamp(x, a, b) : clamp(x, b, a); } /** Euclidean modulus. Always returns `0 <= mod < b`. `b` must be positive. See https://en.wikipedia.org/wiki/Euclidean_division */ inline int eucMod(int a, int b) { int mod = a % b; if (mod < 0) { mod += b; } return mod; } /** Euclidean division. `b` must be positive. */ inline int eucDiv(int a, int b) { int div = a / b; int mod = a % b; if (mod < 0) { div -= 1; } return div; } inline void eucDivMod(int a, int b, int* div, int* mod) { *div = a / b; *mod = a % b; if (*mod < 0) { *div -= 1; *mod += b; } } /** Returns `floor(log_2(n))`, or 0 if `n == 1`. */ inline int log2(int n) { int i = 0; while (n >>= 1) { i++; } return i; } /** Returns whether `n` is a power of 2. */ inline bool isPow2(int n) { return n > 0 && (n & (n - 1)) == 0; } //////////////////// // basic float functions //////////////////// /** Limits `x` between `a` and `b`. If `b < a`, returns a. */ inline float clamp(float x, float a, float b) { return std::fmax(std::fmin(x, b), a); } /** Limits `x` between `a` and `b`. If `b < a`, switches the two values. */ inline float clampSafe(float x, float a, float b) { return (a <= b) ? clamp(x, a, b) : clamp(x, b, a); } /** Returns 1 for positive numbers, -1 for negative numbers, and 0 for zero. See https://en.wikipedia.org/wiki/Sign_function. */ inline float sgn(float x) { return x > 0.f ? 1.f : (x < 0.f ? -1.f : 0.f); } /** Converts -0.f to 0.f. Leaves all other values unchanged. */ inline float normalizeZero(float x) { return x + 0.f; } /** Euclidean modulus. Always returns `0 <= mod < b`. See https://en.wikipedia.org/wiki/Euclidean_division. */ inline float eucMod(float a, float b) { float mod = std::fmod(a, b); if (mod < 0.f) { mod += b; } return mod; } /** Returns whether `a` is within epsilon distance from `b`. */ inline bool isNear(float a, float b, float epsilon = 1e-6f) { return std::fabs(a - b) <= epsilon; } /** If the magnitude of `x` if less than epsilon, return 0. */ inline float chop(float x, float epsilon = 1e-6f) { return std::fabs(x) <= epsilon ? 0.f : x; } inline float rescale(float x, float xMin, float xMax, float yMin, float yMax) { return yMin + (x - xMin) / (xMax - xMin) * (yMax - yMin); } inline float crossfade(float a, float b, float p) { return a + (b - a) * p; } /** Linearly interpolates an array `p` with index `x`. The array at `p` must be at least length `floor(x) + 2`. */ inline float interpolateLinear(const float* p, float x) { int xi = x; float xf = x - xi; return crossfade(p[xi], p[xi + 1], xf); } /** Complex multiplication `c = a * b`. Arguments may be the same pointers. Example: cmultf(ar, ai, br, bi, &ar, &ai); */ inline void complexMult(float ar, float ai, float br, float bi, float* cr, float* ci) { *cr = ar * br - ai * bi; *ci = ar * bi + ai * br; } //////////////////// // 2D vector and rectangle //////////////////// struct Rect; struct Vec { float x = 0.f; float y = 0.f; Vec() {} Vec(float x, float y) : x(x), y(y) {} /** Negates the vector. Equivalent to a reflection across the `y = -x` line. */ Vec neg() const { return Vec(-x, -y); } Vec plus(Vec b) const { return Vec(x + b.x, y + b.y); } Vec minus(Vec b) const { return Vec(x - b.x, y - b.y); } Vec mult(float s) const { return Vec(x * s, y * s); } Vec mult(Vec b) const { return Vec(x * b.x, y * b.y); } Vec div(float s) const { return Vec(x / s, y / s); } Vec div(Vec b) const { return Vec(x / b.x, y / b.y); } float dot(Vec b) const { return x * b.x + y * b.y; } float arg() const { return std::atan2(y, x); } float norm() const { return std::hypot(x, y); } Vec normalize() const { return div(norm()); } float square() const { return x * x + y * y; } /** Rotates counterclockwise in radians. */ Vec rotate(float angle) { float sin = std::sin(angle); float cos = std::cos(angle); return Vec(x * cos - y * sin, x * sin + y * cos); } /** Swaps the coordinates. Equivalent to a reflection across the `y = x` line. */ Vec flip() const { return Vec(y, x); } Vec min(Vec b) const { return Vec(std::fmin(x, b.x), std::fmin(y, b.y)); } Vec max(Vec b) const { return Vec(std::fmax(x, b.x), std::fmax(y, b.y)); } Vec abs() const { return Vec(std::fabs(x), std::fabs(y)); } Vec round() const { return Vec(std::round(x), std::round(y)); } Vec floor() const { return Vec(std::floor(x), std::floor(y)); } Vec ceil() const { return Vec(std::ceil(x), std::ceil(y)); } bool isEqual(Vec b) const { return x == b.x && y == b.y; } bool isZero() const { return x == 0.f && y == 0.f; } bool isFinite() const { return std::isfinite(x) && std::isfinite(y); } Vec clamp(Rect bound) const; Vec clampSafe(Rect bound) const; Vec crossfade(Vec b, float p) { return this->plus(b.minus(*this).mult(p)); } }; struct Rect { Vec pos; Vec size; Rect() {} Rect(Vec pos, Vec size) : pos(pos), size(size) {} Rect(float posX, float posY, float sizeX, float sizeY) : pos(math::Vec(posX, posY)), size(math::Vec(sizeX, sizeY)) {} /** Constructs a Rect from the upper-left position `a` and lower-right pos `b`. */ static Rect fromMinMax(Vec a, Vec b) { return Rect(a, b.minus(a)); } /** Returns whether this Rect contains an entire point, inclusive on the top/left, non-inclusive on the bottom/right. */ bool isContaining(Vec v) const { return pos.x <= v.x && v.x < pos.x + size.x && pos.y <= v.y && v.y < pos.y + size.y; } /** Returns whether this Rect contains an entire Rect. */ bool isContaining(Rect r) const { return pos.x <= r.pos.x && r.pos.x + r.size.x <= pos.x + size.x && pos.y <= r.pos.y && r.pos.y + r.size.y <= pos.y + size.y; } /** Returns whether this Rect overlaps with another Rect. */ bool isIntersecting(Rect r) const { return (pos.x + size.x > r.pos.x && r.pos.x + r.size.x > pos.x) && (pos.y + size.y > r.pos.y && r.pos.y + r.size.y > pos.y); } bool isEqual(Rect r) const { return pos.isEqual(r.pos) && size.isEqual(r.size); } float getRight() const { return pos.x + size.x; } float getBottom() const { return pos.y + size.y; } Vec getCenter() const { return pos.plus(size.mult(0.5f)); } Vec getTopLeft() const { return pos; } Vec getTopRight() const { return pos.plus(Vec(size.x, 0.f)); } Vec getBottomLeft() const { return pos.plus(Vec(0.f, size.y)); } Vec getBottomRight() const { return pos.plus(size); } /** Clamps the edges of the rectangle to fit within a bound. */ Rect clamp(Rect bound) const { Rect r; r.pos.x = math::clampSafe(pos.x, bound.pos.x, bound.pos.x + bound.size.x); r.pos.y = math::clampSafe(pos.y, bound.pos.y, bound.pos.y + bound.size.y); r.size.x = math::clamp(pos.x + size.x, bound.pos.x, bound.pos.x + bound.size.x) - r.pos.x; r.size.y = math::clamp(pos.y + size.y, bound.pos.y, bound.pos.y + bound.size.y) - r.pos.y; return r; } /** Nudges the position to fix inside a bounding box. */ Rect nudge(Rect bound) const { Rect r; r.size = size; r.pos.x = math::clampSafe(pos.x, bound.pos.x, bound.pos.x + bound.size.x - size.x); r.pos.y = math::clampSafe(pos.y, bound.pos.y, bound.pos.y + bound.size.y - size.y); return r; } /** Returns the bounding box of the union of `this` and `b`. */ Rect expand(Rect b) const { Rect r; r.pos.x = std::fmin(pos.x, b.pos.x); r.pos.y = std::fmin(pos.y, b.pos.y); r.size.x = std::fmax(pos.x + size.x, b.pos.x + b.size.x) - r.pos.x; r.size.y = std::fmax(pos.y + size.y, b.pos.y + b.size.y) - r.pos.y; return r; } /** Returns the intersection of `this` and `b`. */ Rect intersect(Rect b) const { Rect r; r.pos.x = std::fmax(pos.x, b.pos.x); r.pos.y = std::fmax(pos.y, b.pos.y); r.size.x = std::fmin(pos.x + size.x, b.pos.x + b.size.x) - r.pos.x; r.size.y = std::fmin(pos.y + size.y, b.pos.y + b.size.y) - r.pos.y; return r; } /** Returns a Rect with its position set to zero. */ Rect zeroPos() const { return Rect(Vec(), size); } /** Expands each corner. Use a negative delta to shrink. */ Rect grow(Vec delta) const { Rect r; r.pos = pos.minus(delta); r.size = size.plus(delta.mult(2.f)); return r; } DEPRECATED bool contains(Vec v) const { return isContaining(v); } DEPRECATED bool contains(Rect r) const { return isContaining(r); } DEPRECATED bool intersects(Rect r) const { return isIntersecting(r); } }; inline Vec Vec::clamp(Rect bound) const { return Vec( math::clamp(x, bound.pos.x, bound.pos.x + bound.size.x), math::clamp(y, bound.pos.y, bound.pos.y + bound.size.y)); } inline Vec Vec::clampSafe(Rect bound) const { return Vec( math::clampSafe(x, bound.pos.x, bound.pos.x + bound.size.x), math::clampSafe(y, bound.pos.y, bound.pos.y + bound.size.y)); } /** Expands a Vec and Rect into a comma-separated list. Useful for print debugging. printf("(%f %f) (%f %f %f %f)", VEC_ARGS(v), RECT_ARGS(r)); Or passing the values to a C function. nvgRect(vg, RECT_ARGS(r)); */ #define VEC_ARGS(v) (v).x, (v).y #define RECT_ARGS(r) (r).pos.x, (r).pos.y, (r).size.x, (r).size.y } // namespace math } // namespace rack <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2017 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes // Local Includes #include "libmesh/elem.h" #include "libmesh/libmesh_logging.h" #include "libmesh/mesh_base.h" #include "libmesh/mesh_tools.h" #include "libmesh/point_locator_tree.h" #include "libmesh/tree.h" namespace libMesh { //------------------------------------------------------------------ // PointLocator methods PointLocatorTree::PointLocatorTree (const MeshBase & mesh, const PointLocatorBase * master) : PointLocatorBase (mesh,master), _tree (libmesh_nullptr), _element (libmesh_nullptr), _out_of_mesh_mode(false), _target_bin_size (200), _build_type(Trees::NODES) { this->init(_build_type); } PointLocatorTree::PointLocatorTree (const MeshBase & mesh, const Trees::BuildType build_type, const PointLocatorBase * master) : PointLocatorBase (mesh,master), _tree (libmesh_nullptr), _element (libmesh_nullptr), _out_of_mesh_mode(false), _target_bin_size (200), _build_type(build_type) { this->init(_build_type); } PointLocatorTree::~PointLocatorTree () { this->clear (); } void PointLocatorTree::clear () { // only delete the tree when we are the master if (this->_tree != libmesh_nullptr) { if (this->_master == libmesh_nullptr) // we own the tree delete this->_tree; else // someone else owns and therefore deletes the tree this->_tree = libmesh_nullptr; // make sure operator () throws an assertion this->_initialized = false; } } void PointLocatorTree::init() { this->init(_build_type); } void PointLocatorTree::init (Trees::BuildType build_type) { libmesh_assert (!this->_tree); if (this->_initialized) { // Warn that we are already initialized libMesh::err << "Warning: PointLocatorTree already initialized! Will ignore this call..." << std::endl; // Further warn if we try to init() again with a different build_type if (_build_type != build_type) { libMesh::err << "Warning: PointLocatorTree is using build_type = " << _build_type << ".\n" << "Your requested build_type, " << build_type << " will not be used!" << std::endl; } } else { // Let the requested build_type override the _build_type we were // constructed with. This is no big deal since we have not been // initialized before. _build_type = build_type; if (this->_master == libmesh_nullptr) { LOG_SCOPE("init(no master)", "PointLocatorTree"); if (this->_mesh.mesh_dimension() == 3) _tree = new Trees::OctTree (this->_mesh, get_target_bin_size(), _build_type); else { // A 1D/2D mesh in 3D space needs special consideration. // If the mesh is planar XY, we want to build a QuadTree // to search efficiently. If the mesh is truly a manifold, // then we need an octree #if LIBMESH_DIM > 2 bool is_planar_xy = false; // Build the bounding box for the mesh. If the delta-z bound is // negligibly small then we can use a quadtree. { MeshTools::BoundingBox bbox = MeshTools::bounding_box(this->_mesh); const Real Dx = bbox.second(0) - bbox.first(0), Dz = bbox.second(2) - bbox.first(2); if (std::abs(Dz/(Dx + 1.e-20)) < 1e-10) is_planar_xy = true; } if (!is_planar_xy) _tree = new Trees::OctTree (this->_mesh, get_target_bin_size(), _build_type); else #endif #if LIBMESH_DIM > 1 _tree = new Trees::QuadTree (this->_mesh, get_target_bin_size(), _build_type); #else _tree = new Trees::BinaryTree (this->_mesh, get_target_bin_size(), _build_type); #endif } } else { // We are _not_ the master. Let our Tree point to // the master's tree. But for this we first transform // the master in a state for which we are friends. // And make sure the master @e has a tree! const PointLocatorTree * my_master = cast_ptr<const PointLocatorTree *>(this->_master); if (my_master->initialized()) this->_tree = my_master->_tree; else libmesh_error_msg("ERROR: Initialize master first, then servants!"); } // Not all PointLocators may own a tree, but all of them // use their own element pointer. Let the element pointer // be unique for every interpolator. // Suppose the interpolators are used concurrently // at different locations in the mesh, then it makes quite // sense to have unique start elements. this->_element = libmesh_nullptr; } // ready for take-off this->_initialized = true; } const Elem * PointLocatorTree::operator() (const Point & p, const std::set<subdomain_id_type> * allowed_subdomains) const { libmesh_assert (this->_initialized); LOG_SCOPE("operator()", "PointLocatorTree"); // If we're provided with an allowed_subdomains list and have a cached element, make sure it complies if (allowed_subdomains && this->_element && !allowed_subdomains->count(this->_element->subdomain_id())) this->_element = libmesh_nullptr; // First check the element from last time before asking the tree if (this->_element==libmesh_nullptr || !(this->_element->contains_point(p))) { // ask the tree this->_element = this->_tree->find_element (p,allowed_subdomains); if (this->_element == libmesh_nullptr) { // If we haven't found the element, we may want to do a linear // search using a tolerance. if( _use_close_to_point_tol ) { if(_verbose) { libMesh::out << "Performing linear search using close-to-point tolerance " << _close_to_point_tol << std::endl; } this->_element = this->perform_linear_search(p, allowed_subdomains, /*use_close_to_point*/ true, _close_to_point_tol); return this->_element; } // No element seems to contain this point. Thus: // 1.) If _out_of_mesh_mode == true, we can just return NULL // without searching further. // 2.) If _out_of_mesh_mode == false, we perform a linear // search over all active (possibly local) elements. // The idea here is that, in the case of curved elements, // the bounding box computed in \p TreeNode::insert(const // Elem *) might be slightly inaccurate and therefore we may // have generated a false negative. // // Note that we skip the _use_close_to_point_tol case below, because // we already did a linear search in that case above. if (_out_of_mesh_mode == false && !_use_close_to_point_tol) { this->_element = this->perform_linear_search(p, allowed_subdomains, /*use_close_to_point*/ false); return this->_element; } } } // If we found an element, it should be active libmesh_assert (!this->_element || this->_element->active()); // If we found an element and have a restriction list, they better match libmesh_assert (!this->_element || !allowed_subdomains || allowed_subdomains->count(this->_element->subdomain_id())); // return the element return this->_element; } void PointLocatorTree::operator() (const Point & p, std::set<const Elem *> & candidate_elements, const std::set<subdomain_id_type> * allowed_subdomains) const { libmesh_assert (this->_initialized); LOG_SCOPE("operator() - Version 2", "PointLocatorTree"); // forward call to perform_linear_search candidate_elements = this->perform_fuzzy_linear_search(p, allowed_subdomains, _close_to_point_tol); } const Elem * PointLocatorTree::perform_linear_search(const Point & p, const std::set<subdomain_id_type> * allowed_subdomains, bool use_close_to_point, Real close_to_point_tolerance) const { LOG_SCOPE("perform_linear_search", "PointLocatorTree"); // The type of iterator depends on the Trees::BuildType // used for this PointLocator. If it's // TREE_LOCAL_ELEMENTS, we only want to double check // local elements during this linear search. MeshBase::const_element_iterator pos = this->_build_type == Trees::LOCAL_ELEMENTS ? this->_mesh.active_local_elements_begin() : this->_mesh.active_elements_begin(); const MeshBase::const_element_iterator end_pos = this->_build_type == Trees::LOCAL_ELEMENTS ? this->_mesh.active_local_elements_end() : this->_mesh.active_elements_end(); for ( ; pos != end_pos; ++pos) { if (!allowed_subdomains || allowed_subdomains->count((*pos)->subdomain_id())) { if(!use_close_to_point) { if ((*pos)->contains_point(p)) return (*pos); } else { if ((*pos)->close_to_point(p, close_to_point_tolerance)) return (*pos); } } } return libmesh_nullptr; } std::set<const Elem *> PointLocatorTree::perform_fuzzy_linear_search(const Point & p, const std::set<subdomain_id_type> * allowed_subdomains, Real close_to_point_tolerance) const { LOG_SCOPE("perform_fuzzy_linear_search", "PointLocatorTree"); std::set<const Elem *> candidate_elements; // The type of iterator depends on the Trees::BuildType // used for this PointLocator. If it's // TREE_LOCAL_ELEMENTS, we only want to double check // local elements during this linear search. MeshBase::const_element_iterator pos = this->_build_type == Trees::LOCAL_ELEMENTS ? this->_mesh.active_local_elements_begin() : this->_mesh.active_elements_begin(); const MeshBase::const_element_iterator end_pos = this->_build_type == Trees::LOCAL_ELEMENTS ? this->_mesh.active_local_elements_end() : this->_mesh.active_elements_end(); for ( ; pos != end_pos; ++pos) { if ((!allowed_subdomains || allowed_subdomains->count((*pos)->subdomain_id())) && (*pos)->close_to_point(p, close_to_point_tolerance)) candidate_elements.insert(*pos); } return candidate_elements; } void PointLocatorTree::enable_out_of_mesh_mode () { // Out-of-mesh mode should now work properly even on meshes with // non-affine elements. _out_of_mesh_mode = true; } void PointLocatorTree::disable_out_of_mesh_mode () { _out_of_mesh_mode = false; } void PointLocatorTree::set_target_bin_size (unsigned int target_bin_size) { _target_bin_size = target_bin_size; } unsigned int PointLocatorTree::get_target_bin_size () const { return _target_bin_size; } } // namespace libMesh <commit_msg>Don't bother with linear searches<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2017 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes // Local Includes #include "libmesh/elem.h" #include "libmesh/libmesh_logging.h" #include "libmesh/mesh_base.h" #include "libmesh/mesh_tools.h" #include "libmesh/point_locator_tree.h" #include "libmesh/tree.h" namespace libMesh { //------------------------------------------------------------------ // PointLocator methods PointLocatorTree::PointLocatorTree (const MeshBase & mesh, const PointLocatorBase * master) : PointLocatorBase (mesh,master), _tree (libmesh_nullptr), _element (libmesh_nullptr), _out_of_mesh_mode(false), _target_bin_size (200), _build_type(Trees::NODES) { this->init(_build_type); } PointLocatorTree::PointLocatorTree (const MeshBase & mesh, const Trees::BuildType build_type, const PointLocatorBase * master) : PointLocatorBase (mesh,master), _tree (libmesh_nullptr), _element (libmesh_nullptr), _out_of_mesh_mode(false), _target_bin_size (200), _build_type(build_type) { this->init(_build_type); } PointLocatorTree::~PointLocatorTree () { this->clear (); } void PointLocatorTree::clear () { // only delete the tree when we are the master if (this->_tree != libmesh_nullptr) { if (this->_master == libmesh_nullptr) // we own the tree delete this->_tree; else // someone else owns and therefore deletes the tree this->_tree = libmesh_nullptr; // make sure operator () throws an assertion this->_initialized = false; } } void PointLocatorTree::init() { this->init(_build_type); } void PointLocatorTree::init (Trees::BuildType build_type) { libmesh_assert (!this->_tree); if (this->_initialized) { // Warn that we are already initialized libMesh::err << "Warning: PointLocatorTree already initialized! Will ignore this call..." << std::endl; // Further warn if we try to init() again with a different build_type if (_build_type != build_type) { libMesh::err << "Warning: PointLocatorTree is using build_type = " << _build_type << ".\n" << "Your requested build_type, " << build_type << " will not be used!" << std::endl; } } else { // Let the requested build_type override the _build_type we were // constructed with. This is no big deal since we have not been // initialized before. _build_type = build_type; if (this->_master == libmesh_nullptr) { LOG_SCOPE("init(no master)", "PointLocatorTree"); if (this->_mesh.mesh_dimension() == 3) _tree = new Trees::OctTree (this->_mesh, get_target_bin_size(), _build_type); else { // A 1D/2D mesh in 3D space needs special consideration. // If the mesh is planar XY, we want to build a QuadTree // to search efficiently. If the mesh is truly a manifold, // then we need an octree #if LIBMESH_DIM > 2 bool is_planar_xy = false; // Build the bounding box for the mesh. If the delta-z bound is // negligibly small then we can use a quadtree. { MeshTools::BoundingBox bbox = MeshTools::bounding_box(this->_mesh); const Real Dx = bbox.second(0) - bbox.first(0), Dz = bbox.second(2) - bbox.first(2); if (std::abs(Dz/(Dx + 1.e-20)) < 1e-10) is_planar_xy = true; } if (!is_planar_xy) _tree = new Trees::OctTree (this->_mesh, get_target_bin_size(), _build_type); else #endif #if LIBMESH_DIM > 1 _tree = new Trees::QuadTree (this->_mesh, get_target_bin_size(), _build_type); #else _tree = new Trees::BinaryTree (this->_mesh, get_target_bin_size(), _build_type); #endif } } else { // We are _not_ the master. Let our Tree point to // the master's tree. But for this we first transform // the master in a state for which we are friends. // And make sure the master @e has a tree! const PointLocatorTree * my_master = cast_ptr<const PointLocatorTree *>(this->_master); if (my_master->initialized()) this->_tree = my_master->_tree; else libmesh_error_msg("ERROR: Initialize master first, then servants!"); } // Not all PointLocators may own a tree, but all of them // use their own element pointer. Let the element pointer // be unique for every interpolator. // Suppose the interpolators are used concurrently // at different locations in the mesh, then it makes quite // sense to have unique start elements. this->_element = libmesh_nullptr; } // ready for take-off this->_initialized = true; } const Elem * PointLocatorTree::operator() (const Point & p, const std::set<subdomain_id_type> * allowed_subdomains) const { libmesh_assert (this->_initialized); LOG_SCOPE("operator()", "PointLocatorTree"); // If we're provided with an allowed_subdomains list and have a cached element, make sure it complies if (allowed_subdomains && this->_element && !allowed_subdomains->count(this->_element->subdomain_id())) this->_element = libmesh_nullptr; // First check the element from last time before asking the tree if (this->_element==libmesh_nullptr || !(this->_element->contains_point(p))) { // ask the tree this->_element = this->_tree->find_element (p,allowed_subdomains); if (this->_element == libmesh_nullptr) { // If we haven't found the element, we may want to do a linear // search using a tolerance. if( _use_close_to_point_tol ) { if(_verbose) { libMesh::out << "Performing linear search using close-to-point tolerance " << _close_to_point_tol << std::endl; } this->_element = this->perform_linear_search(p, allowed_subdomains, /*use_close_to_point*/ true, _close_to_point_tol); return this->_element; } // No element seems to contain this point. In theory, our // tree now correctly handles curved elements. In // out-of-mesh mode this is sometimes expected, and we can // just return NULL without searching further. Out of // out-of-mesh mode, something must have gone wrong. // We'll avoid making this assertion just yet, though, // because some users are leaving out_of_mesh_mode disabled // as a workaround for old PointLocatorTree behavior. // libmesh_assert_equal_to (_out_of_mesh_mode, true); return this->_element; } } // If we found an element, it should be active libmesh_assert (!this->_element || this->_element->active()); // If we found an element and have a restriction list, they better match libmesh_assert (!this->_element || !allowed_subdomains || allowed_subdomains->count(this->_element->subdomain_id())); // return the element return this->_element; } void PointLocatorTree::operator() (const Point & p, std::set<const Elem *> & candidate_elements, const std::set<subdomain_id_type> * allowed_subdomains) const { libmesh_assert (this->_initialized); LOG_SCOPE("operator() - Version 2", "PointLocatorTree"); // forward call to perform_linear_search candidate_elements = this->perform_fuzzy_linear_search(p, allowed_subdomains, _close_to_point_tol); } const Elem * PointLocatorTree::perform_linear_search(const Point & p, const std::set<subdomain_id_type> * allowed_subdomains, bool use_close_to_point, Real close_to_point_tolerance) const { LOG_SCOPE("perform_linear_search", "PointLocatorTree"); // The type of iterator depends on the Trees::BuildType // used for this PointLocator. If it's // TREE_LOCAL_ELEMENTS, we only want to double check // local elements during this linear search. MeshBase::const_element_iterator pos = this->_build_type == Trees::LOCAL_ELEMENTS ? this->_mesh.active_local_elements_begin() : this->_mesh.active_elements_begin(); const MeshBase::const_element_iterator end_pos = this->_build_type == Trees::LOCAL_ELEMENTS ? this->_mesh.active_local_elements_end() : this->_mesh.active_elements_end(); for ( ; pos != end_pos; ++pos) { if (!allowed_subdomains || allowed_subdomains->count((*pos)->subdomain_id())) { if(!use_close_to_point) { if ((*pos)->contains_point(p)) return (*pos); } else { if ((*pos)->close_to_point(p, close_to_point_tolerance)) return (*pos); } } } return libmesh_nullptr; } std::set<const Elem *> PointLocatorTree::perform_fuzzy_linear_search(const Point & p, const std::set<subdomain_id_type> * allowed_subdomains, Real close_to_point_tolerance) const { LOG_SCOPE("perform_fuzzy_linear_search", "PointLocatorTree"); std::set<const Elem *> candidate_elements; // The type of iterator depends on the Trees::BuildType // used for this PointLocator. If it's // TREE_LOCAL_ELEMENTS, we only want to double check // local elements during this linear search. MeshBase::const_element_iterator pos = this->_build_type == Trees::LOCAL_ELEMENTS ? this->_mesh.active_local_elements_begin() : this->_mesh.active_elements_begin(); const MeshBase::const_element_iterator end_pos = this->_build_type == Trees::LOCAL_ELEMENTS ? this->_mesh.active_local_elements_end() : this->_mesh.active_elements_end(); for ( ; pos != end_pos; ++pos) { if ((!allowed_subdomains || allowed_subdomains->count((*pos)->subdomain_id())) && (*pos)->close_to_point(p, close_to_point_tolerance)) candidate_elements.insert(*pos); } return candidate_elements; } void PointLocatorTree::enable_out_of_mesh_mode () { // Out-of-mesh mode should now work properly even on meshes with // non-affine elements. _out_of_mesh_mode = true; } void PointLocatorTree::disable_out_of_mesh_mode () { _out_of_mesh_mode = false; } void PointLocatorTree::set_target_bin_size (unsigned int target_bin_size) { _target_bin_size = target_bin_size; } unsigned int PointLocatorTree::get_target_bin_size () const { return _target_bin_size; } } // namespace libMesh <|endoftext|>
<commit_before>/*========================================================================= Copyright (c) Kitware Inc. All rights reserved. =========================================================================*/ // .SECTION Description // This program illustrates the use of the vtkHyperTreeGrid // data set and various filters acting upon hyper it. // It generates output files in VTK format. // // .SECTION Usage // // .SECTION Thanks // This program was written by Daniel Aguilera and Philippe Pebay // This work was supported by Commissariat a l'Energie Atomique (CEA/DIF) #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkPolyDataMapper.h> #include <vtkPolyData.h> #include <vtkActor.h> #include <vtkDataSetSurfaceFilter.h> #include <vtkUnstructuredGrid.h> #include <vtkShrinkFilter.h> #include <vtkProperty.h> #include <vtkUnstructuredGridWriter.h> #include <vtkInteractorStyleSwitch.h> #include "Mesh.h" #include "Cell.h" #include "Node.h" using namespace std; #define SHIFT_ARGS() for (int j=i;j<(argc-1);j++) argv[j] = argv[j+1]; argc--; i-- #define SHIFT_NARGS(n) for (int j=i;j<(argc-(n));j++) argv[j] = argv[j+(n)]; argc-=(n); i-- void usage () { cout << "Usage : amr [-level <int>] [-refine <int>] [-nx <int>] [-ny <int>] [-nz <int>] [-write <file>] [-shrink] [-help]" << endl; cout << " -depth : Number of refinement levels. Defaut = 3" << endl; cout << " -factor : Refinement branching factor. Defaut = 3" << endl; cout << " -n[xyz] : Number of grid points in each direction. Defaut = 5" << endl; cout << " -write : Output mesh in a VTK unstructured grid file. Defaut = no output" << endl; cout << " -shrink : Apply shrink filter before rendering geometry. Defaut = do not shrink" << endl; cout << " -help : Print available options" << endl; exit (0); } int main( int argc, char *argv[] ) { // Default values int nx = 5; int ny = 5; int nz = 5; int depth = 3; int factor = 3; bool shrink = false; string datafile = ""; double R = 0.0; for (int i = 1; i < argc; i++) { // Refinement depth if (strcmp (argv[i], "-depth") == 0) { if (i+1 < argc) {depth = atoi (argv[i+1]); SHIFT_NARGS(2);} else usage(); } // Branch factor else if (strcmp (argv[i], "-factor") == 0) { if (i+1 < argc) {factor = atoi (argv[i+1]); SHIFT_NARGS(2);} else usage(); } // Dimensions else if (strcmp (argv[i], "-nx") == 0) { if (i+1 < argc) {nx = atoi (argv[i+1]); SHIFT_NARGS(2);} else usage(); } else if (strcmp (argv[i], "-ny") == 0) { if (i+1 < argc) {ny = atoi (argv[i+1]); SHIFT_NARGS(2);} else usage(); } else if (strcmp (argv[i], "-nz") == 0) { if (i+1 < argc) {nz = atoi (argv[i+1]); SHIFT_NARGS(2);} else usage(); } else if (strcmp (argv[i], "-write") == 0) { if (i+1 < argc) {datafile = argv[i+1]; SHIFT_NARGS(2);} else usage(); } else if (strcmp (argv[i], "-shrink") == 0) { shrink = true; SHIFT_ARGS(); } else usage(); } // si le rayon n'est pas defini on prend une sphere visible suivant X if (R == 0.0) R = nx; Cell::setR(R); Node * n1 = new Node (0.0, 0.0, 0.0); Node * n2 = new Node ((double) nx+1, 0.0, 0.0); Node * n3 = new Node ((double) nx+1, 0.0, (double) nz+1); Node * n4 = new Node (0.0, 0.0, (double) nz+1); Node * n5 = new Node (0.0, (double) ny+1, 0.0); Node * n6 = new Node ((double) nx+1, (double) ny+1, 0.0); Node * n7 = new Node ((double) nx+1, (double) ny+1, (double) nz+1); Node * n8 = new Node (0.0, (double) ny+1, (double) nz+1); // Create mesh Mesh * mesh = new Mesh (nx, ny, nz, n1, n2, n3, n4, n5, n6, n7, n8); mesh->setFactor (factor); for (int i = 0; i < depth; i++) mesh->refine(); // reduction des points mesh->mergePoints(); // generation du dataset vtkDataSet * ds = mesh->getDataSet(); // reduction des mailles vtkShrinkFilter * shrinkFilter = vtkShrinkFilter::New(); if (shrink) { shrinkFilter->SetShrinkFactor (0.9); shrinkFilter->SetInputData (ds); shrinkFilter->Update(); ds = shrinkFilter->GetOutput(); } // ecriture du dataset if (datafile != "") { vtkUnstructuredGridWriter * writer = vtkUnstructuredGridWriter::New(); writer->SetInputData(ds); writer->SetFileName (datafile.c_str()); writer->Write(); writer->Delete(); } // Geometry filter vtkDataSetSurfaceFilter * dataSetSurfaceFilter = vtkDataSetSurfaceFilter::New(); dataSetSurfaceFilter->SetInputData(ds); // Mappers vtkPolyDataMapper * polyDataMapper1 = vtkPolyDataMapper::New(); polyDataMapper1->SetInputConnection(dataSetSurfaceFilter->GetOutputPort()); polyDataMapper1->SetResolveCoincidentTopologyToPolygonOffset(); polyDataMapper1->SetResolveCoincidentTopologyPolygonOffsetParameters( 0, 1 ); vtkPolyDataMapper * polyDataMapper2 = vtkPolyDataMapper::New(); polyDataMapper2->SetInputConnection(dataSetSurfaceFilter->GetOutputPort()); polyDataMapper2->SetResolveCoincidentTopologyToPolygonOffset(); polyDataMapper2->SetResolveCoincidentTopologyPolygonOffsetParameters( 1, 1 ); // Actors vtkActor *actor1 = vtkActor::New(); actor1->GetProperty()->SetColor(.8,.2,.2); actor1->SetMapper (polyDataMapper1); vtkActor *actor2 = vtkActor::New(); actor2->GetProperty()->SetRepresentationToWireframe(); actor2->GetProperty()->SetColor( .5, .5, .5 ); actor2->SetMapper (polyDataMapper2); // Window and interactor vtkRenderer * ren = vtkRenderer::New(); ren->SetBackground (1.,1.,1.); ren->AddActor(actor1); ren->AddActor(actor2); vtkRenderWindow * renWindow = vtkRenderWindow::New(); renWindow->SetSize (800,800); renWindow->AddRenderer(ren); vtkRenderWindowInteractor * interacteur = vtkRenderWindowInteractor::New(); vtkInteractorStyleSwitch * style = vtkInteractorStyleSwitch::SafeDownCast (interacteur->GetInteractorStyle()); interacteur->SetRenderWindow(renWindow); if (style) style->SetCurrentStyleToTrackballCamera (); // premier rendu renWindow->Render(); interacteur->Start(); // menage delete mesh; delete n1; delete n2; delete n3; delete n4; delete n5; delete n6; delete n7; delete n8; shrinkFilter->Delete(); dataSetSurfaceFilter->Delete(); polyDataMapper1->Delete(); polyDataMapper2->Delete(); actor1->Delete(); actor2->Delete(); ren->Delete(); renWindow->Delete(); interacteur->Delete(); return 0; } <commit_msg>Translate comments from French to English<commit_after>/*========================================================================= Copyright (c) Kitware Inc. All rights reserved. =========================================================================*/ // .SECTION Description // This program illustrates the use of the vtkHyperTreeGrid // data set and various filters acting upon hyper it. // It generates output files in VTK format. // // .SECTION Usage // // .SECTION Thanks // This program was written by Daniel Aguilera and Philippe Pebay // This work was supported by Commissariat a l'Energie Atomique (CEA/DIF) #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkPolyDataMapper.h> #include <vtkPolyData.h> #include <vtkActor.h> #include <vtkDataSetSurfaceFilter.h> #include <vtkUnstructuredGrid.h> #include <vtkShrinkFilter.h> #include <vtkProperty.h> #include <vtkUnstructuredGridWriter.h> #include <vtkInteractorStyleSwitch.h> #include "Mesh.h" #include "Cell.h" #include "Node.h" using namespace std; #define SHIFT_ARGS() for (int j=i;j<(argc-1);j++) argv[j] = argv[j+1]; argc--; i-- #define SHIFT_NARGS(n) for (int j=i;j<(argc-(n));j++) argv[j] = argv[j+(n)]; argc-=(n); i-- void usage () { cout << "Usage : amr [-level <int>] [-refine <int>] [-nx <int>] [-ny <int>] [-nz <int>] [-write <file>] [-shrink] [-help]" << endl; cout << " -depth : Number of refinement levels. Defaut = 3" << endl; cout << " -factor : Refinement branching factor. Defaut = 3" << endl; cout << " -n[xyz] : Number of grid points in each direction. Defaut = 5" << endl; cout << " -write : Output mesh in a VTK unstructured grid file. Defaut = no output" << endl; cout << " -shrink : Apply shrink filter before rendering geometry. Defaut = do not shrink" << endl; cout << " -help : Print available options" << endl; exit (0); } int main( int argc, char *argv[] ) { // Default values int nx = 5; int ny = 5; int nz = 5; int depth = 3; int factor = 3; bool shrink = false; string datafile = ""; double R = 0.0; for (int i = 1; i < argc; i++) { // Refinement depth if (strcmp (argv[i], "-depth") == 0) { if (i+1 < argc) {depth = atoi (argv[i+1]); SHIFT_NARGS(2);} else usage(); } // Branch factor else if (strcmp (argv[i], "-factor") == 0) { if (i+1 < argc) {factor = atoi (argv[i+1]); SHIFT_NARGS(2);} else usage(); } // Dimensions else if (strcmp (argv[i], "-nx") == 0) { if (i+1 < argc) {nx = atoi (argv[i+1]); SHIFT_NARGS(2);} else usage(); } else if (strcmp (argv[i], "-ny") == 0) { if (i+1 < argc) {ny = atoi (argv[i+1]); SHIFT_NARGS(2);} else usage(); } else if (strcmp (argv[i], "-nz") == 0) { if (i+1 < argc) {nz = atoi (argv[i+1]); SHIFT_NARGS(2);} else usage(); } else if (strcmp (argv[i], "-write") == 0) { if (i+1 < argc) {datafile = argv[i+1]; SHIFT_NARGS(2);} else usage(); } else if (strcmp (argv[i], "-shrink") == 0) { shrink = true; SHIFT_ARGS(); } else usage(); } // If no radius is defined, then take the number of grid points along X axis if (R == 0.0) R = nx; Cell::setR(R); Node * n1 = new Node (0.0, 0.0, 0.0); Node * n2 = new Node ((double) nx+1, 0.0, 0.0); Node * n3 = new Node ((double) nx+1, 0.0, (double) nz+1); Node * n4 = new Node (0.0, 0.0, (double) nz+1); Node * n5 = new Node (0.0, (double) ny+1, 0.0); Node * n6 = new Node ((double) nx+1, (double) ny+1, 0.0); Node * n7 = new Node ((double) nx+1, (double) ny+1, (double) nz+1); Node * n8 = new Node (0.0, (double) ny+1, (double) nz+1); // Create mesh Mesh * mesh = new Mesh (nx, ny, nz, n1, n2, n3, n4, n5, n6, n7, n8); mesh->setFactor (factor); for (int i = 0; i < depth; i++) mesh->refine(); // Reduce points mesh->mergePoints(); // Generate dataset vtkDataSet * ds = mesh->getDataSet(); // Reduce cells des mailles vtkShrinkFilter * shrinkFilter = vtkShrinkFilter::New(); if (shrink) { shrinkFilter->SetShrinkFactor (0.9); shrinkFilter->SetInputData (ds); shrinkFilter->Update(); ds = shrinkFilter->GetOutput(); } // Write out dataset if (datafile != "") { vtkUnstructuredGridWriter * writer = vtkUnstructuredGridWriter::New(); writer->SetInputData(ds); writer->SetFileName (datafile.c_str()); writer->Write(); writer->Delete(); } // Geometry filter vtkDataSetSurfaceFilter * dataSetSurfaceFilter = vtkDataSetSurfaceFilter::New(); dataSetSurfaceFilter->SetInputData(ds); // Mappers vtkPolyDataMapper * polyDataMapper1 = vtkPolyDataMapper::New(); polyDataMapper1->SetInputConnection(dataSetSurfaceFilter->GetOutputPort()); polyDataMapper1->SetResolveCoincidentTopologyToPolygonOffset(); polyDataMapper1->SetResolveCoincidentTopologyPolygonOffsetParameters( 0, 1 ); vtkPolyDataMapper * polyDataMapper2 = vtkPolyDataMapper::New(); polyDataMapper2->SetInputConnection(dataSetSurfaceFilter->GetOutputPort()); polyDataMapper2->SetResolveCoincidentTopologyToPolygonOffset(); polyDataMapper2->SetResolveCoincidentTopologyPolygonOffsetParameters( 1, 1 ); // Actors vtkActor *actor1 = vtkActor::New(); actor1->GetProperty()->SetColor(.8,.2,.2); actor1->SetMapper (polyDataMapper1); vtkActor *actor2 = vtkActor::New(); actor2->GetProperty()->SetRepresentationToWireframe(); actor2->GetProperty()->SetColor( .5, .5, .5 ); actor2->SetMapper (polyDataMapper2); // Window and interactor vtkRenderer * ren = vtkRenderer::New(); ren->SetBackground (1.,1.,1.); ren->AddActor(actor1); ren->AddActor(actor2); vtkRenderWindow * renWindow = vtkRenderWindow::New(); renWindow->SetSize (800,800); renWindow->AddRenderer(ren); vtkRenderWindowInteractor * interacteur = vtkRenderWindowInteractor::New(); vtkInteractorStyleSwitch * style = vtkInteractorStyleSwitch::SafeDownCast (interacteur->GetInteractorStyle()); interacteur->SetRenderWindow(renWindow); if (style) style->SetCurrentStyleToTrackballCamera (); // Render renWindow->Render(); interacteur->Start(); // Clean up delete mesh; delete n1; delete n2; delete n3; delete n4; delete n5; delete n6; delete n7; delete n8; shrinkFilter->Delete(); dataSetSurfaceFilter->Delete(); polyDataMapper1->Delete(); polyDataMapper2->Delete(); actor1->Delete(); actor2->Delete(); ren->Delete(); renWindow->Delete(); interacteur->Delete(); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkCpu.h" #include "SkHalf.h" #include "SkOnce.h" #include "SkOpts.h" #if defined(SK_ARM_HAS_NEON) #define SK_OPTS_NS neon #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSSE3 #define SK_OPTS_NS ssse3 #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE3 #define SK_OPTS_NS sse3 #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE2 #define SK_OPTS_NS sse2 #else #define SK_OPTS_NS portable #endif #include "SkBlend_opts.h" #include "SkBlitMask_opts.h" #include "SkBlitRow_opts.h" #include "SkBlurImageFilter_opts.h" #include "SkChecksum_opts.h" #include "SkColorCubeFilter_opts.h" #include "SkMorphologyImageFilter_opts.h" #include "SkSwizzler_opts.h" #include "SkTextureCompressor_opts.h" #include "SkXfermode_opts.h" namespace SkOpts { // Define default function pointer values here... // If our global compile options are set high enough, these defaults might even be // CPU-specialized, e.g. a typical x86-64 machine might start with SSE2 defaults. // They'll still get a chance to be replaced with even better ones, e.g. using SSE4.1. #define DEFINE_DEFAULT(name) decltype(name) name = SK_OPTS_NS::name DEFINE_DEFAULT(create_xfermode); DEFINE_DEFAULT(color_cube_filter_span); DEFINE_DEFAULT(box_blur_xx); DEFINE_DEFAULT(box_blur_xy); DEFINE_DEFAULT(box_blur_yx); DEFINE_DEFAULT(dilate_x); DEFINE_DEFAULT(dilate_y); DEFINE_DEFAULT( erode_x); DEFINE_DEFAULT( erode_y); DEFINE_DEFAULT(texture_compressor); DEFINE_DEFAULT(fill_block_dimensions); DEFINE_DEFAULT(blit_mask_d32_a8); DEFINE_DEFAULT(blit_row_color32); DEFINE_DEFAULT(blit_row_s32a_opaque); DEFINE_DEFAULT(RGBA_to_BGRA); DEFINE_DEFAULT(RGBA_to_rgbA); DEFINE_DEFAULT(RGBA_to_bgrA); DEFINE_DEFAULT(RGB_to_RGB1); DEFINE_DEFAULT(RGB_to_BGR1); DEFINE_DEFAULT(gray_to_RGB1); DEFINE_DEFAULT(grayA_to_RGBA); DEFINE_DEFAULT(grayA_to_rgbA); DEFINE_DEFAULT(inverted_CMYK_to_RGB1); DEFINE_DEFAULT(inverted_CMYK_to_BGR1); DEFINE_DEFAULT(srcover_srgb_srgb); DEFINE_DEFAULT(hash_fn); #undef DEFINE_DEFAULT // Each Init_foo() is defined in src/opts/SkOpts_foo.cpp. void Init_ssse3(); void Init_sse41(); void Init_sse42(); void Init_avx(); void Init_avx2() {} void Init_crc32(); static void init() { #if !defined(SK_BUILD_NO_OPTS) #if defined(SK_CPU_X86) if (SkCpu::Supports(SkCpu::SSSE3)) { Init_ssse3(); } if (SkCpu::Supports(SkCpu::SSE41)) { Init_sse41(); } if (SkCpu::Supports(SkCpu::SSE42)) { Init_sse42(); } if (SkCpu::Supports(SkCpu::AVX )) { Init_avx(); } if (SkCpu::Supports(SkCpu::AVX2 )) { Init_avx2(); } #elif defined(SK_CPU_ARM64) if (SkCpu::Supports(SkCpu::CRC32)) { Init_crc32(); } #endif #endif } void Init() { static SkOnce once; once(init); } } // namespace SkOpts <commit_msg>Flesh out SkOpts namespaces.<commit_after>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkCpu.h" #include "SkHalf.h" #include "SkOnce.h" #include "SkOpts.h" #if defined(SK_ARM_HAS_NEON) #if defined(__ARM_FEATURE_CRC32) #define SK_OPTS_NS neon_and_crc32 #else #define SK_OPTS_NS neon #endif #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_AVX2 #define SK_OPTS_NS avx2 #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_AVX #define SK_OPTS_NS avx #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE42 #define SK_OPTS_NS sse42 #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE41 #define SK_OPTS_NS sse41 #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSSE3 #define SK_OPTS_NS ssse3 #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE3 #define SK_OPTS_NS sse3 #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE2 #define SK_OPTS_NS sse2 #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE1 #define SK_OPTS_NS sse #else #define SK_OPTS_NS portable #endif #include "SkBlend_opts.h" #include "SkBlitMask_opts.h" #include "SkBlitRow_opts.h" #include "SkBlurImageFilter_opts.h" #include "SkChecksum_opts.h" #include "SkColorCubeFilter_opts.h" #include "SkMorphologyImageFilter_opts.h" #include "SkSwizzler_opts.h" #include "SkTextureCompressor_opts.h" #include "SkXfermode_opts.h" namespace SkOpts { // Define default function pointer values here... // If our global compile options are set high enough, these defaults might even be // CPU-specialized, e.g. a typical x86-64 machine might start with SSE2 defaults. // They'll still get a chance to be replaced with even better ones, e.g. using SSE4.1. #define DEFINE_DEFAULT(name) decltype(name) name = SK_OPTS_NS::name DEFINE_DEFAULT(create_xfermode); DEFINE_DEFAULT(color_cube_filter_span); DEFINE_DEFAULT(box_blur_xx); DEFINE_DEFAULT(box_blur_xy); DEFINE_DEFAULT(box_blur_yx); DEFINE_DEFAULT(dilate_x); DEFINE_DEFAULT(dilate_y); DEFINE_DEFAULT( erode_x); DEFINE_DEFAULT( erode_y); DEFINE_DEFAULT(texture_compressor); DEFINE_DEFAULT(fill_block_dimensions); DEFINE_DEFAULT(blit_mask_d32_a8); DEFINE_DEFAULT(blit_row_color32); DEFINE_DEFAULT(blit_row_s32a_opaque); DEFINE_DEFAULT(RGBA_to_BGRA); DEFINE_DEFAULT(RGBA_to_rgbA); DEFINE_DEFAULT(RGBA_to_bgrA); DEFINE_DEFAULT(RGB_to_RGB1); DEFINE_DEFAULT(RGB_to_BGR1); DEFINE_DEFAULT(gray_to_RGB1); DEFINE_DEFAULT(grayA_to_RGBA); DEFINE_DEFAULT(grayA_to_rgbA); DEFINE_DEFAULT(inverted_CMYK_to_RGB1); DEFINE_DEFAULT(inverted_CMYK_to_BGR1); DEFINE_DEFAULT(srcover_srgb_srgb); DEFINE_DEFAULT(hash_fn); #undef DEFINE_DEFAULT // Each Init_foo() is defined in src/opts/SkOpts_foo.cpp. void Init_ssse3(); void Init_sse41(); void Init_sse42(); void Init_avx(); void Init_avx2() {} void Init_crc32(); static void init() { #if !defined(SK_BUILD_NO_OPTS) #if defined(SK_CPU_X86) if (SkCpu::Supports(SkCpu::SSSE3)) { Init_ssse3(); } if (SkCpu::Supports(SkCpu::SSE41)) { Init_sse41(); } if (SkCpu::Supports(SkCpu::SSE42)) { Init_sse42(); } if (SkCpu::Supports(SkCpu::AVX )) { Init_avx(); } if (SkCpu::Supports(SkCpu::AVX2 )) { Init_avx2(); } #elif defined(SK_CPU_ARM64) if (SkCpu::Supports(SkCpu::CRC32)) { Init_crc32(); } #endif #endif } void Init() { static SkOnce once; once(init); } } // namespace SkOpts <|endoftext|>
<commit_before>#ifndef INCLUDED_KONTSEVICH_GRAPH_OPERATOR_ #define INCLUDED_KONTSEVICH_GRAPH_OPERATOR_ #include <ginac/ginac.h> #include "kontsevich_graph_series.hpp" #include "util/cartesian_product.hpp" struct PoissonStructure { std::vector<GiNaC::symbol> coordinates; std::vector< std::vector<GiNaC::ex> > bivector; }; GiNaC::ex operator_from_graph(KontsevichGraph graph, PoissonStructure poisson, std::vector<GiNaC::ex> arguments) { GiNaC::ex result = 0; size_t dimension = poisson.coordinates.size(); // edge labels run from 1 to dimension std::vector<size_t> max_index(2*graph.internal(), dimension); CartesianProduct index_product(max_index); for (auto indices = index_product.begin(); indices != index_product.end(); ++indices) { // TODO: test if graph.external() == arguments.size() GiNaC::ex summand = graph.sign(); for (size_t n = 0; n != graph.vertices(); ++n) { GiNaC::ex factor; if (n < graph.external()) factor = arguments[n]; else factor = poisson.bivector[(*indices)[2*(n-graph.external())]][(*indices)[2*(n-graph.external()) + 1]]; for (size_t j : graph.neighbors_in(n)) { size_t incoming_index = ((size_t)graph.targets(j).first == n) ? (*indices)[2*(j-graph.external())] : (*indices)[2*(j-graph.external()) + 1]; factor = diff(factor, poisson.coordinates[incoming_index]); } summand *= factor; } result += summand; } return result; } GiNaC::ex evaluate(KontsevichGraphSum<GiNaC::ex> terms, PoissonStructure poisson, std::vector<GiNaC::ex> arguments) { GiNaC::ex total = 0; for (auto& term : terms) { total += term.first * operator_from_graph(term.second, poisson, arguments); } return total; } #endif <commit_msg>Add method to get the coefficients of the differential operator associated to a graph.<commit_after>#ifndef INCLUDED_KONTSEVICH_GRAPH_OPERATOR_ #define INCLUDED_KONTSEVICH_GRAPH_OPERATOR_ #include <ginac/ginac.h> #include "kontsevich_graph_series.hpp" #include "util/cartesian_product.hpp" struct PoissonStructure { std::vector<GiNaC::symbol> coordinates; std::vector< std::vector<GiNaC::ex> > bivector; }; GiNaC::ex operator_from_graph(KontsevichGraph graph, PoissonStructure poisson, std::vector<GiNaC::ex> arguments) { GiNaC::ex result = 0; size_t dimension = poisson.coordinates.size(); // edge labels run from 1 to dimension std::vector<size_t> max_index(2*graph.internal(), dimension); CartesianProduct index_product(max_index); for (auto indices = index_product.begin(); indices != index_product.end(); ++indices) { // TODO: test if graph.external() == arguments.size() GiNaC::ex summand = graph.sign(); for (size_t n = 0; n != graph.vertices(); ++n) { GiNaC::ex factor; if (n < graph.external()) factor = arguments[n]; else factor = poisson.bivector[(*indices)[2*(n-graph.external())]][(*indices)[2*(n-graph.external()) + 1]]; for (size_t j : graph.neighbors_in(n)) { size_t incoming_index = ((size_t)graph.targets(j).first == n) ? (*indices)[2*(j-graph.external())] : (*indices)[2*(j-graph.external()) + 1]; factor = diff(factor, poisson.coordinates[incoming_index]); } summand *= factor; } result += summand; } return result; } // TODO: refactor the code duplicated above and below void operator_coefficient_from_graph(KontsevichGraph graph, PoissonStructure poisson, GiNaC::ex coefficient, std::map< std::vector< std::multiset<size_t> >, GiNaC::ex >& accumulator) { std::vector< std::multiset<size_t> > external_indices_template(graph.external()); for (size_t n = 0; n != graph.external(); ++n) for (size_t j : graph.neighbors_in(n)) external_indices_template[n].insert( ((size_t)graph.targets(j).first == n) ? 2*(j-graph.external()) : 2*(j-graph.external()) + 1 ); GiNaC::ex result = 0; size_t dimension = poisson.coordinates.size(); std::vector<size_t> max_index(2*graph.internal(), dimension); CartesianProduct index_product(max_index); for (auto indices = index_product.begin(); indices != index_product.end(); ++indices) { std::vector< std::multiset<size_t> > external_indices(graph.external()); for (size_t n = 0; n != graph.external(); ++n) for (size_t j : external_indices_template[n]) external_indices[n].insert((*indices)[j]); GiNaC::ex summand = coefficient * graph.sign(); for (size_t n : graph.internal_vertices()) { GiNaC::ex factor = poisson.bivector[(*indices)[2*(n-graph.external())]][(*indices)[2*(n-graph.external()) + 1]]; for (size_t j : graph.neighbors_in(n)) { size_t incoming_index = ((size_t)graph.targets(j).first == n) ? (*indices)[2*(j-graph.external())] : (*indices)[2*(j-graph.external()) + 1]; factor = diff(factor, poisson.coordinates[incoming_index]); } summand *= factor; } accumulator[external_indices] += summand; } } GiNaC::ex evaluate(KontsevichGraphSum<GiNaC::ex> terms, PoissonStructure poisson, std::vector<GiNaC::ex> arguments) { GiNaC::ex total = 0; for (auto& term : terms) { total += term.first * operator_from_graph(term.second, poisson, arguments); } return total; } std::map< std::vector< std::multiset<size_t> >, GiNaC::ex > evaluate_coefficients(KontsevichGraphSum<GiNaC::ex> terms, PoissonStructure poisson) { std::map< std::vector< std::multiset<size_t> >, GiNaC::ex > accumulator; for (auto& term : terms) { operator_coefficient_from_graph(term.second, poisson, term.first, accumulator); } return accumulator; } #endif <|endoftext|>
<commit_before>#include <time.h> #include <iostream> #include <fstream> #include "logger.h" LoggerBuf::LoggerBuf() : std::streambuf(), m_has_file(false), m_output_to_console(true) { } LoggerBuf::LoggerBuf(const std::string &file_name, bool output_to_console) : m_file(file_name), m_output_to_console(output_to_console), m_has_file(true) { if(!m_file.is_open()) { m_has_file = false; } } int LoggerBuf::overflow(int c) { if(m_output_to_console) { std::cout.put(c); } if(m_has_file) { m_file.put(c); } return c; } std::streamsize LoggerBuf::xsputn (const char* s, std::streamsize n) { if(m_output_to_console) { std::cout << std::string(s, n); } if(m_has_file) { m_file << std::string(s, n); } return n; } Logger::Logger(const std::string &log_file, bool console_output) : m_buf(log_file, console_output), m_output(&m_buf) { } Logger::Logger() : m_buf(), m_output(&m_buf) { } std::ostream &Logger::log(LogSeverity sev) { const char *sevtext; switch(sev) { case LSEVERITY_SPAM: sevtext = "SPAM"; break; case LSEVERITY_DEBUG: sevtext = "DEBUG"; break; case LSEVERITY_INFO: sevtext = "INFO"; break; case LSEVERITY_WARNING: sevtext = "WARNING"; break; case LSEVERITY_SECURITY: sevtext = "SECURITY"; break; case LSEVERITY_ERROR: sevtext = "ERROR"; break; case LSEVERITY_FATAL: sevtext = "FATAL"; break; } time_t rawtime; time(&rawtime); char timetext[1024]; strftime(timetext, 1024, "%Y-%m-%d %H:%M:%S", localtime(&rawtime)); m_output << "[" << timetext << "] " << sevtext << ": "; return m_output; } #define LOG_LEVEL(name, severity) \ std::ostream &Logger::name() \ { \ return log(severity); \ } LOG_LEVEL(spam, LSEVERITY_SPAM) LOG_LEVEL(debug, LSEVERITY_DEBUG) LOG_LEVEL(info, LSEVERITY_INFO) LOG_LEVEL(warning, LSEVERITY_WARNING) LOG_LEVEL(security, LSEVERITY_SECURITY) LOG_LEVEL(error, LSEVERITY_ERROR) LOG_LEVEL(fatal, LSEVERITY_FATAL) <commit_msg>Logger: Switch LoggerBuf::xsputn to use ostream::write instead of ostream::operator<<<commit_after>#include <time.h> #include <iostream> #include <fstream> #include "logger.h" LoggerBuf::LoggerBuf() : std::streambuf(), m_has_file(false), m_output_to_console(true) { } LoggerBuf::LoggerBuf(const std::string &file_name, bool output_to_console) : m_file(file_name), m_output_to_console(output_to_console), m_has_file(true) { if(!m_file.is_open()) { m_has_file = false; } } int LoggerBuf::overflow(int c) { if(m_output_to_console) { std::cout.put(c); } if(m_has_file) { m_file.put(c); } return c; } std::streamsize LoggerBuf::xsputn (const char* s, std::streamsize n) { if(m_output_to_console) { std::cout.write(s, n); } if(m_has_file) { m_file.write(s, n); } return n; } Logger::Logger(const std::string &log_file, bool console_output) : m_buf(log_file, console_output), m_output(&m_buf) { } Logger::Logger() : m_buf(), m_output(&m_buf) { } std::ostream &Logger::log(LogSeverity sev) { const char *sevtext; switch(sev) { case LSEVERITY_SPAM: sevtext = "SPAM"; break; case LSEVERITY_DEBUG: sevtext = "DEBUG"; break; case LSEVERITY_INFO: sevtext = "INFO"; break; case LSEVERITY_WARNING: sevtext = "WARNING"; break; case LSEVERITY_SECURITY: sevtext = "SECURITY"; break; case LSEVERITY_ERROR: sevtext = "ERROR"; break; case LSEVERITY_FATAL: sevtext = "FATAL"; break; } time_t rawtime; time(&rawtime); char timetext[1024]; strftime(timetext, 1024, "%Y-%m-%d %H:%M:%S", localtime(&rawtime)); m_output << "[" << timetext << "] " << sevtext << ": "; return m_output; } #define LOG_LEVEL(name, severity) \ std::ostream &Logger::name() \ { \ return log(severity); \ } LOG_LEVEL(spam, LSEVERITY_SPAM) LOG_LEVEL(debug, LSEVERITY_DEBUG) LOG_LEVEL(info, LSEVERITY_INFO) LOG_LEVEL(warning, LSEVERITY_WARNING) LOG_LEVEL(security, LSEVERITY_SECURITY) LOG_LEVEL(error, LSEVERITY_ERROR) LOG_LEVEL(fatal, LSEVERITY_FATAL) <|endoftext|>
<commit_before>/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2010-08-13 Markus Litz <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * @brief Implementation of CPACS wing profile handling routines. */ #include <iostream> #include <sstream> #include <vector> #include "CTiglError.h" #include "CTiglLogging.h" #include "CTiglWingProfilePointList.h" #include "math.h" #include "gp_Pnt2d.hxx" #include "gp_Vec2d.hxx" #include "gp_Dir2d.hxx" #include "gp_Pln.hxx" #include "Geom2d_Line.hxx" #include "Geom2d_TrimmedCurve.hxx" #include "Geom_TrimmedCurve.hxx" #include "TopoDS.hxx" #include "TopExp_Explorer.hxx" #include "TopAbs_ShapeEnum.hxx" #include "TopoDS_Edge.hxx" #include "GCE2d_MakeSegment.hxx" #include "BRep_Tool.hxx" #include "BRepAdaptor_CompCurve.hxx" #include "Geom2dAPI_InterCurveCurve.hxx" #include "GeomAPI_ProjectPointOnCurve.hxx" #include "GeomAPI.hxx" #include "gce_MakeDir.hxx" #include "gce_MakePln.hxx" #include "BRepTools_WireExplorer.hxx" #include "BRepBuilderAPI_MakeEdge.hxx" #include "BRepBuilderAPI_MakeWire.hxx" #include "ShapeFix_Wire.hxx" #include "CTiglInterpolateBsplineWire.h" #include "CTiglInterpolateLinearWire.h" #include "ITiglWingProfileAlgo.h" #include "CCPACSWingProfile.h" namespace tigl { // Constructor CCPACSWingProfile::CCPACSWingProfile(CTiglUIDManager* uidMgr) : generated::CPACSProfileGeometry(uidMgr), isRotorProfile(false) {} CCPACSWingProfile::~CCPACSWingProfile() {} // Cleanup routine void CCPACSWingProfile::Cleanup() { isRotorProfile = false; Invalidate(); } // Read wing profile file void CCPACSWingProfile::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) { Cleanup(); if (xpath.find("rotorAirfoil") != std::string::npos) { isRotorProfile = true; } generated::CPACSProfileGeometry::ReadCPACS(tixiHandle, xpath); } // Returns whether the profile is a rotor profile bool CCPACSWingProfile::IsRotorProfile() const { return isRotorProfile; } // Invalidates internal wing profile state void CCPACSWingProfile::Invalidate() { GetProfileAlgo()->Invalidate(); } // Returns the wing profile upper wire TopoDS_Edge CCPACSWingProfile::GetUpperWire(TiglShapeModifier mod) const { return GetProfileAlgo()->GetUpperWire(mod); } // Returns the wing profile lower wire TopoDS_Edge CCPACSWingProfile::GetLowerWire(TiglShapeModifier mod) const { return GetProfileAlgo()->GetLowerWire(mod); } // Returns the wing profile trailing edge TopoDS_Edge CCPACSWingProfile::GetTrailingEdge(TiglShapeModifier mod) const { return GetProfileAlgo()->GetTrailingEdge(mod); } // Returns the wing profile lower and upper wire fused TopoDS_Wire CCPACSWingProfile::GetSplitWire(TiglShapeModifier mod) const { const ITiglWingProfileAlgo* profileAlgo = GetProfileAlgo(); // rebuild closed wire BRepBuilderAPI_MakeWire closedWireBuilder; closedWireBuilder.Add(profileAlgo->GetLowerWire(mod)); closedWireBuilder.Add(profileAlgo->GetUpperWire(mod)); if (!profileAlgo->GetTrailingEdge(mod).IsNull()) { closedWireBuilder.Add(profileAlgo->GetTrailingEdge(mod)); } closedWireBuilder.Build(); if (!closedWireBuilder.IsDone()) { throw CTiglError("Error creating closed wing profile"); } return closedWireBuilder.Wire(); } TopoDS_Wire CCPACSWingProfile::GetWire(TiglShapeModifier mod) const { const ITiglWingProfileAlgo* profileAlgo = GetProfileAlgo(); // rebuild closed wire BRepBuilderAPI_MakeWire closedWireBuilder; closedWireBuilder.Add(profileAlgo->GetUpperLowerWire(mod)); if (!profileAlgo->GetTrailingEdge(mod).IsNull()) { closedWireBuilder.Add(profileAlgo->GetTrailingEdge(mod)); } return closedWireBuilder.Wire(); } // Returns the leading edge point of the wing profile wire. The leading edge point // is already transformed by the wing profile transformation. gp_Pnt CCPACSWingProfile::GetLEPoint() const { return GetProfileAlgo()->GetLEPoint(); } // Returns the trailing edge point of the wing profile wire. The trailing edge point // is already transformed by the wing profile transformation. gp_Pnt CCPACSWingProfile::GetTEPoint() const { return GetProfileAlgo()->GetTEPoint(); } // Returns a point on the chord line between leading and trailing // edge as function of parameter xsi, which ranges from 0.0 to 1.0. // For xsi = 0.0 chord point is equal to leading edge, for xsi = 1.0 // chord point is equal to trailing edge. gp_Pnt CCPACSWingProfile::GetChordPoint(double xsi) const { if (xsi < 0.0 || xsi > 1.0) { throw CTiglError("Parameter xsi not in the range 0.0 <= xsi <= 1.0 in CCPACSWingProfile::GetChordPoint", TIGL_ERROR); } Handle(Geom2d_TrimmedCurve) chordLine = GetChordLine(); Standard_Real firstParam = chordLine->FirstParameter(); Standard_Real lastParam = chordLine->LastParameter(); Standard_Real param = (lastParam - firstParam) * xsi; gp_Pnt2d chordPoint2d; chordLine->D0(param, chordPoint2d); return gp_Pnt(chordPoint2d.X(), 0.0, chordPoint2d.Y()); } // Returns the chord line as a wire TopoDS_Wire CCPACSWingProfile::GetChordLineWire() const { // convert 2d chordline to 3d Handle(Geom2d_TrimmedCurve) chordLine = GetChordLine(); gp_Pnt origin; gp_Dir yDir(0.0, 1.0, 0.0); gp_Pln xzPlane(origin, yDir); Handle(Geom_Curve) chordLine3d = GeomAPI::To3d(chordLine, xzPlane); TopoDS_Edge chordEdge = BRepBuilderAPI_MakeEdge(chordLine3d); TopoDS_Wire chordWire = BRepBuilderAPI_MakeWire(chordEdge); return chordWire; } // Returns a point on the upper wing profile as function of // parameter xsi, which ranges from 0.0 to 1.0. // For xsi = 0.0 point is equal to leading edge, for xsi = 1.0 // point is equal to trailing edge. gp_Pnt CCPACSWingProfile::GetUpperPoint(double xsi) const { return GetPoint(xsi, true); } // Returns a point on the lower wing profile as function of // parameter xsi, which ranges from 0.0 to 1.0. // For xsi = 0.0 point is equal to leading edge, for xsi = 1.0 // point is equal to trailing edge. gp_Pnt CCPACSWingProfile::GetLowerPoint(double xsi) const { return GetPoint(xsi, false); } // Returns an upper or lower point on the wing profile in // dependence of parameter xsi, which ranges from 0.0 to 1.0. // For xsi = 0.0 point is equal to leading edge, for xsi = 1.0 // point is equal to trailing edge. If fromUpper is true, a point // on the upper profile is returned, otherwise from the lower. gp_Pnt CCPACSWingProfile::GetPoint(double xsi, bool fromUpper) const { if (xsi < 0.0 || xsi > 1.0) { throw CTiglError("Parameter xsi not in the range 0.0 <= xsi <= 1.0 in CCPACSWingProfile::GetPoint", TIGL_ERROR); } if (xsi < Precision::Confusion()) { return GetLEPoint(); } if ((1.0 - xsi) < Precision::Confusion()) { return GetTEPoint(); } gp_Pnt chordPoint3d = GetChordPoint(xsi); gp_Pnt2d chordPoint2d(chordPoint3d.X(), chordPoint3d.Z()); gp_Pnt le3d = GetLEPoint(); gp_Pnt te3d = GetTEPoint(); gp_Pnt2d le2d(le3d.X(), le3d.Z()); gp_Pnt2d te2d(te3d.X(), te3d.Z()); // Normal vector on chord line gp_Vec2d normalVec2d(-(le2d.Y() - te2d.Y()), (le2d.X() - te2d.X())); // Compute 2d line normal to chord line Handle(Geom2d_Line) line2d = new Geom2d_Line(chordPoint2d, gp_Dir2d(normalVec2d)); // Define xz-plane for curve projection gp_Pln xzPlane = gce_MakePln(gp_Pnt(0.0, 0.0, 0.0), gp_Pnt(1.0, 0.0, 0.0), gp_Pnt(0.0, 0.0, 1.0)); // Loop over all edges of the wing profile curve and try to find intersection points std::vector<gp_Pnt2d> ipnts2d; TopoDS_Edge edge; if (fromUpper) { edge = GetUpperWire(); } else { edge = GetLowerWire(); } Standard_Real firstParam; Standard_Real lastParam; // get curve and trim it - trimming is important, else it will be infinite Handle(Geom_Curve) curve3d = BRep_Tool::Curve(edge, firstParam, lastParam); curve3d = new Geom_TrimmedCurve(curve3d, firstParam, lastParam); // Convert 3d curve to 2d curve lying in the xz-plane Handle(Geom2d_Curve) curve2d = GeomAPI::To2d(curve3d, xzPlane); // Check if there are intersection points between line2d and curve2d Geom2dAPI_InterCurveCurve intersection(line2d, curve2d); for (int n = 1; n <= intersection.NbPoints(); n++) { ipnts2d.push_back(intersection.Point(n)); } if (ipnts2d.size() == 1) { // There is only one intesection point with the wire gp_Pnt2d ipnt2d = ipnts2d[0]; gp_Pnt ipnt3d(ipnt2d.X(), 0.0, ipnt2d.Y()); return ipnt3d; } else if (ipnts2d.size() > 1) { // There are one or more intersection points with the wire. Find the // points with the minimum and maximum y-values. gp_Pnt2d minYPnt2d = ipnts2d[0]; gp_Pnt2d maxYPnt2d = minYPnt2d; for (std::vector<gp_Pnt2d>::size_type i = 1; i < ipnts2d.size(); i++) { gp_Pnt2d currPnt2d = ipnts2d[i]; if (currPnt2d.Y() < minYPnt2d.Y()) { minYPnt2d = currPnt2d; } if (currPnt2d.Y() > maxYPnt2d.Y()) { maxYPnt2d = currPnt2d; } } gp_Pnt maxYPnt3d(maxYPnt2d.X(), 0.0, maxYPnt2d.Y()); gp_Pnt minYPnt3d(minYPnt2d.X(), 0.0, minYPnt2d.Y()); if (fromUpper) { return maxYPnt3d; } return minYPnt3d; } throw CTiglError("No intersection point found in CCPACSWingProfile::GetPoint", TIGL_NOT_FOUND); } // Helper function to determine the chord line between leading and trailing edge in the profile plane Handle(Geom2d_TrimmedCurve) CCPACSWingProfile::GetChordLine() const { gp_Pnt le3d = GetLEPoint(); gp_Pnt te3d = GetTEPoint(); gp_Pnt2d le2d(le3d.X(), le3d.Z()); // create point in profile-plane (omitting Y coordinate) gp_Pnt2d te2d(te3d.X(), te3d.Z()); Handle(Geom2d_TrimmedCurve) chordLine = GCE2d_MakeSegment(le2d, te2d); return chordLine; } ITiglWingProfileAlgo* CCPACSWingProfile::GetProfileAlgo() { if (m_pointList_choice1) { // in case the wing profile algorithm is a point list, create the additional algorithm instance if (!pointListAlgo) pointListAlgo.reset(new CTiglWingProfilePointList(*this, *m_pointList_choice1)); return &*pointListAlgo; } else if (m_cst2D_choice2) { return &*m_cst2D_choice2; } else { throw CTiglError("no profile algorithm"); } } const ITiglWingProfileAlgo* CCPACSWingProfile::GetProfileAlgo() const { return const_cast<CCPACSWingProfile&>(*this).GetProfileAlgo(); } bool CCPACSWingProfile::HasBluntTE() const { const ITiglWingProfileAlgo* algo = GetProfileAlgo(); if (!algo) { throw CTiglError("No wing profile algorithm regsitered in CCPACSWingProfile::HasBluntTE()!"); } return algo->HasBluntTE(); } } // end namespace tigl <commit_msg>resetting profile algo in CCPACSWingProfile::Cleanup() instead of invalidating it to avoid retrieving profile algo before ReadCPACS was called<commit_after>/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2010-08-13 Markus Litz <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * @brief Implementation of CPACS wing profile handling routines. */ #include <iostream> #include <sstream> #include <vector> #include "CTiglError.h" #include "CTiglLogging.h" #include "CTiglWingProfilePointList.h" #include "math.h" #include "gp_Pnt2d.hxx" #include "gp_Vec2d.hxx" #include "gp_Dir2d.hxx" #include "gp_Pln.hxx" #include "Geom2d_Line.hxx" #include "Geom2d_TrimmedCurve.hxx" #include "Geom_TrimmedCurve.hxx" #include "TopoDS.hxx" #include "TopExp_Explorer.hxx" #include "TopAbs_ShapeEnum.hxx" #include "TopoDS_Edge.hxx" #include "GCE2d_MakeSegment.hxx" #include "BRep_Tool.hxx" #include "BRepAdaptor_CompCurve.hxx" #include "Geom2dAPI_InterCurveCurve.hxx" #include "GeomAPI_ProjectPointOnCurve.hxx" #include "GeomAPI.hxx" #include "gce_MakeDir.hxx" #include "gce_MakePln.hxx" #include "BRepTools_WireExplorer.hxx" #include "BRepBuilderAPI_MakeEdge.hxx" #include "BRepBuilderAPI_MakeWire.hxx" #include "ShapeFix_Wire.hxx" #include "CTiglInterpolateBsplineWire.h" #include "CTiglInterpolateLinearWire.h" #include "ITiglWingProfileAlgo.h" #include "CCPACSWingProfile.h" namespace tigl { // Constructor CCPACSWingProfile::CCPACSWingProfile(CTiglUIDManager* uidMgr) : generated::CPACSProfileGeometry(uidMgr), isRotorProfile(false) {} CCPACSWingProfile::~CCPACSWingProfile() {} // Cleanup routine void CCPACSWingProfile::Cleanup() { isRotorProfile = false; pointListAlgo.reset(); } // Read wing profile file void CCPACSWingProfile::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) { Cleanup(); if (xpath.find("rotorAirfoil") != std::string::npos) { isRotorProfile = true; } generated::CPACSProfileGeometry::ReadCPACS(tixiHandle, xpath); } // Returns whether the profile is a rotor profile bool CCPACSWingProfile::IsRotorProfile() const { return isRotorProfile; } // Invalidates internal wing profile state void CCPACSWingProfile::Invalidate() { GetProfileAlgo()->Invalidate(); } // Returns the wing profile upper wire TopoDS_Edge CCPACSWingProfile::GetUpperWire(TiglShapeModifier mod) const { return GetProfileAlgo()->GetUpperWire(mod); } // Returns the wing profile lower wire TopoDS_Edge CCPACSWingProfile::GetLowerWire(TiglShapeModifier mod) const { return GetProfileAlgo()->GetLowerWire(mod); } // Returns the wing profile trailing edge TopoDS_Edge CCPACSWingProfile::GetTrailingEdge(TiglShapeModifier mod) const { return GetProfileAlgo()->GetTrailingEdge(mod); } // Returns the wing profile lower and upper wire fused TopoDS_Wire CCPACSWingProfile::GetSplitWire(TiglShapeModifier mod) const { const ITiglWingProfileAlgo* profileAlgo = GetProfileAlgo(); // rebuild closed wire BRepBuilderAPI_MakeWire closedWireBuilder; closedWireBuilder.Add(profileAlgo->GetLowerWire(mod)); closedWireBuilder.Add(profileAlgo->GetUpperWire(mod)); if (!profileAlgo->GetTrailingEdge(mod).IsNull()) { closedWireBuilder.Add(profileAlgo->GetTrailingEdge(mod)); } closedWireBuilder.Build(); if (!closedWireBuilder.IsDone()) { throw CTiglError("Error creating closed wing profile"); } return closedWireBuilder.Wire(); } TopoDS_Wire CCPACSWingProfile::GetWire(TiglShapeModifier mod) const { const ITiglWingProfileAlgo* profileAlgo = GetProfileAlgo(); // rebuild closed wire BRepBuilderAPI_MakeWire closedWireBuilder; closedWireBuilder.Add(profileAlgo->GetUpperLowerWire(mod)); if (!profileAlgo->GetTrailingEdge(mod).IsNull()) { closedWireBuilder.Add(profileAlgo->GetTrailingEdge(mod)); } return closedWireBuilder.Wire(); } // Returns the leading edge point of the wing profile wire. The leading edge point // is already transformed by the wing profile transformation. gp_Pnt CCPACSWingProfile::GetLEPoint() const { return GetProfileAlgo()->GetLEPoint(); } // Returns the trailing edge point of the wing profile wire. The trailing edge point // is already transformed by the wing profile transformation. gp_Pnt CCPACSWingProfile::GetTEPoint() const { return GetProfileAlgo()->GetTEPoint(); } // Returns a point on the chord line between leading and trailing // edge as function of parameter xsi, which ranges from 0.0 to 1.0. // For xsi = 0.0 chord point is equal to leading edge, for xsi = 1.0 // chord point is equal to trailing edge. gp_Pnt CCPACSWingProfile::GetChordPoint(double xsi) const { if (xsi < 0.0 || xsi > 1.0) { throw CTiglError("Parameter xsi not in the range 0.0 <= xsi <= 1.0 in CCPACSWingProfile::GetChordPoint", TIGL_ERROR); } Handle(Geom2d_TrimmedCurve) chordLine = GetChordLine(); Standard_Real firstParam = chordLine->FirstParameter(); Standard_Real lastParam = chordLine->LastParameter(); Standard_Real param = (lastParam - firstParam) * xsi; gp_Pnt2d chordPoint2d; chordLine->D0(param, chordPoint2d); return gp_Pnt(chordPoint2d.X(), 0.0, chordPoint2d.Y()); } // Returns the chord line as a wire TopoDS_Wire CCPACSWingProfile::GetChordLineWire() const { // convert 2d chordline to 3d Handle(Geom2d_TrimmedCurve) chordLine = GetChordLine(); gp_Pnt origin; gp_Dir yDir(0.0, 1.0, 0.0); gp_Pln xzPlane(origin, yDir); Handle(Geom_Curve) chordLine3d = GeomAPI::To3d(chordLine, xzPlane); TopoDS_Edge chordEdge = BRepBuilderAPI_MakeEdge(chordLine3d); TopoDS_Wire chordWire = BRepBuilderAPI_MakeWire(chordEdge); return chordWire; } // Returns a point on the upper wing profile as function of // parameter xsi, which ranges from 0.0 to 1.0. // For xsi = 0.0 point is equal to leading edge, for xsi = 1.0 // point is equal to trailing edge. gp_Pnt CCPACSWingProfile::GetUpperPoint(double xsi) const { return GetPoint(xsi, true); } // Returns a point on the lower wing profile as function of // parameter xsi, which ranges from 0.0 to 1.0. // For xsi = 0.0 point is equal to leading edge, for xsi = 1.0 // point is equal to trailing edge. gp_Pnt CCPACSWingProfile::GetLowerPoint(double xsi) const { return GetPoint(xsi, false); } // Returns an upper or lower point on the wing profile in // dependence of parameter xsi, which ranges from 0.0 to 1.0. // For xsi = 0.0 point is equal to leading edge, for xsi = 1.0 // point is equal to trailing edge. If fromUpper is true, a point // on the upper profile is returned, otherwise from the lower. gp_Pnt CCPACSWingProfile::GetPoint(double xsi, bool fromUpper) const { if (xsi < 0.0 || xsi > 1.0) { throw CTiglError("Parameter xsi not in the range 0.0 <= xsi <= 1.0 in CCPACSWingProfile::GetPoint", TIGL_ERROR); } if (xsi < Precision::Confusion()) { return GetLEPoint(); } if ((1.0 - xsi) < Precision::Confusion()) { return GetTEPoint(); } gp_Pnt chordPoint3d = GetChordPoint(xsi); gp_Pnt2d chordPoint2d(chordPoint3d.X(), chordPoint3d.Z()); gp_Pnt le3d = GetLEPoint(); gp_Pnt te3d = GetTEPoint(); gp_Pnt2d le2d(le3d.X(), le3d.Z()); gp_Pnt2d te2d(te3d.X(), te3d.Z()); // Normal vector on chord line gp_Vec2d normalVec2d(-(le2d.Y() - te2d.Y()), (le2d.X() - te2d.X())); // Compute 2d line normal to chord line Handle(Geom2d_Line) line2d = new Geom2d_Line(chordPoint2d, gp_Dir2d(normalVec2d)); // Define xz-plane for curve projection gp_Pln xzPlane = gce_MakePln(gp_Pnt(0.0, 0.0, 0.0), gp_Pnt(1.0, 0.0, 0.0), gp_Pnt(0.0, 0.0, 1.0)); // Loop over all edges of the wing profile curve and try to find intersection points std::vector<gp_Pnt2d> ipnts2d; TopoDS_Edge edge; if (fromUpper) { edge = GetUpperWire(); } else { edge = GetLowerWire(); } Standard_Real firstParam; Standard_Real lastParam; // get curve and trim it - trimming is important, else it will be infinite Handle(Geom_Curve) curve3d = BRep_Tool::Curve(edge, firstParam, lastParam); curve3d = new Geom_TrimmedCurve(curve3d, firstParam, lastParam); // Convert 3d curve to 2d curve lying in the xz-plane Handle(Geom2d_Curve) curve2d = GeomAPI::To2d(curve3d, xzPlane); // Check if there are intersection points between line2d and curve2d Geom2dAPI_InterCurveCurve intersection(line2d, curve2d); for (int n = 1; n <= intersection.NbPoints(); n++) { ipnts2d.push_back(intersection.Point(n)); } if (ipnts2d.size() == 1) { // There is only one intesection point with the wire gp_Pnt2d ipnt2d = ipnts2d[0]; gp_Pnt ipnt3d(ipnt2d.X(), 0.0, ipnt2d.Y()); return ipnt3d; } else if (ipnts2d.size() > 1) { // There are one or more intersection points with the wire. Find the // points with the minimum and maximum y-values. gp_Pnt2d minYPnt2d = ipnts2d[0]; gp_Pnt2d maxYPnt2d = minYPnt2d; for (std::vector<gp_Pnt2d>::size_type i = 1; i < ipnts2d.size(); i++) { gp_Pnt2d currPnt2d = ipnts2d[i]; if (currPnt2d.Y() < minYPnt2d.Y()) { minYPnt2d = currPnt2d; } if (currPnt2d.Y() > maxYPnt2d.Y()) { maxYPnt2d = currPnt2d; } } gp_Pnt maxYPnt3d(maxYPnt2d.X(), 0.0, maxYPnt2d.Y()); gp_Pnt minYPnt3d(minYPnt2d.X(), 0.0, minYPnt2d.Y()); if (fromUpper) { return maxYPnt3d; } return minYPnt3d; } throw CTiglError("No intersection point found in CCPACSWingProfile::GetPoint", TIGL_NOT_FOUND); } // Helper function to determine the chord line between leading and trailing edge in the profile plane Handle(Geom2d_TrimmedCurve) CCPACSWingProfile::GetChordLine() const { gp_Pnt le3d = GetLEPoint(); gp_Pnt te3d = GetTEPoint(); gp_Pnt2d le2d(le3d.X(), le3d.Z()); // create point in profile-plane (omitting Y coordinate) gp_Pnt2d te2d(te3d.X(), te3d.Z()); Handle(Geom2d_TrimmedCurve) chordLine = GCE2d_MakeSegment(le2d, te2d); return chordLine; } ITiglWingProfileAlgo* CCPACSWingProfile::GetProfileAlgo() { if (m_pointList_choice1) { // in case the wing profile algorithm is a point list, create the additional algorithm instance if (!pointListAlgo) pointListAlgo.reset(new CTiglWingProfilePointList(*this, *m_pointList_choice1)); return &*pointListAlgo; } else if (m_cst2D_choice2) { return &*m_cst2D_choice2; } else { throw CTiglError("no profile algorithm"); } } const ITiglWingProfileAlgo* CCPACSWingProfile::GetProfileAlgo() const { return const_cast<CCPACSWingProfile&>(*this).GetProfileAlgo(); } bool CCPACSWingProfile::HasBluntTE() const { const ITiglWingProfileAlgo* algo = GetProfileAlgo(); if (!algo) { throw CTiglError("No wing profile algorithm regsitered in CCPACSWingProfile::HasBluntTE()!"); } return algo->HasBluntTE(); } } // end namespace tigl <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <numeric> // UNSUPPORTED: c++98, c++03, c++11, c++14 // template<class InputIterator, class OutputIterator, class T, // class BinaryOperation, class UnaryOperation> // OutputIterator transform_exclusive_scan(InputIterator first, InputIterator last, // OutputIterator result, T init, // BinaryOperation binary_op, // UnaryOperation unary_op); #include <numeric> #include <vector> #include <cassert> #include <iostream> #include "test_iterators.h" template <class _Tp = void> struct identity : std::unary_function<_Tp, _Tp> { constexpr const _Tp& operator()(const _Tp& __x) const { return __x;} }; template <> struct identity<void> { template <class _Tp> constexpr auto operator()(_Tp&& __x) const _NOEXCEPT_(noexcept(_VSTD::forward<_Tp>(__x))) -> decltype (_VSTD::forward<_Tp>(__x)) { return _VSTD::forward<_Tp>(__x); } }; template <class Iter1, class BOp, class UOp, class T, class Iter2> void test(Iter1 first, Iter1 last, BOp bop, UOp uop, T init, Iter2 rFirst, Iter2 rLast) { std::vector<typename std::iterator_traits<Iter1>::value_type> v; // Test not in-place std::transform_exclusive_scan(first, last, std::back_inserter(v), init, bop, uop); assert(std::equal(v.begin(), v.end(), rFirst, rLast)); // Test in-place v.clear(); v.assign(first, last); std::transform_exclusive_scan(v.begin(), v.end(), v.begin(), init, bop, uop); assert(std::equal(v.begin(), v.end(), rFirst, rLast)); } template <class Iter> void test() { int ia[] = { 1, 3, 5, 7, 9}; const int pResI0[] = { 0, 1, 4, 9, 16}; // with identity const int mResI0[] = { 0, 0, 0, 0, 0}; const int pResN0[] = { 0, -1, -4, -9, -16}; // with negate const int mResN0[] = { 0, 0, 0, 0, 0}; const int pResI2[] = { 2, 3, 6, 11, 18}; // with identity const int mResI2[] = { 2, 2, 6, 30, 210}; const int pResN2[] = { 2, 1, -2, -7, -14}; // with negate const int mResN2[] = { 2, -2, 6, -30, 210}; const unsigned sa = sizeof(ia) / sizeof(ia[0]); static_assert(sa == sizeof(pResI0) / sizeof(pResI0[0])); // just to be sure static_assert(sa == sizeof(mResI0) / sizeof(mResI0[0])); // just to be sure static_assert(sa == sizeof(pResN0) / sizeof(pResN0[0])); // just to be sure static_assert(sa == sizeof(mResN0) / sizeof(mResN0[0])); // just to be sure static_assert(sa == sizeof(pResI2) / sizeof(pResI2[0])); // just to be sure static_assert(sa == sizeof(mResI2) / sizeof(mResI2[0])); // just to be sure static_assert(sa == sizeof(pResN2) / sizeof(pResN2[0])); // just to be sure static_assert(sa == sizeof(mResN2) / sizeof(mResN2[0])); // just to be sure for (unsigned int i = 0; i < sa; ++i ) { test(Iter(ia), Iter(ia + i), std::plus<>(), identity<>(), 0, pResI0, pResI0 + i); test(Iter(ia), Iter(ia + i), std::multiplies<>(), identity<>(), 0, mResI0, mResI0 + i); test(Iter(ia), Iter(ia + i), std::plus<>(), std::negate<>(), 0, pResN0, pResN0 + i); test(Iter(ia), Iter(ia + i), std::multiplies<>(), std::negate<>(), 0, mResN0, mResN0 + i); test(Iter(ia), Iter(ia + i), std::plus<>(), identity<>(), 2, pResI2, pResI2 + i); test(Iter(ia), Iter(ia + i), std::multiplies<>(), identity<>(), 2, mResI2, mResI2 + i); test(Iter(ia), Iter(ia + i), std::plus<>(), std::negate<>(), 2, pResN2, pResN2 + i); test(Iter(ia), Iter(ia + i), std::multiplies<>(), std::negate<>(), 2, mResN2, mResN2 + i); } } int triangle(int n) { return n*(n+1)/2; } // Basic sanity void basic_tests() { { std::vector<int> v(10); std::fill(v.begin(), v.end(), 3); std::transform_exclusive_scan(v.begin(), v.end(), v.begin(), 50, std::plus<>(), identity<>()); for (size_t i = 0; i < v.size(); ++i) assert(v[i] == 50 + (int) i * 3); } { std::vector<int> v(10); std::iota(v.begin(), v.end(), 0); std::transform_exclusive_scan(v.begin(), v.end(), v.begin(), 30, std::plus<>(), identity<>()); for (size_t i = 0; i < v.size(); ++i) assert(v[i] == 30 + triangle(i-1)); } { std::vector<int> v(10); std::iota(v.begin(), v.end(), 1); std::transform_exclusive_scan(v.begin(), v.end(), v.begin(), 40, std::plus<>(), identity<>()); for (size_t i = 0; i < v.size(); ++i) assert(v[i] == 40 + triangle(i)); } // Make sure that the calculations are done using the init typedef { std::vector<unsigned char> v(10); std::iota(v.begin(), v.end(), 1); std::vector<int> res; std::transform_exclusive_scan(v.begin(), v.end(), std::back_inserter(res), 1, std::multiplies<>(), identity<>()); assert(res.size() == 10); int j = 1; assert(res[0] == 1); for (size_t i = 1; i < res.size(); ++i) { j *= i; assert(res[i] == j); } } } int main() { basic_tests(); // All the iterator categories test<input_iterator <const int*> >(); test<forward_iterator <const int*> >(); test<bidirectional_iterator<const int*> >(); test<random_access_iterator<const int*> >(); test<const int*>(); test< int*>(); } <commit_msg>Add a test with an empty input range - should do nothing<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <numeric> // UNSUPPORTED: c++98, c++03, c++11, c++14 // template<class InputIterator, class OutputIterator, class T, // class BinaryOperation, class UnaryOperation> // OutputIterator transform_exclusive_scan(InputIterator first, InputIterator last, // OutputIterator result, T init, // BinaryOperation binary_op, // UnaryOperation unary_op); #include <numeric> #include <vector> #include <cassert> #include <iostream> #include "test_iterators.h" template <class _Tp = void> struct identity : std::unary_function<_Tp, _Tp> { constexpr const _Tp& operator()(const _Tp& __x) const { return __x;} }; template <> struct identity<void> { template <class _Tp> constexpr auto operator()(_Tp&& __x) const _NOEXCEPT_(noexcept(_VSTD::forward<_Tp>(__x))) -> decltype (_VSTD::forward<_Tp>(__x)) { return _VSTD::forward<_Tp>(__x); } }; template <class Iter1, class BOp, class UOp, class T, class Iter2> void test(Iter1 first, Iter1 last, BOp bop, UOp uop, T init, Iter2 rFirst, Iter2 rLast) { std::vector<typename std::iterator_traits<Iter1>::value_type> v; // Test not in-place std::transform_exclusive_scan(first, last, std::back_inserter(v), init, bop, uop); assert(std::equal(v.begin(), v.end(), rFirst, rLast)); // Test in-place v.clear(); v.assign(first, last); std::transform_exclusive_scan(v.begin(), v.end(), v.begin(), init, bop, uop); assert(std::equal(v.begin(), v.end(), rFirst, rLast)); } template <class Iter> void test() { int ia[] = { 1, 3, 5, 7, 9}; const int pResI0[] = { 0, 1, 4, 9, 16}; // with identity const int mResI0[] = { 0, 0, 0, 0, 0}; const int pResN0[] = { 0, -1, -4, -9, -16}; // with negate const int mResN0[] = { 0, 0, 0, 0, 0}; const int pResI2[] = { 2, 3, 6, 11, 18}; // with identity const int mResI2[] = { 2, 2, 6, 30, 210}; const int pResN2[] = { 2, 1, -2, -7, -14}; // with negate const int mResN2[] = { 2, -2, 6, -30, 210}; const unsigned sa = sizeof(ia) / sizeof(ia[0]); static_assert(sa == sizeof(pResI0) / sizeof(pResI0[0])); // just to be sure static_assert(sa == sizeof(mResI0) / sizeof(mResI0[0])); // just to be sure static_assert(sa == sizeof(pResN0) / sizeof(pResN0[0])); // just to be sure static_assert(sa == sizeof(mResN0) / sizeof(mResN0[0])); // just to be sure static_assert(sa == sizeof(pResI2) / sizeof(pResI2[0])); // just to be sure static_assert(sa == sizeof(mResI2) / sizeof(mResI2[0])); // just to be sure static_assert(sa == sizeof(pResN2) / sizeof(pResN2[0])); // just to be sure static_assert(sa == sizeof(mResN2) / sizeof(mResN2[0])); // just to be sure for (unsigned int i = 0; i < sa; ++i ) { test(Iter(ia), Iter(ia + i), std::plus<>(), identity<>(), 0, pResI0, pResI0 + i); test(Iter(ia), Iter(ia + i), std::multiplies<>(), identity<>(), 0, mResI0, mResI0 + i); test(Iter(ia), Iter(ia + i), std::plus<>(), std::negate<>(), 0, pResN0, pResN0 + i); test(Iter(ia), Iter(ia + i), std::multiplies<>(), std::negate<>(), 0, mResN0, mResN0 + i); test(Iter(ia), Iter(ia + i), std::plus<>(), identity<>(), 2, pResI2, pResI2 + i); test(Iter(ia), Iter(ia + i), std::multiplies<>(), identity<>(), 2, mResI2, mResI2 + i); test(Iter(ia), Iter(ia + i), std::plus<>(), std::negate<>(), 2, pResN2, pResN2 + i); test(Iter(ia), Iter(ia + i), std::multiplies<>(), std::negate<>(), 2, mResN2, mResN2 + i); } } int triangle(int n) { return n*(n+1)/2; } // Basic sanity void basic_tests() { { std::vector<int> v(10); std::fill(v.begin(), v.end(), 3); std::transform_exclusive_scan(v.begin(), v.end(), v.begin(), 50, std::plus<>(), identity<>()); for (size_t i = 0; i < v.size(); ++i) assert(v[i] == 50 + (int) i * 3); } { std::vector<int> v(10); std::iota(v.begin(), v.end(), 0); std::transform_exclusive_scan(v.begin(), v.end(), v.begin(), 30, std::plus<>(), identity<>()); for (size_t i = 0; i < v.size(); ++i) assert(v[i] == 30 + triangle(i-1)); } { std::vector<int> v(10); std::iota(v.begin(), v.end(), 1); std::transform_exclusive_scan(v.begin(), v.end(), v.begin(), 40, std::plus<>(), identity<>()); for (size_t i = 0; i < v.size(); ++i) assert(v[i] == 40 + triangle(i)); } { std::vector<int> v, res; std::transform_exclusive_scan(v.begin(), v.end(), std::back_inserter(res), 40, std::plus<>(), identity<>()); assert(res.empty()); } // Make sure that the calculations are done using the init typedef { std::vector<unsigned char> v(10); std::iota(v.begin(), v.end(), 1); std::vector<int> res; std::transform_exclusive_scan(v.begin(), v.end(), std::back_inserter(res), 1, std::multiplies<>(), identity<>()); assert(res.size() == 10); int j = 1; assert(res[0] == 1); for (size_t i = 1; i < res.size(); ++i) { j *= i; assert(res[i] == j); } } } int main() { basic_tests(); // All the iterator categories test<input_iterator <const int*> >(); test<forward_iterator <const int*> >(); test<bidirectional_iterator<const int*> >(); test<random_access_iterator<const int*> >(); test<const int*>(); test< int*>(); } <|endoftext|>
<commit_before>#include <string> #include <Poco/Exception.h> #include <Poco/XML/XMLWriter.h> #include "xmlui/XmlValueConsumer.h" using namespace std; using namespace Poco; using namespace BeeeOn; using namespace BeeeOn::XmlUI; XmlValueConsumer::XmlValueConsumer(Poco::XML::XMLWriter &writer): m_writer(writer), m_info(NULL) { } void XmlValueConsumer::begin(const TypeInfo &info) { m_info = &info; } const TypeInfo &XmlValueConsumer::info() const { if (m_info == NULL) throw IllegalStateException("info is missing, forgot to call begin()?"); return *m_info; } void XmlValueConsumer::single(const ValueAt &v) { m_writer.dataElement("", "row", "row", to_string(v.atRaw()) + " " + info().asString(v.value())); } void XmlValueConsumer::end() { m_info = NULL; } <commit_msg>XmlValueConsumer: use at().epochTime() instead of atRaw()<commit_after>#include <string> #include <Poco/Exception.h> #include <Poco/XML/XMLWriter.h> #include "xmlui/XmlValueConsumer.h" using namespace std; using namespace Poco; using namespace BeeeOn; using namespace BeeeOn::XmlUI; XmlValueConsumer::XmlValueConsumer(Poco::XML::XMLWriter &writer): m_writer(writer), m_info(NULL) { } void XmlValueConsumer::begin(const TypeInfo &info) { m_info = &info; } const TypeInfo &XmlValueConsumer::info() const { if (m_info == NULL) throw IllegalStateException("info is missing, forgot to call begin()?"); return *m_info; } void XmlValueConsumer::single(const ValueAt &v) { m_writer.dataElement("", "row", "row", to_string(v.at().epochTime()) + " " + info().asString(v.value())); } void XmlValueConsumer::end() { m_info = NULL; } <|endoftext|>
<commit_before>#include <Python.h> #include <numpy/arrayobject.h> #include <math.h> #include <stdlib.h> #include "numpymacros.h" // small value, used to avoid division by zero #define eps 0.0001 // unit vectors used to compute gradient orientation double uu[9] = {1.0000, 0.9397, 0.7660, 0.500, 0.1736, -0.1736, -0.5000, -0.7660, -0.9397}; double vv[9] = {0.0000, 0.3420, 0.6428, 0.8660, 0.9848, 0.9848, 0.8660, 0.6428, 0.3420}; static inline double min(double x, double y) { return (x <= y ? x : y); } static inline double max(double x, double y) { return (x <= y ? y : x); } static inline int min(int x, int y) { return (x <= y ? x : y); } static inline int max(int x, int y) { return (x <= y ? y : x); } // main function: // takes a double color image and a bin size // returns HOG features static PyObject *process(PyObject *self, PyObject *args) { // in NPY_AO *mximage; int sbin; // out NPY_AO *mxfeat; if (!PyArg_ParseTuple(args, "O!i", &PyArray_Type, &mximage, &sbin )) { return NULL; } //TODO fix warnings FARRAY_CHECK(mximage); NDIM_CHECK(mximage, 3); DIM_CHECK(mximage, 2, 3); TYPE_CHECK(mximage, NPY_FLOAT64); double *im = (double *)PyArray_DATA(mximage); npy_intp dims[3]; dims[0] = PyArray_DIM(mximage, 0); dims[1] = PyArray_DIM(mximage, 1); dims[2] = PyArray_DIM(mximage, 2); printf("%d %d %d\n",(int)dims[0],(int)dims[1],(int)dims[2]); // memory for caching orientation histograms & their norms int blocks[2]; blocks[0] = (int)round((double)dims[0]/(double)sbin); blocks[1] = (int)round((double)dims[1]/(double)sbin); double *hist = (double *)calloc(blocks[0]*blocks[1]*18, sizeof(double)); double *norm = (double *)calloc(blocks[0]*blocks[1], sizeof(double)); // memory for HOG features // TODO there's a way to do this in one call npy_intp out[3]; out[0] = max(blocks[0]-2, 0); out[1] = max(blocks[1]-2, 0); out[2] = 27+4; //mxfeat = mxCreateNumericArray(3, out, mxDOUBLE_CLASS, mxREAL); mxfeat = (PyArrayObject*) PyArray_NewFromDescr( &PyArray_Type, PyArray_DescrFromType(PyArray_FLOAT64), 3, out, NULL, NULL, NPY_F_CONTIGUOUS, NULL); //(PyArrayObject *)PyArray_SimpleNew(3, out, NPY_FLOAT64); double *feat = (double *)PyArray_DATA(mxfeat); int visible[2]; visible[0] = blocks[0]*sbin; visible[1] = blocks[1]*sbin; for (int x = 1; x < visible[1]-1; x++) { for (int y = 1; y < visible[0]-1; y++) { // first color channel double *s = im + min(x, dims[1]-2)*dims[0] + min(y, dims[0]-2); double dy = *(s+1) - *(s-1); double dx = *(s+dims[0]) - *(s-dims[0]); double v = dx*dx + dy*dy; // second color channel s += dims[0]*dims[1]; double dy2 = *(s+1) - *(s-1); double dx2 = *(s+dims[0]) - *(s-dims[0]); double v2 = dx2*dx2 + dy2*dy2; // third color channel s += dims[0]*dims[1]; double dy3 = *(s+1) - *(s-1); double dx3 = *(s+dims[0]) - *(s-dims[0]); double v3 = dx3*dx3 + dy3*dy3; // pick channel with strongest gradient if (v2 > v) { v = v2; dx = dx2; dy = dy2; } if (v3 > v) { v = v3; dx = dx3; dy = dy3; } // snap to one of 18 orientations double best_dot = 0; int best_o = 0; for (int o = 0; o < 9; o++) { double dot = uu[o]*dx + vv[o]*dy; if (dot > best_dot) { best_dot = dot; best_o = o; } else if (-dot > best_dot) { best_dot = -dot; best_o = o+9; } } // add to 4 histograms around pixel using linear interpolation double xp = ((double)x+0.5)/(double)sbin - 0.5; double yp = ((double)y+0.5)/(double)sbin - 0.5; int ixp = (int)floor(xp); int iyp = (int)floor(yp); double vx0 = xp-ixp; double vy0 = yp-iyp; double vx1 = 1.0-vx0; double vy1 = 1.0-vy0; v = sqrt(v); if (ixp >= 0 && iyp >= 0) { *(hist + ixp*blocks[0] + iyp + best_o*blocks[0]*blocks[1]) += vx1*vy1*v; } if (ixp+1 < blocks[1] && iyp >= 0) { *(hist + (ixp+1)*blocks[0] + iyp + best_o*blocks[0]*blocks[1]) += vx0*vy1*v; } if (ixp >= 0 && iyp+1 < blocks[0]) { *(hist + ixp*blocks[0] + (iyp+1) + best_o*blocks[0]*blocks[1]) += vx1*vy0*v; } if (ixp+1 < blocks[1] && iyp+1 < blocks[0]) { *(hist + (ixp+1)*blocks[0] + (iyp+1) + best_o*blocks[0]*blocks[1]) += vx0*vy0*v; } } } // compute energy in each block by summing over orientations for (int o = 0; o < 9; o++) { double *src1 = hist + o*blocks[0]*blocks[1]; double *src2 = hist + (o+9)*blocks[0]*blocks[1]; double *dst = norm; double *end = norm + blocks[1]*blocks[0]; while (dst < end) { *(dst++) += (*src1 + *src2) * (*src1 + *src2); src1++; src2++; } } // compute features for (int x = 0; x < out[1]; x++) { for (int y = 0; y < out[0]; y++) { double *dst = feat + x*out[0] + y; double *src, *p, n1, n2, n3, n4; p = norm + (x+1)*blocks[0] + y+1; n1 = 1.0 / sqrt(*p + *(p+1) + *(p+blocks[0]) + *(p+blocks[0]+1) + eps); p = norm + (x+1)*blocks[0] + y; n2 = 1.0 / sqrt(*p + *(p+1) + *(p+blocks[0]) + *(p+blocks[0]+1) + eps); p = norm + x*blocks[0] + y+1; n3 = 1.0 / sqrt(*p + *(p+1) + *(p+blocks[0]) + *(p+blocks[0]+1) + eps); p = norm + x*blocks[0] + y; n4 = 1.0 / sqrt(*p + *(p+1) + *(p+blocks[0]) + *(p+blocks[0]+1) + eps); double t1 = 0; double t2 = 0; double t3 = 0; double t4 = 0; // contrast-sensitive features src = hist + (x+1)*blocks[0] + (y+1); for (int o = 0; o < 18; o++) { double h1 = min(*src * n1, 0.2); double h2 = min(*src * n2, 0.2); double h3 = min(*src * n3, 0.2); double h4 = min(*src * n4, 0.2); *dst = 0.5 * (h1 + h2 + h3 + h4); t1 += h1; t2 += h2; t3 += h3; t4 += h4; dst += out[0]*out[1]; src += blocks[0]*blocks[1]; } // contrast-insensitive features src = hist + (x+1)*blocks[0] + (y+1); for (int o = 0; o < 9; o++) { double sum = *src + *(src + 9*blocks[0]*blocks[1]); double h1 = min(sum * n1, 0.2); double h2 = min(sum * n2, 0.2); double h3 = min(sum * n3, 0.2); double h4 = min(sum * n4, 0.2); *dst = 0.5 * (h1 + h2 + h3 + h4); dst += out[0]*out[1]; src += blocks[0]*blocks[1]; } // texture features *dst = 0.2357 * t1; dst += out[0]*out[1]; *dst = 0.2357 * t2; dst += out[0]*out[1]; *dst = 0.2357 * t3; dst += out[0]*out[1]; *dst = 0.2357 * t4; } } // hack //PyArray_FLAGS(mxfeat) |= NPY_F_CONTIGUOUS; //PyArray_FLAGS(mxfeat) &= ~NPY_C_CONTIGUOUS; free(hist); free(norm); return PyArray_Return(mxfeat);//Py_BuildValue("N", mxfeat); } static PyMethodDef features_pedro_py_methods[] = { {"process", process, METH_VARARGS, "process"}, {NULL, NULL, 0, NULL} /* sentinel*/ }; PyMODINIT_FUNC initfeatures_pedro_py() { Py_InitModule("features_pedro_py", features_pedro_py_methods); import_array(); } <commit_msg>don't print info<commit_after>#include <Python.h> #include <numpy/arrayobject.h> #include <math.h> #include <stdlib.h> #include "numpymacros.h" // small value, used to avoid division by zero #define eps 0.0001 // unit vectors used to compute gradient orientation double uu[9] = {1.0000, 0.9397, 0.7660, 0.500, 0.1736, -0.1736, -0.5000, -0.7660, -0.9397}; double vv[9] = {0.0000, 0.3420, 0.6428, 0.8660, 0.9848, 0.9848, 0.8660, 0.6428, 0.3420}; static inline double min(double x, double y) { return (x <= y ? x : y); } static inline double max(double x, double y) { return (x <= y ? y : x); } static inline int min(int x, int y) { return (x <= y ? x : y); } static inline int max(int x, int y) { return (x <= y ? y : x); } // main function: // takes a double color image and a bin size // returns HOG features static PyObject *process(PyObject *self, PyObject *args) { // in NPY_AO *mximage; int sbin; // out NPY_AO *mxfeat; if (!PyArg_ParseTuple(args, "O!i", &PyArray_Type, &mximage, &sbin )) { return NULL; } //TODO fix warnings FARRAY_CHECK(mximage); NDIM_CHECK(mximage, 3); DIM_CHECK(mximage, 2, 3); TYPE_CHECK(mximage, NPY_FLOAT64); double *im = (double *)PyArray_DATA(mximage); npy_intp dims[3]; dims[0] = PyArray_DIM(mximage, 0); dims[1] = PyArray_DIM(mximage, 1); dims[2] = PyArray_DIM(mximage, 2); //printf("%d %d %d\n",(int)dims[0],(int)dims[1],(int)dims[2]); // memory for caching orientation histograms & their norms int blocks[2]; blocks[0] = (int)round((double)dims[0]/(double)sbin); blocks[1] = (int)round((double)dims[1]/(double)sbin); double *hist = (double *)calloc(blocks[0]*blocks[1]*18, sizeof(double)); double *norm = (double *)calloc(blocks[0]*blocks[1], sizeof(double)); // memory for HOG features // TODO there's a way to do this in one call npy_intp out[3]; out[0] = max(blocks[0]-2, 0); out[1] = max(blocks[1]-2, 0); out[2] = 27+4; //mxfeat = mxCreateNumericArray(3, out, mxDOUBLE_CLASS, mxREAL); mxfeat = (PyArrayObject*) PyArray_NewFromDescr( &PyArray_Type, PyArray_DescrFromType(PyArray_FLOAT64), 3, out, NULL, NULL, NPY_F_CONTIGUOUS, NULL); //(PyArrayObject *)PyArray_SimpleNew(3, out, NPY_FLOAT64); double *feat = (double *)PyArray_DATA(mxfeat); int visible[2]; visible[0] = blocks[0]*sbin; visible[1] = blocks[1]*sbin; for (int x = 1; x < visible[1]-1; x++) { for (int y = 1; y < visible[0]-1; y++) { // first color channel double *s = im + min(x, dims[1]-2)*dims[0] + min(y, dims[0]-2); double dy = *(s+1) - *(s-1); double dx = *(s+dims[0]) - *(s-dims[0]); double v = dx*dx + dy*dy; // second color channel s += dims[0]*dims[1]; double dy2 = *(s+1) - *(s-1); double dx2 = *(s+dims[0]) - *(s-dims[0]); double v2 = dx2*dx2 + dy2*dy2; // third color channel s += dims[0]*dims[1]; double dy3 = *(s+1) - *(s-1); double dx3 = *(s+dims[0]) - *(s-dims[0]); double v3 = dx3*dx3 + dy3*dy3; // pick channel with strongest gradient if (v2 > v) { v = v2; dx = dx2; dy = dy2; } if (v3 > v) { v = v3; dx = dx3; dy = dy3; } // snap to one of 18 orientations double best_dot = 0; int best_o = 0; for (int o = 0; o < 9; o++) { double dot = uu[o]*dx + vv[o]*dy; if (dot > best_dot) { best_dot = dot; best_o = o; } else if (-dot > best_dot) { best_dot = -dot; best_o = o+9; } } // add to 4 histograms around pixel using linear interpolation double xp = ((double)x+0.5)/(double)sbin - 0.5; double yp = ((double)y+0.5)/(double)sbin - 0.5; int ixp = (int)floor(xp); int iyp = (int)floor(yp); double vx0 = xp-ixp; double vy0 = yp-iyp; double vx1 = 1.0-vx0; double vy1 = 1.0-vy0; v = sqrt(v); if (ixp >= 0 && iyp >= 0) { *(hist + ixp*blocks[0] + iyp + best_o*blocks[0]*blocks[1]) += vx1*vy1*v; } if (ixp+1 < blocks[1] && iyp >= 0) { *(hist + (ixp+1)*blocks[0] + iyp + best_o*blocks[0]*blocks[1]) += vx0*vy1*v; } if (ixp >= 0 && iyp+1 < blocks[0]) { *(hist + ixp*blocks[0] + (iyp+1) + best_o*blocks[0]*blocks[1]) += vx1*vy0*v; } if (ixp+1 < blocks[1] && iyp+1 < blocks[0]) { *(hist + (ixp+1)*blocks[0] + (iyp+1) + best_o*blocks[0]*blocks[1]) += vx0*vy0*v; } } } // compute energy in each block by summing over orientations for (int o = 0; o < 9; o++) { double *src1 = hist + o*blocks[0]*blocks[1]; double *src2 = hist + (o+9)*blocks[0]*blocks[1]; double *dst = norm; double *end = norm + blocks[1]*blocks[0]; while (dst < end) { *(dst++) += (*src1 + *src2) * (*src1 + *src2); src1++; src2++; } } // compute features for (int x = 0; x < out[1]; x++) { for (int y = 0; y < out[0]; y++) { double *dst = feat + x*out[0] + y; double *src, *p, n1, n2, n3, n4; p = norm + (x+1)*blocks[0] + y+1; n1 = 1.0 / sqrt(*p + *(p+1) + *(p+blocks[0]) + *(p+blocks[0]+1) + eps); p = norm + (x+1)*blocks[0] + y; n2 = 1.0 / sqrt(*p + *(p+1) + *(p+blocks[0]) + *(p+blocks[0]+1) + eps); p = norm + x*blocks[0] + y+1; n3 = 1.0 / sqrt(*p + *(p+1) + *(p+blocks[0]) + *(p+blocks[0]+1) + eps); p = norm + x*blocks[0] + y; n4 = 1.0 / sqrt(*p + *(p+1) + *(p+blocks[0]) + *(p+blocks[0]+1) + eps); double t1 = 0; double t2 = 0; double t3 = 0; double t4 = 0; // contrast-sensitive features src = hist + (x+1)*blocks[0] + (y+1); for (int o = 0; o < 18; o++) { double h1 = min(*src * n1, 0.2); double h2 = min(*src * n2, 0.2); double h3 = min(*src * n3, 0.2); double h4 = min(*src * n4, 0.2); *dst = 0.5 * (h1 + h2 + h3 + h4); t1 += h1; t2 += h2; t3 += h3; t4 += h4; dst += out[0]*out[1]; src += blocks[0]*blocks[1]; } // contrast-insensitive features src = hist + (x+1)*blocks[0] + (y+1); for (int o = 0; o < 9; o++) { double sum = *src + *(src + 9*blocks[0]*blocks[1]); double h1 = min(sum * n1, 0.2); double h2 = min(sum * n2, 0.2); double h3 = min(sum * n3, 0.2); double h4 = min(sum * n4, 0.2); *dst = 0.5 * (h1 + h2 + h3 + h4); dst += out[0]*out[1]; src += blocks[0]*blocks[1]; } // texture features *dst = 0.2357 * t1; dst += out[0]*out[1]; *dst = 0.2357 * t2; dst += out[0]*out[1]; *dst = 0.2357 * t3; dst += out[0]*out[1]; *dst = 0.2357 * t4; } } // hack //PyArray_FLAGS(mxfeat) |= NPY_F_CONTIGUOUS; //PyArray_FLAGS(mxfeat) &= ~NPY_C_CONTIGUOUS; free(hist); free(norm); return PyArray_Return(mxfeat);//Py_BuildValue("N", mxfeat); } static PyMethodDef features_pedro_py_methods[] = { {"process", process, METH_VARARGS, "process"}, {NULL, NULL, 0, NULL} /* sentinel*/ }; PyMODINIT_FUNC initfeatures_pedro_py() { Py_InitModule("features_pedro_py", features_pedro_py_methods); import_array(); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm 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 "results.hpp" #include "impl/async_query.hpp" #include "impl/realm_coordinator.hpp" #include "object_store.hpp" #include <stdexcept> using namespace realm; #ifdef __has_cpp_attribute #define REALM_HAS_CCP_ATTRIBUTE(attr) __has_cpp_attribute(attr) #else #define REALM_HAS_CCP_ATTRIBUTE(attr) 0 #endif #if REALM_HAS_CCP_ATTRIBUTE(clang::fallthrough) #define REALM_FALLTHROUGH [[clang::fallthrough]] #else #define REALM_FALLTHROUGH #endif Results::Results(SharedRealm r, const ObjectSchema &o, Query q, SortOrder s) : m_realm(std::move(r)) , m_object_schema(&o) , m_query(std::move(q)) , m_table(m_query.get_table().get()) , m_sort(std::move(s)) , m_mode(Mode::Query) { } Results::Results(SharedRealm r, const ObjectSchema &o, Table& table) : m_realm(std::move(r)) , m_object_schema(&o) , m_table(&table) , m_mode(Mode::Table) { } Results::~Results() { if (m_background_query) { m_background_query->unregister(); } } void Results::validate_read() const { if (m_realm) m_realm->verify_thread(); if (m_table && !m_table->is_attached()) throw InvalidatedException(); if (m_mode == Mode::TableView && !m_table_view.is_attached()) throw InvalidatedException(); } void Results::validate_write() const { validate_read(); if (!m_realm || !m_realm->is_in_transaction()) throw InvalidTransactionException("Must be in a write transaction"); } void Results::set_live(bool live) { if (!live && m_mode == Mode::Table) { m_query = m_table->where(); m_mode = Mode::Query; } update_tableview(); m_live = live; } size_t Results::size() { validate_read(); switch (m_mode) { case Mode::Empty: return 0; case Mode::Table: return m_table->size(); case Mode::Query: return m_query.count(); case Mode::TableView: update_tableview(); return m_table_view.size(); } REALM_UNREACHABLE(); } StringData Results::get_object_type() const noexcept { return get_object_schema().name; } RowExpr Results::get(size_t row_ndx) { validate_read(); switch (m_mode) { case Mode::Empty: break; case Mode::Table: if (row_ndx < m_table->size()) return m_table->get(row_ndx); break; case Mode::Query: case Mode::TableView: update_tableview(); if (row_ndx < m_table_view.size()) return (!m_live && !m_table_view.is_row_attached(row_ndx)) ? RowExpr() : m_table_view.get(row_ndx); break; } throw OutOfBoundsIndexException{row_ndx, size()}; } util::Optional<RowExpr> Results::first() { validate_read(); switch (m_mode) { case Mode::Empty: return none; case Mode::Table: return m_table->size() == 0 ? util::none : util::make_optional(m_table->front()); case Mode::Query: case Mode::TableView: update_tableview(); return m_table_view.size() == 0 ? util::none : util::make_optional(m_table_view.front()); } REALM_UNREACHABLE(); } util::Optional<RowExpr> Results::last() { validate_read(); switch (m_mode) { case Mode::Empty: return none; case Mode::Table: return m_table->size() == 0 ? util::none : util::make_optional(m_table->back()); case Mode::Query: case Mode::TableView: update_tableview(); return m_table_view.size() == 0 ? util::none : util::make_optional(m_table_view.back()); } REALM_UNREACHABLE(); } void Results::update_tableview() { validate_read(); switch (m_mode) { case Mode::Empty: case Mode::Table: return; case Mode::Query: m_table_view = m_query.find_all(); if (m_sort) { m_table_view.sort(m_sort.columnIndices, m_sort.ascending); } m_mode = Mode::TableView; break; case Mode::TableView: if (!m_live) { return; } if (!m_background_query && !m_realm->is_in_transaction() && m_realm->can_deliver_notifications()) { m_background_query = std::make_shared<_impl::AsyncQuery>(*this); _impl::RealmCoordinator::register_query(m_background_query); } m_has_used_table_view = true; m_table_view.sync_if_needed(); break; } } size_t Results::index_of(Row const& row) { validate_read(); if (!row) { throw DetatchedAccessorException{}; } if (m_table && row.get_table() != m_table) { throw IncorrectTableException(m_object_schema->name, ObjectStore::object_type_for_table_name(row.get_table()->get_name()), "Attempting to get the index of a Row of the wrong type" ); } return index_of(row.get_index()); } size_t Results::index_of(size_t row_ndx) { validate_read(); switch (m_mode) { case Mode::Empty: return not_found; case Mode::Table: return row_ndx; case Mode::Query: case Mode::TableView: update_tableview(); return m_table_view.find_by_source_ndx(row_ndx); } REALM_UNREACHABLE(); } template<typename Int, typename Float, typename Double, typename DateTime> util::Optional<Mixed> Results::aggregate(size_t column, bool return_none_for_empty, Int agg_int, Float agg_float, Double agg_double, DateTime agg_datetime) { validate_read(); if (!m_table) return none; if (column > m_table->get_column_count()) throw OutOfBoundsIndexException{column, m_table->get_column_count()}; auto do_agg = [&](auto const& getter) -> util::Optional<Mixed> { switch (m_mode) { case Mode::Empty: return none; case Mode::Table: if (return_none_for_empty && m_table->size() == 0) return none; return util::Optional<Mixed>(getter(*m_table)); case Mode::Query: case Mode::TableView: this->update_tableview(); if (return_none_for_empty && m_table_view.size() == 0) return none; return util::Optional<Mixed>(getter(m_table_view)); } REALM_UNREACHABLE(); }; switch (m_table->get_column_type(column)) { case type_DateTime: return do_agg(agg_datetime); case type_Double: return do_agg(agg_double); case type_Float: return do_agg(agg_float); case type_Int: return do_agg(agg_int); default: throw UnsupportedColumnTypeException{column, m_table}; } } util::Optional<Mixed> Results::max(size_t column) { return aggregate(column, true, [=](auto const& table) { return table.maximum_int(column); }, [=](auto const& table) { return table.maximum_float(column); }, [=](auto const& table) { return table.maximum_double(column); }, [=](auto const& table) { return table.maximum_datetime(column); }); } util::Optional<Mixed> Results::min(size_t column) { return aggregate(column, true, [=](auto const& table) { return table.minimum_int(column); }, [=](auto const& table) { return table.minimum_float(column); }, [=](auto const& table) { return table.minimum_double(column); }, [=](auto const& table) { return table.minimum_datetime(column); }); } util::Optional<Mixed> Results::sum(size_t column) { return aggregate(column, false, [=](auto const& table) { return table.sum_int(column); }, [=](auto const& table) { return table.sum_float(column); }, [=](auto const& table) { return table.sum_double(column); }, [=](auto const&) -> util::None { throw UnsupportedColumnTypeException{column, m_table}; }); } util::Optional<Mixed> Results::average(size_t column) { return aggregate(column, true, [=](auto const& table) { return table.average_int(column); }, [=](auto const& table) { return table.average_float(column); }, [=](auto const& table) { return table.average_double(column); }, [=](auto const&) -> util::None { throw UnsupportedColumnTypeException{column, m_table}; }); } void Results::clear() { switch (m_mode) { case Mode::Empty: return; case Mode::Table: validate_write(); m_table->clear(); break; case Mode::Query: // Not using Query:remove() because building the tableview and // clearing it is actually significantly faster case Mode::TableView: validate_write(); update_tableview(); m_table_view.clear(RemoveMode::unordered); break; } } Query Results::get_query() const { validate_read(); switch (m_mode) { case Mode::Empty: case Mode::Query: return m_query; case Mode::TableView: return m_table_view.get_query(); case Mode::Table: return m_table->where(); } REALM_UNREACHABLE(); } TableView Results::get_tableview() { validate_read(); switch (m_mode) { case Mode::Empty: return {}; case Mode::Query: case Mode::TableView: update_tableview(); return m_table_view; case Mode::Table: return m_table->where().find_all(); } REALM_UNREACHABLE(); } Results Results::sort(realm::SortOrder&& sort) const { return Results(m_realm, get_object_schema(), get_query(), std::move(sort)); } Results Results::filter(Query&& q) const { return Results(m_realm, get_object_schema(), get_query().and_query(std::move(q)), get_sort()); } AsyncQueryCancelationToken Results::async(std::function<void (std::exception_ptr)> target) { if (m_realm->config().read_only) { throw InvalidTransactionException("Cannot create asynchronous query for read-only Realms"); } if (m_realm->is_in_transaction()) { throw InvalidTransactionException("Cannot create asynchronous query while in a write transaction"); } if (!m_background_query) { m_background_query = std::make_shared<_impl::AsyncQuery>(*this); _impl::RealmCoordinator::register_query(m_background_query); } return {m_background_query, m_background_query->add_callback(std::move(target))}; } void Results::Internal::set_table_view(Results& results, realm::TableView &&tv) { // If the previous TableView was never actually used, then stop generating // new ones until the user actually uses the Results object again if (results.m_mode == Mode::TableView) { results.m_wants_background_updates = results.m_has_used_table_view; } results.m_table_view = std::move(tv); results.m_mode = Mode::TableView; results.m_has_used_table_view = false; REALM_ASSERT(results.m_table_view.is_in_sync()); } Results::UnsupportedColumnTypeException::UnsupportedColumnTypeException(size_t column, const Table* table) : std::runtime_error((std::string)"Operation not supported on '" + table->get_column_name(column).data() + "' columns") , column_index(column) , column_name(table->get_column_name(column)) , column_type(table->get_column_type(column)) { } AsyncQueryCancelationToken::AsyncQueryCancelationToken(std::shared_ptr<_impl::AsyncQuery> query, size_t token) : m_query(std::move(query)), m_token(token) { } AsyncQueryCancelationToken::~AsyncQueryCancelationToken() { // m_query itself (and not just the pointed-to thing) needs to be accessed // atomically to ensure that there are no data races when the token is // destroyed after being modified on a different thread. // This is needed despite the token not being thread-safe in general as // users find it very surpringing for obj-c objects to care about what // thread they are deallocated on. if (auto query = m_query.exchange({})) { query->remove_callback(m_token); } } AsyncQueryCancelationToken::AsyncQueryCancelationToken(AsyncQueryCancelationToken&& rgt) = default; AsyncQueryCancelationToken& AsyncQueryCancelationToken::operator=(realm::AsyncQueryCancelationToken&& rgt) { if (this != &rgt) { if (auto query = m_query.exchange({})) { query->remove_callback(m_token); } m_query = std::move(rgt.m_query); m_token = rgt.m_token; } return *this; } <commit_msg>Add validate_read() check to Results::set_live()<commit_after>//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm 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 "results.hpp" #include "impl/async_query.hpp" #include "impl/realm_coordinator.hpp" #include "object_store.hpp" #include <stdexcept> using namespace realm; #ifdef __has_cpp_attribute #define REALM_HAS_CCP_ATTRIBUTE(attr) __has_cpp_attribute(attr) #else #define REALM_HAS_CCP_ATTRIBUTE(attr) 0 #endif #if REALM_HAS_CCP_ATTRIBUTE(clang::fallthrough) #define REALM_FALLTHROUGH [[clang::fallthrough]] #else #define REALM_FALLTHROUGH #endif Results::Results(SharedRealm r, const ObjectSchema &o, Query q, SortOrder s) : m_realm(std::move(r)) , m_object_schema(&o) , m_query(std::move(q)) , m_table(m_query.get_table().get()) , m_sort(std::move(s)) , m_mode(Mode::Query) { } Results::Results(SharedRealm r, const ObjectSchema &o, Table& table) : m_realm(std::move(r)) , m_object_schema(&o) , m_table(&table) , m_mode(Mode::Table) { } Results::~Results() { if (m_background_query) { m_background_query->unregister(); } } void Results::validate_read() const { if (m_realm) m_realm->verify_thread(); if (m_table && !m_table->is_attached()) throw InvalidatedException(); if (m_mode == Mode::TableView && !m_table_view.is_attached()) throw InvalidatedException(); } void Results::validate_write() const { validate_read(); if (!m_realm || !m_realm->is_in_transaction()) throw InvalidTransactionException("Must be in a write transaction"); } void Results::set_live(bool live) { validate_read(); if (!live && m_mode == Mode::Table) { m_query = m_table->where(); m_mode = Mode::Query; } update_tableview(); m_live = live; } size_t Results::size() { validate_read(); switch (m_mode) { case Mode::Empty: return 0; case Mode::Table: return m_table->size(); case Mode::Query: return m_query.count(); case Mode::TableView: update_tableview(); return m_table_view.size(); } REALM_UNREACHABLE(); } StringData Results::get_object_type() const noexcept { return get_object_schema().name; } RowExpr Results::get(size_t row_ndx) { validate_read(); switch (m_mode) { case Mode::Empty: break; case Mode::Table: if (row_ndx < m_table->size()) return m_table->get(row_ndx); break; case Mode::Query: case Mode::TableView: update_tableview(); if (row_ndx < m_table_view.size()) return (!m_live && !m_table_view.is_row_attached(row_ndx)) ? RowExpr() : m_table_view.get(row_ndx); break; } throw OutOfBoundsIndexException{row_ndx, size()}; } util::Optional<RowExpr> Results::first() { validate_read(); switch (m_mode) { case Mode::Empty: return none; case Mode::Table: return m_table->size() == 0 ? util::none : util::make_optional(m_table->front()); case Mode::Query: case Mode::TableView: update_tableview(); return m_table_view.size() == 0 ? util::none : util::make_optional(m_table_view.front()); } REALM_UNREACHABLE(); } util::Optional<RowExpr> Results::last() { validate_read(); switch (m_mode) { case Mode::Empty: return none; case Mode::Table: return m_table->size() == 0 ? util::none : util::make_optional(m_table->back()); case Mode::Query: case Mode::TableView: update_tableview(); return m_table_view.size() == 0 ? util::none : util::make_optional(m_table_view.back()); } REALM_UNREACHABLE(); } void Results::update_tableview() { validate_read(); switch (m_mode) { case Mode::Empty: case Mode::Table: return; case Mode::Query: m_table_view = m_query.find_all(); if (m_sort) { m_table_view.sort(m_sort.columnIndices, m_sort.ascending); } m_mode = Mode::TableView; break; case Mode::TableView: if (!m_live) { return; } if (!m_background_query && !m_realm->is_in_transaction() && m_realm->can_deliver_notifications()) { m_background_query = std::make_shared<_impl::AsyncQuery>(*this); _impl::RealmCoordinator::register_query(m_background_query); } m_has_used_table_view = true; m_table_view.sync_if_needed(); break; } } size_t Results::index_of(Row const& row) { validate_read(); if (!row) { throw DetatchedAccessorException{}; } if (m_table && row.get_table() != m_table) { throw IncorrectTableException(m_object_schema->name, ObjectStore::object_type_for_table_name(row.get_table()->get_name()), "Attempting to get the index of a Row of the wrong type" ); } return index_of(row.get_index()); } size_t Results::index_of(size_t row_ndx) { validate_read(); switch (m_mode) { case Mode::Empty: return not_found; case Mode::Table: return row_ndx; case Mode::Query: case Mode::TableView: update_tableview(); return m_table_view.find_by_source_ndx(row_ndx); } REALM_UNREACHABLE(); } template<typename Int, typename Float, typename Double, typename DateTime> util::Optional<Mixed> Results::aggregate(size_t column, bool return_none_for_empty, Int agg_int, Float agg_float, Double agg_double, DateTime agg_datetime) { validate_read(); if (!m_table) return none; if (column > m_table->get_column_count()) throw OutOfBoundsIndexException{column, m_table->get_column_count()}; auto do_agg = [&](auto const& getter) -> util::Optional<Mixed> { switch (m_mode) { case Mode::Empty: return none; case Mode::Table: if (return_none_for_empty && m_table->size() == 0) return none; return util::Optional<Mixed>(getter(*m_table)); case Mode::Query: case Mode::TableView: this->update_tableview(); if (return_none_for_empty && m_table_view.size() == 0) return none; return util::Optional<Mixed>(getter(m_table_view)); } REALM_UNREACHABLE(); }; switch (m_table->get_column_type(column)) { case type_DateTime: return do_agg(agg_datetime); case type_Double: return do_agg(agg_double); case type_Float: return do_agg(agg_float); case type_Int: return do_agg(agg_int); default: throw UnsupportedColumnTypeException{column, m_table}; } } util::Optional<Mixed> Results::max(size_t column) { return aggregate(column, true, [=](auto const& table) { return table.maximum_int(column); }, [=](auto const& table) { return table.maximum_float(column); }, [=](auto const& table) { return table.maximum_double(column); }, [=](auto const& table) { return table.maximum_datetime(column); }); } util::Optional<Mixed> Results::min(size_t column) { return aggregate(column, true, [=](auto const& table) { return table.minimum_int(column); }, [=](auto const& table) { return table.minimum_float(column); }, [=](auto const& table) { return table.minimum_double(column); }, [=](auto const& table) { return table.minimum_datetime(column); }); } util::Optional<Mixed> Results::sum(size_t column) { return aggregate(column, false, [=](auto const& table) { return table.sum_int(column); }, [=](auto const& table) { return table.sum_float(column); }, [=](auto const& table) { return table.sum_double(column); }, [=](auto const&) -> util::None { throw UnsupportedColumnTypeException{column, m_table}; }); } util::Optional<Mixed> Results::average(size_t column) { return aggregate(column, true, [=](auto const& table) { return table.average_int(column); }, [=](auto const& table) { return table.average_float(column); }, [=](auto const& table) { return table.average_double(column); }, [=](auto const&) -> util::None { throw UnsupportedColumnTypeException{column, m_table}; }); } void Results::clear() { switch (m_mode) { case Mode::Empty: return; case Mode::Table: validate_write(); m_table->clear(); break; case Mode::Query: // Not using Query:remove() because building the tableview and // clearing it is actually significantly faster case Mode::TableView: validate_write(); update_tableview(); m_table_view.clear(RemoveMode::unordered); break; } } Query Results::get_query() const { validate_read(); switch (m_mode) { case Mode::Empty: case Mode::Query: return m_query; case Mode::TableView: return m_table_view.get_query(); case Mode::Table: return m_table->where(); } REALM_UNREACHABLE(); } TableView Results::get_tableview() { validate_read(); switch (m_mode) { case Mode::Empty: return {}; case Mode::Query: case Mode::TableView: update_tableview(); return m_table_view; case Mode::Table: return m_table->where().find_all(); } REALM_UNREACHABLE(); } Results Results::sort(realm::SortOrder&& sort) const { return Results(m_realm, get_object_schema(), get_query(), std::move(sort)); } Results Results::filter(Query&& q) const { return Results(m_realm, get_object_schema(), get_query().and_query(std::move(q)), get_sort()); } AsyncQueryCancelationToken Results::async(std::function<void (std::exception_ptr)> target) { if (m_realm->config().read_only) { throw InvalidTransactionException("Cannot create asynchronous query for read-only Realms"); } if (m_realm->is_in_transaction()) { throw InvalidTransactionException("Cannot create asynchronous query while in a write transaction"); } if (!m_background_query) { m_background_query = std::make_shared<_impl::AsyncQuery>(*this); _impl::RealmCoordinator::register_query(m_background_query); } return {m_background_query, m_background_query->add_callback(std::move(target))}; } void Results::Internal::set_table_view(Results& results, realm::TableView &&tv) { // If the previous TableView was never actually used, then stop generating // new ones until the user actually uses the Results object again if (results.m_mode == Mode::TableView) { results.m_wants_background_updates = results.m_has_used_table_view; } results.m_table_view = std::move(tv); results.m_mode = Mode::TableView; results.m_has_used_table_view = false; REALM_ASSERT(results.m_table_view.is_in_sync()); } Results::UnsupportedColumnTypeException::UnsupportedColumnTypeException(size_t column, const Table* table) : std::runtime_error((std::string)"Operation not supported on '" + table->get_column_name(column).data() + "' columns") , column_index(column) , column_name(table->get_column_name(column)) , column_type(table->get_column_type(column)) { } AsyncQueryCancelationToken::AsyncQueryCancelationToken(std::shared_ptr<_impl::AsyncQuery> query, size_t token) : m_query(std::move(query)), m_token(token) { } AsyncQueryCancelationToken::~AsyncQueryCancelationToken() { // m_query itself (and not just the pointed-to thing) needs to be accessed // atomically to ensure that there are no data races when the token is // destroyed after being modified on a different thread. // This is needed despite the token not being thread-safe in general as // users find it very surpringing for obj-c objects to care about what // thread they are deallocated on. if (auto query = m_query.exchange({})) { query->remove_callback(m_token); } } AsyncQueryCancelationToken::AsyncQueryCancelationToken(AsyncQueryCancelationToken&& rgt) = default; AsyncQueryCancelationToken& AsyncQueryCancelationToken::operator=(realm::AsyncQueryCancelationToken&& rgt) { if (this != &rgt) { if (auto query = m_query.exchange({})) { query->remove_callback(m_token); } m_query = std::move(rgt.m_query); m_token = rgt.m_token; } return *this; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: numrule.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: cmc $ $Date: 2002-11-18 14:02:33 $ * * 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 _NUMRULE_HXX #define _NUMRULE_HXX #ifndef _LINK_HXX //autogen #include <tools/link.hxx> #endif #ifndef _SV_GEN_HXX //autogen wg. Size #include <tools/gen.hxx> #endif #ifndef _STRING_HXX //autogen #include <tools/string.hxx> #endif #ifndef _SVX_SVXENUM_HXX //autogen #include <svx/svxenum.hxx> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #ifndef _CALBCK_HXX #include <calbck.hxx> #endif #ifndef _ERRHDL_HXX #include <errhdl.hxx> // Fuer die inline-ASSERTs #endif #ifndef _SWERROR_H #include <error.h> // Fuer die inline-ASSERTs #endif #ifndef _SVX_NUMITEM_HXX #include <svx/numitem.hxx> #endif class Font; class SvxBrushItem; class SvxNumRule; class SwCharFmt; class SwDoc; class SwFmtVertOrient; class SwNodeNum; class SwTxtNode; extern char __FAR_DATA sOutlineStr[]; // SWG-Filter inline BYTE GetRealLevel( const BYTE nLvl ) { return nLvl & (NO_NUMLEVEL - 1); } const sal_Unicode cBulletChar = 0x2022; // Charakter fuer Aufzaehlungen class SwNumFmt : public SvxNumberFormat, public SwClient { SwFmtVertOrient* pVertOrient; void UpdateNumNodes( SwDoc* pDoc ); virtual void NotifyGraphicArrived(); public: SwNumFmt(); SwNumFmt( const SwNumFmt& ); SwNumFmt( const SvxNumberFormat&, SwDoc* pDoc); virtual ~SwNumFmt(); SwNumFmt& operator=( const SwNumFmt& ); BOOL operator==( const SwNumFmt& ) const; BOOL operator!=( const SwNumFmt& r ) const { return !(*this == r); } const Graphic* GetGraphic() const; SwCharFmt* GetCharFmt() const { return (SwCharFmt*)pRegisteredIn; } void SetCharFmt( SwCharFmt* ); virtual void Modify( SfxPoolItem* pOld, SfxPoolItem* pNew ); virtual void SetCharFmtName(const String& rSet); virtual const String& GetCharFmtName()const; virtual void SetGraphicBrush( const SvxBrushItem* pBrushItem, const Size* pSize = 0, const SvxFrameVertOrient* pOrient = 0); virtual void SetVertOrient(SvxFrameVertOrient eSet); virtual SvxFrameVertOrient GetVertOrient() const; const SwFmtVertOrient* GetGraphicOrientation() const; }; enum SwNumRuleType { OUTLINE_RULE = 0, NUM_RULE = 1, RULE_END = 2 }; class SwNumRule { friend void _FinitCore(); static SwNumFmt* aBaseFmts [ RULE_END ][ MAXLEVEL ]; static USHORT aDefNumIndents[ MAXLEVEL ]; static USHORT nRefCount; static Font* pDefBulletFont; static char* pDefOutlineName; SwNumFmt* aFmts[ MAXLEVEL ]; String sName; SwNumRuleType eRuleType; USHORT nPoolFmtId; // Id-fuer "automatich" erzeugte NumRules USHORT nPoolHelpId; // HelpId fuer diese Pool-Vorlage BYTE nPoolHlpFileId; // FilePos ans Doc auf die Vorlagen-Hilfen BOOL bAutoRuleFlag : 1; BOOL bInvalidRuleFlag : 1; BOOL bContinusNum : 1; // Fortlaufende Numerierung - ohne Ebenen BOOL bAbsSpaces : 1; // die Ebenen repraesentieren absol. Einzuege static void _MakeDefBulletFont(); public: SwNumRule( const String& rNm, SwNumRuleType = NUM_RULE, BOOL bAutoFlg = TRUE ); SwNumRule( const SwNumRule& ); ~SwNumRule(); SwNumRule& operator=( const SwNumRule& ); BOOL operator==( const SwNumRule& ) const; BOOL operator!=( const SwNumRule& r ) const { return !(*this == r); } inline const SwNumFmt* GetNumFmt( USHORT i ) const; inline const SwNumFmt& Get( USHORT i ) const; void Set( USHORT i, const SwNumFmt* ); void Set( USHORT i, const SwNumFmt& ); String MakeNumString( const SwNodeNum&, BOOL bInclStrings = TRUE, BOOL bOnlyArabic = FALSE ) const; inline sal_Unicode GetBulletChar( const SwNodeNum& ) const; inline const Font* GetBulletFont( const SwNodeNum& ) const; static inline const Font& GetDefBulletFont(); static char* GetOutlineRuleName() { return pDefOutlineName; } static inline USHORT GetNumIndent( BYTE nLvl ); static inline USHORT GetBullIndent( BYTE nLvl ); SwNumRuleType GetRuleType() const { return eRuleType; } void SetRuleType( SwNumRuleType eNew ) { eRuleType = eNew; bInvalidRuleFlag = TRUE; } // eine Art Copy-Constructor, damit die Num-Formate auch an den // richtigen CharFormaten eines Dokumentes haengen !! // (Kopiert die NumFormate und returnt sich selbst) SwNumRule& CopyNumRule( SwDoc*, const SwNumRule& ); // testet ob die CharFormate aus dem angegeben Doc sind und kopiert // die gegebenfalls void CheckCharFmts( SwDoc* pDoc ); // test ob der Einzug von dieser Numerierung kommt. BOOL IsRuleLSpace( SwTxtNode& rNd ) const; const String& GetName() const { return sName; } void SetName( const String& rNm ) { sName = rNm; } BOOL IsAutoRule() const { return bAutoRuleFlag; } void SetAutoRule( BOOL bFlag ) { bAutoRuleFlag = bFlag; } BOOL IsInvalidRule() const { return bInvalidRuleFlag; } void SetInvalidRule( BOOL bFlag ) { bInvalidRuleFlag = bFlag; } BOOL IsContinusNum() const { return bContinusNum; } void SetContinusNum( BOOL bFlag ) { bContinusNum = bFlag; } BOOL IsAbsSpaces() const { return bAbsSpaces; } void SetAbsSpaces( BOOL bFlag ) { bAbsSpaces = bFlag; } // erfragen und setzen der Poolvorlagen-Id's USHORT GetPoolFmtId() const { return nPoolFmtId; } void SetPoolFmtId( USHORT nId ) { nPoolFmtId = nId; } // erfragen und setzen der Hilfe-Id's fuer die Document-Vorlagen USHORT GetPoolHelpId() const { return nPoolHelpId; } void SetPoolHelpId( USHORT nId ) { nPoolHelpId = nId; } BYTE GetPoolHlpFileId() const { return nPoolHlpFileId; } void SetPoolHlpFileId( BYTE nId ) { nPoolHlpFileId = nId; } void SetSvxRule(const SvxNumRule&, SwDoc* pDoc); SvxNumRule MakeSvxNumRule() const; }; class SwNodeNum { USHORT nLevelVal[ MAXLEVEL ]; // Nummern aller Levels USHORT nSetValue; // vorgegeben Nummer BYTE nMyLevel; // akt. Level BOOL bStartNum; // Numerierung neu starten public: inline SwNodeNum( BYTE nLevel = NO_NUM, USHORT nSetVal = USHRT_MAX ); inline SwNodeNum& operator=( const SwNodeNum& rCpy ); BOOL operator==( const SwNodeNum& ) const; BYTE GetLevel() const { return nMyLevel; } void SetLevel( BYTE nVal ) { nMyLevel = nVal; } BOOL IsStart() const { return bStartNum; } void SetStart( BOOL bFlag = TRUE ) { bStartNum = bFlag; } USHORT GetSetValue() const { return nSetValue; } void SetSetValue( USHORT nVal ) { nSetValue = nVal; } const USHORT* GetLevelVal() const { return nLevelVal; } USHORT* GetLevelVal() { return nLevelVal; } }; // ------------ inline Methoden ---------------------------- inline const SwNumFmt& SwNumRule::Get( USHORT i ) const { ASSERT_ID( i < MAXLEVEL && eRuleType < RULE_END, ERR_NUMLEVEL); return aFmts[ i ] ? *aFmts[ i ] : *aBaseFmts[ eRuleType ][ i ]; } inline const SwNumFmt* SwNumRule::GetNumFmt( USHORT i ) const { ASSERT_ID( i < MAXLEVEL && eRuleType < RULE_END, ERR_NUMLEVEL); return aFmts[ i ]; } inline const Font& SwNumRule::GetDefBulletFont() { if( !pDefBulletFont ) SwNumRule::_MakeDefBulletFont(); return *pDefBulletFont; } inline USHORT SwNumRule::GetNumIndent( BYTE nLvl ) { ASSERT( MAXLEVEL > nLvl, "NumLevel is out of range" ); return aDefNumIndents[ nLvl ]; } inline USHORT SwNumRule::GetBullIndent( BYTE nLvl ) { ASSERT( MAXLEVEL > nLvl, "NumLevel is out of range" ); return aDefNumIndents[ nLvl ]; } inline sal_Unicode SwNumRule::GetBulletChar( const SwNodeNum& rNum ) const { return Get( rNum.GetLevel() & ~NO_NUMLEVEL ).GetBulletChar(); } inline const Font* SwNumRule::GetBulletFont( const SwNodeNum& rNum ) const { return Get( rNum.GetLevel() & ~NO_NUMLEVEL ).GetBulletFont(); } SwNodeNum::SwNodeNum( BYTE nLevel, USHORT nSetVal ) : nSetValue( nSetVal ), nMyLevel( nLevel ), bStartNum( FALSE ) { memset( nLevelVal, 0, sizeof( nLevelVal ) ); } inline SwNodeNum& SwNodeNum::operator=( const SwNodeNum& rCpy ) { nSetValue = rCpy.nSetValue; nMyLevel = rCpy.nMyLevel; bStartNum = rCpy.bStartNum; memcpy( nLevelVal, rCpy.nLevelVal, sizeof( nLevelVal ) ); return *this; } #endif // _NUMRULE_HXX <commit_msg>INTEGRATION: CWS sw015 (1.7.202); FILE MERGED 2003/05/19 12:40:03 hbrinkm 1.7.202.1: #109308# SwNumRule::SetNumAdjust<commit_after>/************************************************************************* * * $RCSfile: numrule.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: vg $ $Date: 2003-06-10 13:16:59 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _NUMRULE_HXX #define _NUMRULE_HXX #ifndef _LINK_HXX //autogen #include <tools/link.hxx> #endif #ifndef _SV_GEN_HXX //autogen wg. Size #include <tools/gen.hxx> #endif #ifndef _STRING_HXX //autogen #include <tools/string.hxx> #endif #ifndef _SVX_SVXENUM_HXX //autogen #include <svx/svxenum.hxx> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #ifndef _CALBCK_HXX #include <calbck.hxx> #endif #ifndef _ERRHDL_HXX #include <errhdl.hxx> // Fuer die inline-ASSERTs #endif #ifndef _SWERROR_H #include <error.h> // Fuer die inline-ASSERTs #endif #ifndef _SVX_NUMITEM_HXX #include <svx/numitem.hxx> #endif class Font; class SvxBrushItem; class SvxNumRule; class SwCharFmt; class SwDoc; class SwFmtVertOrient; class SwNodeNum; class SwTxtNode; extern char __FAR_DATA sOutlineStr[]; // SWG-Filter inline BYTE GetRealLevel( const BYTE nLvl ) { return nLvl & (NO_NUMLEVEL - 1); } const sal_Unicode cBulletChar = 0x2022; // Charakter fuer Aufzaehlungen class SwNumFmt : public SvxNumberFormat, public SwClient { SwFmtVertOrient* pVertOrient; void UpdateNumNodes( SwDoc* pDoc ); virtual void NotifyGraphicArrived(); public: SwNumFmt(); SwNumFmt( const SwNumFmt& ); SwNumFmt( const SvxNumberFormat&, SwDoc* pDoc); virtual ~SwNumFmt(); SwNumFmt& operator=( const SwNumFmt& ); BOOL operator==( const SwNumFmt& ) const; BOOL operator!=( const SwNumFmt& r ) const { return !(*this == r); } const Graphic* GetGraphic() const; SwCharFmt* GetCharFmt() const { return (SwCharFmt*)pRegisteredIn; } void SetCharFmt( SwCharFmt* ); virtual void Modify( SfxPoolItem* pOld, SfxPoolItem* pNew ); virtual void SetCharFmtName(const String& rSet); virtual const String& GetCharFmtName()const; virtual void SetGraphicBrush( const SvxBrushItem* pBrushItem, const Size* pSize = 0, const SvxFrameVertOrient* pOrient = 0); virtual void SetVertOrient(SvxFrameVertOrient eSet); virtual SvxFrameVertOrient GetVertOrient() const; const SwFmtVertOrient* GetGraphicOrientation() const; }; enum SwNumRuleType { OUTLINE_RULE = 0, NUM_RULE = 1, RULE_END = 2 }; class SwNumRule { friend void _FinitCore(); static SwNumFmt* aBaseFmts [ RULE_END ][ MAXLEVEL ]; static USHORT aDefNumIndents[ MAXLEVEL ]; static USHORT nRefCount; static Font* pDefBulletFont; static char* pDefOutlineName; SwNumFmt* aFmts[ MAXLEVEL ]; String sName; SwNumRuleType eRuleType; USHORT nPoolFmtId; // Id-fuer "automatich" erzeugte NumRules USHORT nPoolHelpId; // HelpId fuer diese Pool-Vorlage BYTE nPoolHlpFileId; // FilePos ans Doc auf die Vorlagen-Hilfen BOOL bAutoRuleFlag : 1; BOOL bInvalidRuleFlag : 1; BOOL bContinusNum : 1; // Fortlaufende Numerierung - ohne Ebenen BOOL bAbsSpaces : 1; // die Ebenen repraesentieren absol. Einzuege static void _MakeDefBulletFont(); public: SwNumRule( const String& rNm, SwNumRuleType = NUM_RULE, BOOL bAutoFlg = TRUE ); SwNumRule( const SwNumRule& ); ~SwNumRule(); SwNumRule& operator=( const SwNumRule& ); BOOL operator==( const SwNumRule& ) const; BOOL operator!=( const SwNumRule& r ) const { return !(*this == r); } inline const SwNumFmt* GetNumFmt( USHORT i ) const; inline const SwNumFmt& Get( USHORT i ) const; void Set( USHORT i, const SwNumFmt* ); void Set( USHORT i, const SwNumFmt& ); String MakeNumString( const SwNodeNum&, BOOL bInclStrings = TRUE, BOOL bOnlyArabic = FALSE ) const; inline sal_Unicode GetBulletChar( const SwNodeNum& ) const; inline const Font* GetBulletFont( const SwNodeNum& ) const; static inline const Font& GetDefBulletFont(); static char* GetOutlineRuleName() { return pDefOutlineName; } static inline USHORT GetNumIndent( BYTE nLvl ); static inline USHORT GetBullIndent( BYTE nLvl ); SwNumRuleType GetRuleType() const { return eRuleType; } void SetRuleType( SwNumRuleType eNew ) { eRuleType = eNew; bInvalidRuleFlag = TRUE; } // eine Art Copy-Constructor, damit die Num-Formate auch an den // richtigen CharFormaten eines Dokumentes haengen !! // (Kopiert die NumFormate und returnt sich selbst) SwNumRule& CopyNumRule( SwDoc*, const SwNumRule& ); // testet ob die CharFormate aus dem angegeben Doc sind und kopiert // die gegebenfalls void CheckCharFmts( SwDoc* pDoc ); // test ob der Einzug von dieser Numerierung kommt. BOOL IsRuleLSpace( SwTxtNode& rNd ) const; const String& GetName() const { return sName; } void SetName( const String& rNm ) { sName = rNm; } BOOL IsAutoRule() const { return bAutoRuleFlag; } void SetAutoRule( BOOL bFlag ) { bAutoRuleFlag = bFlag; } BOOL IsInvalidRule() const { return bInvalidRuleFlag; } void SetInvalidRule( BOOL bFlag ) { bInvalidRuleFlag = bFlag; } BOOL IsContinusNum() const { return bContinusNum; } void SetContinusNum( BOOL bFlag ) { bContinusNum = bFlag; } BOOL IsAbsSpaces() const { return bAbsSpaces; } void SetAbsSpaces( BOOL bFlag ) { bAbsSpaces = bFlag; } // erfragen und setzen der Poolvorlagen-Id's USHORT GetPoolFmtId() const { return nPoolFmtId; } void SetPoolFmtId( USHORT nId ) { nPoolFmtId = nId; } // erfragen und setzen der Hilfe-Id's fuer die Document-Vorlagen USHORT GetPoolHelpId() const { return nPoolHelpId; } void SetPoolHelpId( USHORT nId ) { nPoolHelpId = nId; } BYTE GetPoolHlpFileId() const { return nPoolHlpFileId; } void SetPoolHlpFileId( BYTE nId ) { nPoolHlpFileId = nId; } /** #109308# Sets adjustment in all formats of the numbering rule. @param eNum adjustment to be set */ void SetNumAdjust(SvxAdjust eNum); void SetSvxRule(const SvxNumRule&, SwDoc* pDoc); SvxNumRule MakeSvxNumRule() const; }; class SwNodeNum { USHORT nLevelVal[ MAXLEVEL ]; // Nummern aller Levels USHORT nSetValue; // vorgegeben Nummer BYTE nMyLevel; // akt. Level BOOL bStartNum; // Numerierung neu starten public: inline SwNodeNum( BYTE nLevel = NO_NUM, USHORT nSetVal = USHRT_MAX ); inline SwNodeNum& operator=( const SwNodeNum& rCpy ); BOOL operator==( const SwNodeNum& ) const; BYTE GetLevel() const { return nMyLevel; } void SetLevel( BYTE nVal ) { nMyLevel = nVal; } BOOL IsStart() const { return bStartNum; } void SetStart( BOOL bFlag = TRUE ) { bStartNum = bFlag; } USHORT GetSetValue() const { return nSetValue; } void SetSetValue( USHORT nVal ) { nSetValue = nVal; } const USHORT* GetLevelVal() const { return nLevelVal; } USHORT* GetLevelVal() { return nLevelVal; } }; // ------------ inline Methoden ---------------------------- inline const SwNumFmt& SwNumRule::Get( USHORT i ) const { ASSERT_ID( i < MAXLEVEL && eRuleType < RULE_END, ERR_NUMLEVEL); return aFmts[ i ] ? *aFmts[ i ] : *aBaseFmts[ eRuleType ][ i ]; } inline const SwNumFmt* SwNumRule::GetNumFmt( USHORT i ) const { ASSERT_ID( i < MAXLEVEL && eRuleType < RULE_END, ERR_NUMLEVEL); return aFmts[ i ]; } inline const Font& SwNumRule::GetDefBulletFont() { if( !pDefBulletFont ) SwNumRule::_MakeDefBulletFont(); return *pDefBulletFont; } inline USHORT SwNumRule::GetNumIndent( BYTE nLvl ) { ASSERT( MAXLEVEL > nLvl, "NumLevel is out of range" ); return aDefNumIndents[ nLvl ]; } inline USHORT SwNumRule::GetBullIndent( BYTE nLvl ) { ASSERT( MAXLEVEL > nLvl, "NumLevel is out of range" ); return aDefNumIndents[ nLvl ]; } inline sal_Unicode SwNumRule::GetBulletChar( const SwNodeNum& rNum ) const { return Get( rNum.GetLevel() & ~NO_NUMLEVEL ).GetBulletChar(); } inline const Font* SwNumRule::GetBulletFont( const SwNodeNum& rNum ) const { return Get( rNum.GetLevel() & ~NO_NUMLEVEL ).GetBulletFont(); } SwNodeNum::SwNodeNum( BYTE nLevel, USHORT nSetVal ) : nSetValue( nSetVal ), nMyLevel( nLevel ), bStartNum( FALSE ) { memset( nLevelVal, 0, sizeof( nLevelVal ) ); } inline SwNodeNum& SwNodeNum::operator=( const SwNodeNum& rCpy ) { nSetValue = rCpy.nSetValue; nMyLevel = rCpy.nMyLevel; bStartNum = rCpy.bStartNum; memcpy( nLevelVal, rCpy.nLevelVal, sizeof( nLevelVal ) ); return *this; } #endif // _NUMRULE_HXX <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2020 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 <iomanip> #include <iostream> #include <fstream> #include <boost/algorithm/string.hpp> #include "otbGeomMetadataSupplier.h" #include "otbMetaDataKey.h" #include "otbGeometryMetadata.h" #include "otbStringUtils.h" namespace otb { GeomMetadataSupplier::GeomMetadataSupplier(std::string const& geomFile) { GeomMetadataSupplier(geomFile, ""); } GeomMetadataSupplier::GeomMetadataSupplier(std::string const& geomFile, const std::string & imageFile) { this->m_FileNames["geom"] = geomFile; this->m_FileNames["image"] = imageFile; this->ReadGeomFile(); } std::string GeomMetadataSupplier::GetMetadataValue(std::string const& path, bool& hasValue, int) const { auto value = this->m_MetadataDic.find(path); if(value != this->m_MetadataDic.end()) { hasValue = true; return value->second; } hasValue = false; return ""; } std::string GeomMetadataSupplier::GetResourceFile(std::string const& name) const { assert((name == "") || (name == "geom") || (name == "image")); if (name.empty()) return this->m_FileNames.at("geom"); return this->m_FileNames.at(name); } std::vector<std::string> GeomMetadataSupplier::GetResourceFiles() const { return std::vector<std::string>({this->m_FileNames.at("geom"), this->m_FileNames.at("image")}); } int GeomMetadataSupplier::GetNbBands() const { bool hasValue; std::string ret = this->GetMetadataValue("support_data.number_bands", hasValue); if (hasValue) { boost::algorithm::trim_if(ret, boost::algorithm::is_any_of("\" ")); return std::stoi(ret); } ret = this->GetMetadataValue("support_data.band_name_list", hasValue); boost::algorithm::trim_if(ret, boost::algorithm::is_any_of("\" ")); if (hasValue) { std::vector<std::string> ret_vect; otb::Utils::ConvertStringToVector(ret, ret_vect, "band name"); return ret_vect.size(); } return 1; } bool GeomMetadataSupplier::FetchRPC(ImageMetadata & imd) { bool hasValue; GetMetadataValue("polynomial_format", hasValue); if (!hasValue) return false; Projection::RPCParam rpcStruct; rpcStruct.LineOffset = this->GetAs<double>("line_off"); rpcStruct.SampleOffset = this->GetAs<double>("samp_off"); rpcStruct.LatOffset = this->GetAs<double>("lat_off"); rpcStruct.LonOffset = this->GetAs<double>("long_off"); rpcStruct.HeightOffset = this->GetAs<double>("height_off"); rpcStruct.LineScale = this->GetAs<double>("line_scale"); rpcStruct.SampleScale = this->GetAs<double>("samp_scale"); rpcStruct.LatScale = this->GetAs<double>("lat_scale"); rpcStruct.LonScale = this->GetAs<double>("long_scale"); rpcStruct.HeightScale = this->GetAs<double>("height_scale"); std::vector<double> coeffs; int loop = 0; std::stringstream path; for (auto & coeff : rpcStruct.LineNum) { path.str(""); path << "line_num_coeff_" << std::setfill('0') << std::setw(2) << loop++; coeff = this->GetAs<double>(path.str()); } loop = 0; for (auto & coeff : rpcStruct.LineDen) { path.str(""); path << "line_den_coeff_" << std::setfill('0') << std::setw(2) << loop++; coeff = this->GetAs<double>(path.str()); } loop = 0; for (auto & coeff : rpcStruct.SampleNum) { path.str(""); path << "samp_num_coeff_" << std::setfill('0') << std::setw(2) << loop++; coeff = this->GetAs<double>(path.str()); } loop = 0; for (auto & coeff : rpcStruct.SampleDen) { path.str(""); path << "samp_den_coeff_" << std::setfill('0') << std::setw(2) << loop++; coeff = this->GetAs<double>(path.str()); } imd.Add(MDGeom::RPC, rpcStruct); assert(imd.Has(MDGeom::RPC)); assert(rpcStruct == boost::any_cast<Projection::RPCParam>(imd[MDGeom::RPC])); return true; } std::string GeomMetadataSupplier::PrintSelf() const { std::ostringstream oss; oss << "GeomMetadataSupplier: " << this->m_FileNames.at("geom") << '\t' << this->m_FileNames.at("image") << '\n'; for (const auto& kv : this->m_MetadataDic) oss << kv.first << " : " << kv.second << '\n'; return oss.str(); } void GeomMetadataSupplier::ReadGeomFile() { std::ifstream inputFile(this->m_FileNames["geom"]); std::string line; while (std::getline(inputFile, line)) { auto pos = line.find(":"); if (pos != std::string::npos) { auto key = line.substr(0,pos); auto value = line.substr(pos+1, line.size()); boost::trim(key); boost::trim(value); m_MetadataDic[key] = value; } } } } // end namespace otb <commit_msg>BUG: Correctly construct GeomMetadataSupplier<commit_after>/* * Copyright (C) 2005-2020 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 <iomanip> #include <iostream> #include <fstream> #include <boost/algorithm/string.hpp> #include "otbGeomMetadataSupplier.h" #include "otbMetaDataKey.h" #include "otbGeometryMetadata.h" #include "otbStringUtils.h" namespace otb { GeomMetadataSupplier::GeomMetadataSupplier(std::string const& geomFile) : GeomMetadataSupplier(geomFile, "") {} GeomMetadataSupplier::GeomMetadataSupplier(std::string const& geomFile, const std::string & imageFile) { this->m_FileNames["geom"] = geomFile; this->m_FileNames["image"] = imageFile; this->ReadGeomFile(); } std::string GeomMetadataSupplier::GetMetadataValue(std::string const& path, bool& hasValue, int) const { auto value = this->m_MetadataDic.find(path); if(value != this->m_MetadataDic.end()) { hasValue = true; return value->second; } hasValue = false; return ""; } std::string GeomMetadataSupplier::GetResourceFile(std::string const& name) const { assert((name == "") || (name == "geom") || (name == "image")); if (name.empty()) return this->m_FileNames.at("geom"); return this->m_FileNames.at(name); } std::vector<std::string> GeomMetadataSupplier::GetResourceFiles() const { return std::vector<std::string>({this->m_FileNames.at("geom"), this->m_FileNames.at("image")}); } int GeomMetadataSupplier::GetNbBands() const { bool hasValue; std::string ret = this->GetMetadataValue("support_data.number_bands", hasValue); if (hasValue) { boost::algorithm::trim_if(ret, boost::algorithm::is_any_of("\" ")); return std::stoi(ret); } ret = this->GetMetadataValue("support_data.band_name_list", hasValue); boost::algorithm::trim_if(ret, boost::algorithm::is_any_of("\" ")); if (hasValue) { std::vector<std::string> ret_vect; otb::Utils::ConvertStringToVector(ret, ret_vect, "band name"); return ret_vect.size(); } return 1; } bool GeomMetadataSupplier::FetchRPC(ImageMetadata & imd) { bool hasValue; GetMetadataValue("polynomial_format", hasValue); if (!hasValue) return false; Projection::RPCParam rpcStruct; rpcStruct.LineOffset = this->GetAs<double>("line_off"); rpcStruct.SampleOffset = this->GetAs<double>("samp_off"); rpcStruct.LatOffset = this->GetAs<double>("lat_off"); rpcStruct.LonOffset = this->GetAs<double>("long_off"); rpcStruct.HeightOffset = this->GetAs<double>("height_off"); rpcStruct.LineScale = this->GetAs<double>("line_scale"); rpcStruct.SampleScale = this->GetAs<double>("samp_scale"); rpcStruct.LatScale = this->GetAs<double>("lat_scale"); rpcStruct.LonScale = this->GetAs<double>("long_scale"); rpcStruct.HeightScale = this->GetAs<double>("height_scale"); std::vector<double> coeffs; int loop = 0; std::stringstream path; for (auto & coeff : rpcStruct.LineNum) { path.str(""); path << "line_num_coeff_" << std::setfill('0') << std::setw(2) << loop++; coeff = this->GetAs<double>(path.str()); } loop = 0; for (auto & coeff : rpcStruct.LineDen) { path.str(""); path << "line_den_coeff_" << std::setfill('0') << std::setw(2) << loop++; coeff = this->GetAs<double>(path.str()); } loop = 0; for (auto & coeff : rpcStruct.SampleNum) { path.str(""); path << "samp_num_coeff_" << std::setfill('0') << std::setw(2) << loop++; coeff = this->GetAs<double>(path.str()); } loop = 0; for (auto & coeff : rpcStruct.SampleDen) { path.str(""); path << "samp_den_coeff_" << std::setfill('0') << std::setw(2) << loop++; coeff = this->GetAs<double>(path.str()); } imd.Add(MDGeom::RPC, rpcStruct); assert(imd.Has(MDGeom::RPC)); assert(rpcStruct == boost::any_cast<Projection::RPCParam>(imd[MDGeom::RPC])); return true; } std::string GeomMetadataSupplier::PrintSelf() const { std::ostringstream oss; oss << "GeomMetadataSupplier: " << this->m_FileNames.at("geom") << '\t' << this->m_FileNames.at("image") << '\n'; for (const auto& kv : this->m_MetadataDic) oss << kv.first << " : " << kv.second << '\n'; return oss.str(); } void GeomMetadataSupplier::ReadGeomFile() { std::ifstream inputFile(this->m_FileNames.at("geom")); std::string line, key, value; std::string::size_type pos; while (std::getline(inputFile, line)) { pos = line.find(":"); if (pos != std::string::npos) { key = line.substr(0,pos); value = line.substr(pos+1, line.size()); boost::trim(key); boost::trim(value); m_MetadataDic[key] = value; } } } } // end namespace otb <|endoftext|>
<commit_before>#include "AnomalyBombControllerSystem.h" #include "Transform.h" #include "PhysicsBody.h" #include "AnomalyBomb.h" #include "PhysicsSystem.h" #include <PhysicsController.h> #include <TcpServer.h> #include "BombActivationPacket.h" AnomalyBombControllerSystem::AnomalyBombControllerSystem(TcpServer* p_server) : EntitySystem(SystemType::AnomalyBombControllerSystem, 4, ComponentType::AnomalyBomb, ComponentType::Transform, ComponentType::PhysicsBody, ComponentType::NetworkSynced) { m_server = p_server; } void AnomalyBombControllerSystem::processEntities( const vector<Entity*>& p_entities ) { float dt = m_world->getDelta(); const vector<Entity*>& dynamicEntities = m_world->getSystem( SystemType::ServerDynamicPhysicalObjectsSystem)->getActiveEntities(); for(unsigned int i=0; i<p_entities.size(); i++) { AnomalyBomb* bombBomb = static_cast<AnomalyBomb*>(p_entities[i]->getComponent( ComponentType::AnomalyBomb)); Transform* bombTransform = static_cast<Transform*>(p_entities[i]->getComponent( ComponentType::Transform)); bombBomb->lifeTime -= dt; if(bombBomb->lifeTime <= 0.0f) { m_world->deleteEntity(p_entities[i]); } else if(bombBomb->lifeTime <= bombBomb->explodeTime) { if(bombBomb->activated == false) { bombBomb->activated = true; BombActivationPacket packet; packet.netsyncId = p_entities[i]->getIndex(); m_server->broadcastPacket(packet.pack()); } for(unsigned int netsyncIndex=0; netsyncIndex<dynamicEntities.size(); netsyncIndex++) { Transform* otherTransform = static_cast<Transform*>( dynamicEntities[netsyncIndex]->getComponent(ComponentType::Transform)); AglVector3 dir = ( bombTransform->getTranslation() - otherTransform->getTranslation() ); float lengthSquared = dir.lengthSquared(); if(lengthSquared <= bombBomb->eventHorizonRadius * bombBomb->eventHorizonRadius) { // Stillness. } else if(lengthSquared <= bombBomb->arriveRadius * bombBomb->arriveRadius) { PhysicsBody* body = static_cast<PhysicsBody*>( dynamicEntities[netsyncIndex]->getComponent( ComponentType::PhysicsBody)); vector<ComponentType::ComponentTypeIdx> bombComps = m_world->getComponentManager()->getComponentEnumList(p_entities[i]); vector<ComponentType::ComponentTypeIdx> otherComps = m_world->getComponentManager()->getComponentEnumList( dynamicEntities[netsyncIndex]); PhysicsSystem* physSystem = static_cast<PhysicsSystem*>( m_world->getSystem(SystemType::PhysicsSystem)); float length = dir.length(); dir.normalize(); float radiusFactor = (length - bombBomb->eventHorizonRadius) / (bombBomb->arriveRadius - bombBomb->eventHorizonRadius); physSystem->getController()->ApplyExternalImpulse( body->m_id, dir * radiusFactor * dt * bombBomb->impulse, AglVector3::zero()); } else if(lengthSquared <= bombBomb->radius * bombBomb->radius) { PhysicsBody* body = static_cast<PhysicsBody*>( dynamicEntities[netsyncIndex]->getComponent( ComponentType::PhysicsBody)); vector<ComponentType::ComponentTypeIdx> bombComps = m_world->getComponentManager()->getComponentEnumList(p_entities[i]); vector<ComponentType::ComponentTypeIdx> otherComps = m_world->getComponentManager()->getComponentEnumList( dynamicEntities[netsyncIndex]); PhysicsSystem* physSystem = static_cast<PhysicsSystem*>( m_world->getSystem(SystemType::PhysicsSystem)); float length = dir.length(); dir.normalize(); float radiusFactor = (length - bombBomb->arriveRadius) / (bombBomb->radius - bombBomb->arriveRadius); physSystem->getController()->ApplyExternalImpulse( body->m_id, dir * (1.0f - radiusFactor) * dt * bombBomb->impulse, AglVector3::zero()); } } } } }<commit_msg>Small change in AnomalyBombControllerSystem.<commit_after>#include "AnomalyBombControllerSystem.h" #include "Transform.h" #include "PhysicsBody.h" #include "AnomalyBomb.h" #include "PhysicsSystem.h" #include <PhysicsController.h> #include <TcpServer.h> #include "BombActivationPacket.h" AnomalyBombControllerSystem::AnomalyBombControllerSystem(TcpServer* p_server) : EntitySystem(SystemType::AnomalyBombControllerSystem, 4, ComponentType::AnomalyBomb, ComponentType::Transform, ComponentType::PhysicsBody, ComponentType::NetworkSynced) { m_server = p_server; } void AnomalyBombControllerSystem::processEntities( const vector<Entity*>& p_entities ) { float dt = m_world->getDelta(); const vector<Entity*>& dynamicEntities = m_world->getSystem( SystemType::ServerDynamicPhysicalObjectsSystem)->getActiveEntities(); for(unsigned int i=0; i<p_entities.size(); i++) { AnomalyBomb* bombBomb = static_cast<AnomalyBomb*>(p_entities[i]->getComponent( ComponentType::AnomalyBomb)); Transform* bombTransform = static_cast<Transform*>(p_entities[i]->getComponent( ComponentType::Transform)); PhysicsBody* bombBody = static_cast<PhysicsBody*>(p_entities[i]->getComponent( ComponentType::PhysicsBody)); PhysicsSystem* physSystem = static_cast<PhysicsSystem*>( m_world->getSystem(SystemType::PhysicsSystem)); bombBomb->lifeTime -= dt; if(bombBomb->lifeTime <= 0.0f) { m_world->deleteEntity(p_entities[i]); } else if(bombBomb->lifeTime <= bombBomb->explodeTime) { if(bombBomb->activated == false) { bombBomb->activated = true; BombActivationPacket packet; packet.netsyncId = p_entities[i]->getIndex(); m_server->broadcastPacket(packet.pack()); } for(unsigned int netsyncIndex=0; netsyncIndex<dynamicEntities.size(); netsyncIndex++) { Transform* otherTransform = static_cast<Transform*>( dynamicEntities[netsyncIndex]->getComponent(ComponentType::Transform)); AglVector3 dir = ( bombTransform->getTranslation() - otherTransform->getTranslation() ); float lengthSquared = dir.lengthSquared(); if(lengthSquared <= bombBomb->eventHorizonRadius * bombBomb->eventHorizonRadius) { // Stillness. } else if(lengthSquared <= bombBomb->arriveRadius * bombBomb->arriveRadius) { PhysicsBody* body = static_cast<PhysicsBody*>( dynamicEntities[netsyncIndex]->getComponent( ComponentType::PhysicsBody)); vector<ComponentType::ComponentTypeIdx> bombComps = m_world->getComponentManager()->getComponentEnumList(p_entities[i]); vector<ComponentType::ComponentTypeIdx> otherComps = m_world->getComponentManager()->getComponentEnumList( dynamicEntities[netsyncIndex]); float length = dir.length(); dir.normalize(); float radiusFactor = (length - bombBomb->eventHorizonRadius) / (bombBomb->arriveRadius - bombBomb->eventHorizonRadius); physSystem->getController()->ApplyExternalImpulse( body->m_id, dir * radiusFactor * dt * bombBomb->impulse, AglVector3::zero()); } else if(lengthSquared <= bombBomb->radius * bombBomb->radius) { PhysicsBody* body = static_cast<PhysicsBody*>( dynamicEntities[netsyncIndex]->getComponent( ComponentType::PhysicsBody)); vector<ComponentType::ComponentTypeIdx> bombComps = m_world->getComponentManager()->getComponentEnumList(p_entities[i]); vector<ComponentType::ComponentTypeIdx> otherComps = m_world->getComponentManager()->getComponentEnumList( dynamicEntities[netsyncIndex]); float length = dir.length(); dir.normalize(); float radiusFactor = (length - bombBomb->arriveRadius) / (bombBomb->radius - bombBomb->arriveRadius); physSystem->getController()->ApplyExternalImpulse( body->m_id, dir * (1.0f - radiusFactor) * dt * bombBomb->impulse, AglVector3::zero()); } } } } }<|endoftext|>
<commit_before>/* * Copyright 2011 Marco Martin <[email protected]> * Copyright 2014 Aleix Pol Gonzalez <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "desktopicon.h" #include <QSGSimpleTextureNode> #include <qquickwindow.h> #include <QIcon> #include <QBitmap> #include <QSGTexture> #include <QDebug> #include <QSGSimpleTextureNode> #include <QSGTexture> #include <QSharedPointer> #include <QtQml> #include <QQuickImageProvider> #include <QGuiApplication> class ManagedTextureNode : public QSGSimpleTextureNode { Q_DISABLE_COPY(ManagedTextureNode) public: ManagedTextureNode(); void setTexture(QSharedPointer<QSGTexture> texture); private: QSharedPointer<QSGTexture> m_texture; }; ManagedTextureNode::ManagedTextureNode() {} void ManagedTextureNode::setTexture(QSharedPointer<QSGTexture> texture) { m_texture = texture; QSGSimpleTextureNode::setTexture(texture.data()); } typedef QHash<qint64, QHash<QWindow*, QWeakPointer<QSGTexture> > > TexturesCache; struct ImageTexturesCachePrivate { TexturesCache cache; }; class ImageTexturesCache { public: ImageTexturesCache(); ~ImageTexturesCache(); /** * @returns the texture for a given @p window and @p image. * * If an @p image id is the same as one already provided before, we won't create * a new texture and return a shared pointer to the existing texture. */ QSharedPointer<QSGTexture> loadTexture(QQuickWindow *window, const QImage &image, QQuickWindow::CreateTextureOptions options); QSharedPointer<QSGTexture> loadTexture(QQuickWindow *window, const QImage &image); private: QScopedPointer<ImageTexturesCachePrivate> d; }; ImageTexturesCache::ImageTexturesCache() : d(new ImageTexturesCachePrivate) { } ImageTexturesCache::~ImageTexturesCache() { } QSharedPointer<QSGTexture> ImageTexturesCache::loadTexture(QQuickWindow *window, const QImage &image, QQuickWindow::CreateTextureOptions options) { qint64 id = image.cacheKey(); QSharedPointer<QSGTexture> texture = d->cache.value(id).value(window).toStrongRef(); if (!texture) { auto cleanAndDelete = [this, window, id](QSGTexture* texture) { QHash<QWindow*, QWeakPointer<QSGTexture> >& textures = (d->cache)[id]; textures.remove(window); if (textures.isEmpty()) d->cache.remove(id); delete texture; }; texture = QSharedPointer<QSGTexture>(window->createTextureFromImage(image, options), cleanAndDelete); (d->cache)[id][window] = texture.toWeakRef(); } //if we have a cache in an atlas but our request cannot use an atlassed texture //create a new texture and use that //don't use removedFromAtlas() as that requires keeping a reference to the non atlased version if (!(options & QQuickWindow::TextureCanUseAtlas) && texture->isAtlasTexture()) { texture = QSharedPointer<QSGTexture>(window->createTextureFromImage(image, options)); } return texture; } QSharedPointer<QSGTexture> ImageTexturesCache::loadTexture(QQuickWindow *window, const QImage &image) { return loadTexture(window, image, 0); } Q_GLOBAL_STATIC(ImageTexturesCache, s_iconImageCache) DesktopIcon::DesktopIcon(QQuickItem *parent) : QQuickItem(parent), m_smooth(false), m_changed(false), m_active(false), m_selected(false) { setFlag(ItemHasContents, true); connect(qApp, &QGuiApplication::paletteChanged, this, [this]() { m_changed = true; update(); }); } DesktopIcon::~DesktopIcon() { } void DesktopIcon::setSource(const QVariant &icon) { if (m_source == icon) { return; } m_source = icon; m_changed = true; update(); emit sourceChanged(); } QVariant DesktopIcon::source() const { return m_source; } void DesktopIcon::setEnabled(const bool enabled) { if (enabled == QQuickItem::isEnabled()) { return; } QQuickItem::setEnabled(enabled); m_changed = true; update(); emit enabledChanged(); } void DesktopIcon::setActive(const bool active) { if (active == m_active) { return; } m_active = active; m_changed = true; update(); emit activeChanged(); } bool DesktopIcon::active() const { return m_active; } bool DesktopIcon::valid() const { return !m_source.isNull(); } void DesktopIcon::setSelected(const bool selected) { if (selected == m_selected) { return; } m_selected = selected; m_changed = true; update(); emit selectedChanged(); } bool DesktopIcon::selected() const { return m_selected; } int DesktopIcon::implicitWidth() const { return 32; } int DesktopIcon::implicitHeight() const { return 32; } void DesktopIcon::setSmooth(const bool smooth) { if (smooth == m_smooth) { return; } m_smooth = smooth; m_changed = true; update(); emit smoothChanged(); } bool DesktopIcon::smooth() const { return m_smooth; } QSGNode* DesktopIcon::updatePaintNode(QSGNode* node, QQuickItem::UpdatePaintNodeData* /*data*/) { if (m_source.isNull()) { delete node; return Q_NULLPTR; } if (m_changed || node == 0) { QImage img; const QSize size = QSize(width(), height()) * (window() ? window()->devicePixelRatio() : qApp->devicePixelRatio()); switch(m_source.type()){ case QVariant::Pixmap: img = m_source.value<QPixmap>().toImage(); break; case QVariant::Image: img = m_source.value<QImage>(); break; case QVariant::Bitmap: img = m_source.value<QBitmap>().toImage(); break; case QVariant::Icon: img = m_source.value<QIcon>().pixmap(size, iconMode(), QIcon::On).toImage(); break; case QVariant::String: img = findIcon(size); break; case QVariant::Brush: case QVariant::Color: //perhaps fill image instead? default: break; } if (img.isNull()){ img = QImage(size, QImage::Format_Alpha8); img.fill(Qt::transparent); } if (img.size() != size){ img = img.scaled(size, Qt::IgnoreAspectRatio, m_smooth ? Qt::SmoothTransformation : Qt::FastTransformation ); } m_changed = false; ManagedTextureNode* mNode = dynamic_cast<ManagedTextureNode*>(node); if (!mNode) { delete node; mNode = new ManagedTextureNode; } mNode->setTexture(s_iconImageCache->loadTexture(window(), img)); mNode->setRect(QRect(QPoint(0,0), QSize(width(), height()))); node = mNode; } return node; } void DesktopIcon::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry) { if (newGeometry.size() != oldGeometry.size()) { m_changed = true; update(); } QQuickItem::geometryChanged(newGeometry, oldGeometry); } void DesktopIcon::handleFinished(QNetworkAccessManager* qnam, QNetworkReply* reply) { if (reply->error() == QNetworkReply::NoError) { const QUrl possibleRedirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (!possibleRedirectUrl.isEmpty()) { const QUrl redirectUrl = reply->url().resolved(possibleRedirectUrl); if (redirectUrl == reply->url()) { // no infinite redirections thank you very much reply->deleteLater(); return; } reply->deleteLater(); QNetworkRequest request(possibleRedirectUrl); request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); QNetworkReply* newReply = qnam->get(request); connect(newReply, &QNetworkReply::readyRead, this, [this, newReply](){ handleReadyRead(newReply); }); connect(newReply, &QNetworkReply::finished, this, [this, qnam, newReply](){ handleFinished(qnam, newReply); }); return; } } } void DesktopIcon::handleReadyRead(QNetworkReply* reply) { if (reply->attribute(QNetworkRequest::RedirectionTargetAttribute).isNull()) { QByteArray data; do { data.append(reply->read(32768)); // Because we are in the main thread, this could be potentially very expensive, so let's not block qApp->processEvents(); } while(!reply->atEnd()); m_loadedImage = QImage::fromData(data); if (m_loadedImage.isNull()) { // broken image from data, inform the user of this with some useful broken-image thing... const QSize size = QSize(width(), height()) * (window() ? window()->devicePixelRatio() : qApp->devicePixelRatio()); m_loadedImage = QIcon::fromTheme("unknown").pixmap(size, iconMode(), QIcon::On).toImage(); } m_changed = true; update(); } } QImage DesktopIcon::findIcon(const QSize &size) { QImage img; QString iconSource = m_source.toString(); if (iconSource.startsWith("image://")){ QUrl iconUrl(iconSource); QString iconProviderId = iconUrl.host(); QString iconId = iconUrl.path(); QSize actualSize; QQuickImageProvider* imageProvider = dynamic_cast<QQuickImageProvider*>( qmlEngine(this)->imageProvider(iconProviderId)); if (!imageProvider) return img; switch(imageProvider->imageType()){ case QQmlImageProviderBase::Image: img = imageProvider->requestImage(iconId, &actualSize, size); case QQmlImageProviderBase::Pixmap: img = imageProvider->requestPixmap(iconId, &actualSize, size).toImage(); case QQmlImageProviderBase::Texture: case QQmlImageProviderBase::Invalid: case QQmlImageProviderBase::ImageResponse: //will have to investigate this more break; } } else if(iconSource.startsWith("http://") || iconSource.startsWith("https://")) { if(!m_loadedImage.isNull()) { return m_loadedImage.scaled(size, Qt::KeepAspectRatio, m_smooth ? Qt::SmoothTransformation : Qt::FastTransformation ); } QQmlEngine* engine = qmlEngine(this); QNetworkAccessManager* qnam; if (engine && (qnam = qmlEngine(this)->networkAccessManager())) { QNetworkRequest request(m_source.toUrl()); request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); QNetworkReply* reply = qnam->get(request); connect(reply, &QNetworkReply::readyRead, this, [this, reply](){ handleReadyRead(reply); }); connect(reply, &QNetworkReply::finished, this, [this, qnam, reply](){ handleFinished(qnam, reply); }); } // Temporary icon while we wait for the real image to load... img = QIcon::fromTheme("image-x-icon").pixmap(size, iconMode(), QIcon::On).toImage(); } else { if (iconSource.startsWith("qrc:/")){ iconSource = iconSource.mid(3); } QIcon icon(iconSource); if (icon.availableSizes().isEmpty()) { icon = QIcon::fromTheme(iconSource); } if (!icon.availableSizes().isEmpty()){ img = icon.pixmap(size, iconMode(), QIcon::On).toImage(); } } return img; } QIcon::Mode DesktopIcon::iconMode() const { if (!isEnabled()) { return QIcon::Disabled; } else if (m_selected) { return QIcon::Selected; } else if (m_active) { return QIcon::Active; } return QIcon::Normal; } <commit_msg>Don't crash when deleted during network operations<commit_after>/* * Copyright 2011 Marco Martin <[email protected]> * Copyright 2014 Aleix Pol Gonzalez <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "desktopicon.h" #include <QSGSimpleTextureNode> #include <qquickwindow.h> #include <QIcon> #include <QBitmap> #include <QSGTexture> #include <QDebug> #include <QSGSimpleTextureNode> #include <QSGTexture> #include <QSharedPointer> #include <QtQml> #include <QQuickImageProvider> #include <QGuiApplication> #include <QPointer> class ManagedTextureNode : public QSGSimpleTextureNode { Q_DISABLE_COPY(ManagedTextureNode) public: ManagedTextureNode(); void setTexture(QSharedPointer<QSGTexture> texture); private: QSharedPointer<QSGTexture> m_texture; }; ManagedTextureNode::ManagedTextureNode() {} void ManagedTextureNode::setTexture(QSharedPointer<QSGTexture> texture) { m_texture = texture; QSGSimpleTextureNode::setTexture(texture.data()); } typedef QHash<qint64, QHash<QWindow*, QWeakPointer<QSGTexture> > > TexturesCache; struct ImageTexturesCachePrivate { TexturesCache cache; }; class ImageTexturesCache { public: ImageTexturesCache(); ~ImageTexturesCache(); /** * @returns the texture for a given @p window and @p image. * * If an @p image id is the same as one already provided before, we won't create * a new texture and return a shared pointer to the existing texture. */ QSharedPointer<QSGTexture> loadTexture(QQuickWindow *window, const QImage &image, QQuickWindow::CreateTextureOptions options); QSharedPointer<QSGTexture> loadTexture(QQuickWindow *window, const QImage &image); private: QScopedPointer<ImageTexturesCachePrivate> d; }; ImageTexturesCache::ImageTexturesCache() : d(new ImageTexturesCachePrivate) { } ImageTexturesCache::~ImageTexturesCache() { } QSharedPointer<QSGTexture> ImageTexturesCache::loadTexture(QQuickWindow *window, const QImage &image, QQuickWindow::CreateTextureOptions options) { qint64 id = image.cacheKey(); QSharedPointer<QSGTexture> texture = d->cache.value(id).value(window).toStrongRef(); if (!texture) { auto cleanAndDelete = [this, window, id](QSGTexture* texture) { QHash<QWindow*, QWeakPointer<QSGTexture> >& textures = (d->cache)[id]; textures.remove(window); if (textures.isEmpty()) d->cache.remove(id); delete texture; }; texture = QSharedPointer<QSGTexture>(window->createTextureFromImage(image, options), cleanAndDelete); (d->cache)[id][window] = texture.toWeakRef(); } //if we have a cache in an atlas but our request cannot use an atlassed texture //create a new texture and use that //don't use removedFromAtlas() as that requires keeping a reference to the non atlased version if (!(options & QQuickWindow::TextureCanUseAtlas) && texture->isAtlasTexture()) { texture = QSharedPointer<QSGTexture>(window->createTextureFromImage(image, options)); } return texture; } QSharedPointer<QSGTexture> ImageTexturesCache::loadTexture(QQuickWindow *window, const QImage &image) { return loadTexture(window, image, 0); } Q_GLOBAL_STATIC(ImageTexturesCache, s_iconImageCache) DesktopIcon::DesktopIcon(QQuickItem *parent) : QQuickItem(parent), m_smooth(false), m_changed(false), m_active(false), m_selected(false) { setFlag(ItemHasContents, true); connect(qApp, &QGuiApplication::paletteChanged, this, [this]() { m_changed = true; update(); }); } DesktopIcon::~DesktopIcon() { } void DesktopIcon::setSource(const QVariant &icon) { if (m_source == icon) { return; } m_source = icon; m_changed = true; update(); emit sourceChanged(); } QVariant DesktopIcon::source() const { return m_source; } void DesktopIcon::setEnabled(const bool enabled) { if (enabled == QQuickItem::isEnabled()) { return; } QQuickItem::setEnabled(enabled); m_changed = true; update(); emit enabledChanged(); } void DesktopIcon::setActive(const bool active) { if (active == m_active) { return; } m_active = active; m_changed = true; update(); emit activeChanged(); } bool DesktopIcon::active() const { return m_active; } bool DesktopIcon::valid() const { return !m_source.isNull(); } void DesktopIcon::setSelected(const bool selected) { if (selected == m_selected) { return; } m_selected = selected; m_changed = true; update(); emit selectedChanged(); } bool DesktopIcon::selected() const { return m_selected; } int DesktopIcon::implicitWidth() const { return 32; } int DesktopIcon::implicitHeight() const { return 32; } void DesktopIcon::setSmooth(const bool smooth) { if (smooth == m_smooth) { return; } m_smooth = smooth; m_changed = true; update(); emit smoothChanged(); } bool DesktopIcon::smooth() const { return m_smooth; } QSGNode* DesktopIcon::updatePaintNode(QSGNode* node, QQuickItem::UpdatePaintNodeData* /*data*/) { if (m_source.isNull()) { delete node; return Q_NULLPTR; } if (m_changed || node == 0) { QImage img; const QSize size = QSize(width(), height()) * (window() ? window()->devicePixelRatio() : qApp->devicePixelRatio()); switch(m_source.type()){ case QVariant::Pixmap: img = m_source.value<QPixmap>().toImage(); break; case QVariant::Image: img = m_source.value<QImage>(); break; case QVariant::Bitmap: img = m_source.value<QBitmap>().toImage(); break; case QVariant::Icon: img = m_source.value<QIcon>().pixmap(size, iconMode(), QIcon::On).toImage(); break; case QVariant::String: img = findIcon(size); break; case QVariant::Brush: case QVariant::Color: //perhaps fill image instead? default: break; } if (img.isNull()){ img = QImage(size, QImage::Format_Alpha8); img.fill(Qt::transparent); } if (img.size() != size){ img = img.scaled(size, Qt::IgnoreAspectRatio, m_smooth ? Qt::SmoothTransformation : Qt::FastTransformation ); } m_changed = false; ManagedTextureNode* mNode = dynamic_cast<ManagedTextureNode*>(node); if (!mNode) { delete node; mNode = new ManagedTextureNode; } mNode->setTexture(s_iconImageCache->loadTexture(window(), img)); mNode->setRect(QRect(QPoint(0,0), QSize(width(), height()))); node = mNode; } return node; } void DesktopIcon::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry) { if (newGeometry.size() != oldGeometry.size()) { m_changed = true; update(); } QQuickItem::geometryChanged(newGeometry, oldGeometry); } void DesktopIcon::handleFinished(QNetworkAccessManager* qnam, QNetworkReply* reply) { if (reply->error() == QNetworkReply::NoError) { const QUrl possibleRedirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (!possibleRedirectUrl.isEmpty()) { const QUrl redirectUrl = reply->url().resolved(possibleRedirectUrl); if (redirectUrl == reply->url()) { // no infinite redirections thank you very much reply->deleteLater(); return; } reply->deleteLater(); QNetworkRequest request(possibleRedirectUrl); request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); QNetworkReply* newReply = qnam->get(request); connect(newReply, &QNetworkReply::readyRead, this, [this, newReply](){ handleReadyRead(newReply); }); connect(newReply, &QNetworkReply::finished, this, [this, qnam, newReply](){ handleFinished(qnam, newReply); }); return; } } } void DesktopIcon::handleReadyRead(QNetworkReply* reply) { if (reply->attribute(QNetworkRequest::RedirectionTargetAttribute).isNull()) { // We're handing the event loop back while doing network work, and it turns out // this fairly regularly results in things being deleted under us. So, just // handle that and crash less :) QPointer<DesktopIcon> me(this); QByteArray data; do { data.append(reply->read(32768)); // Because we are in the main thread, this could be potentially very expensive, so let's not block qApp->processEvents(); if(!me) { return; } } while(!reply->atEnd()); m_loadedImage = QImage::fromData(data); if (m_loadedImage.isNull()) { // broken image from data, inform the user of this with some useful broken-image thing... const QSize size = QSize(width(), height()) * (window() ? window()->devicePixelRatio() : qApp->devicePixelRatio()); m_loadedImage = QIcon::fromTheme("unknown").pixmap(size, iconMode(), QIcon::On).toImage(); } m_changed = true; update(); } } QImage DesktopIcon::findIcon(const QSize &size) { QImage img; QString iconSource = m_source.toString(); if (iconSource.startsWith("image://")){ QUrl iconUrl(iconSource); QString iconProviderId = iconUrl.host(); QString iconId = iconUrl.path(); QSize actualSize; QQuickImageProvider* imageProvider = dynamic_cast<QQuickImageProvider*>( qmlEngine(this)->imageProvider(iconProviderId)); if (!imageProvider) return img; switch(imageProvider->imageType()){ case QQmlImageProviderBase::Image: img = imageProvider->requestImage(iconId, &actualSize, size); break; case QQmlImageProviderBase::Pixmap: img = imageProvider->requestPixmap(iconId, &actualSize, size).toImage(); break; case QQmlImageProviderBase::Texture: case QQmlImageProviderBase::Invalid: case QQmlImageProviderBase::ImageResponse: //will have to investigate this more break; } } else if(iconSource.startsWith("http://") || iconSource.startsWith("https://")) { if(!m_loadedImage.isNull()) { return m_loadedImage.scaled(size, Qt::KeepAspectRatio, m_smooth ? Qt::SmoothTransformation : Qt::FastTransformation ); } QQmlEngine* engine = qmlEngine(this); QNetworkAccessManager* qnam; if (engine && (qnam = qmlEngine(this)->networkAccessManager())) { QNetworkRequest request(m_source.toUrl()); request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); QNetworkReply* reply = qnam->get(request); connect(reply, &QNetworkReply::readyRead, this, [this, reply](){ handleReadyRead(reply); }); connect(reply, &QNetworkReply::finished, this, [this, qnam, reply](){ handleFinished(qnam, reply); }); } // Temporary icon while we wait for the real image to load... img = QIcon::fromTheme("image-x-icon").pixmap(size, iconMode(), QIcon::On).toImage(); } else { if (iconSource.startsWith("qrc:/")){ iconSource = iconSource.mid(3); } QIcon icon(iconSource); if (icon.availableSizes().isEmpty()) { icon = QIcon::fromTheme(iconSource); } if (!icon.availableSizes().isEmpty()){ img = icon.pixmap(size, iconMode(), QIcon::On).toImage(); } } return img; } QIcon::Mode DesktopIcon::iconMode() const { if (!isEnabled()) { return QIcon::Disabled; } else if (m_selected) { return QIcon::Selected; } else if (m_active) { return QIcon::Active; } return QIcon::Normal; } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // PelotonDB // // device_test.cpp // // Identification: tests/logging/device_test.cpp // // Copyright (c) 201CACHE_SIZE, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "harness.h" #include <iostream> #include <fcntl.h> #include <string> #include <cstdio> #include <cstdlib> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <cstring> #include <cassert> #include <getopt.h> #include <cstdint> #include "backend/common/timer.h" #include "backend/storage/storage_manager.h" // Logging mode extern LoggingType peloton_logging_mode; namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Device Test //===--------------------------------------------------------------------===// class DeviceTest : public PelotonTest {}; #define CACHELINE_SIZE 64 #define roundup2(x, y) (((x)+((y)-1))&(~((y)-1))) /* if y is powers of two */ TEST_F(DeviceTest, BenchmarkTest) { peloton_logging_mode = LOGGING_TYPE_HDD_HDD; auto &storage_manager = storage::StorageManager::GetInstance(); size_t chunk_size = 1024; std::string source_buf(chunk_size, 'a'); auto data = reinterpret_cast<char *>(storage_manager.Allocate(BACKEND_TYPE_HDD, chunk_size)); EXPECT_NE(data, nullptr); std::memcpy(data, source_buf.c_str(), chunk_size); storage_manager.Sync(BACKEND_TYPE_HDD, data, 0); } } // End test namespace } // End peloton namespace <commit_msg>Updated device test<commit_after>//===----------------------------------------------------------------------===// // // PelotonDB // // device_test.cpp // // Identification: tests/logging/device_test.cpp // // Copyright (c) 201CACHE_SIZE, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "harness.h" #include <iostream> #include <fcntl.h> #include <string> #include <cstdio> #include <cstdlib> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <cstring> #include <cassert> #include <getopt.h> #include <cstdint> #include <string> #include <vector> #include "backend/common/timer.h" #include "backend/common/types.h" namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Device Test //===--------------------------------------------------------------------===// class DeviceTest : public PelotonTest {}; #define DATA_FILE_LEN 1024 * 1024 * UINT64_C(512) // 512 MB #define DATA_FILE_NAME "peloton.pmem" TEST_F(DeviceTest, BenchmarkTest) { std::vector<std::string> data_file_dirs = {NVM_DIR, HDD_DIR}; int data_fd; size_t data_file_len = DATA_FILE_LEN; oid_t num_trials = 3; std::size_t begin_chunk_size = 9, end_chunk_size = 21; // lg base 2 // Go over all the dirs for(auto data_file_dir : data_file_dirs){ // Create a data file std::string data_file_name = data_file_dir + DATA_FILE_NAME; std::cout << "Data File Name : " << data_file_name << "\n"; if ((data_fd = open(data_file_name.c_str(), O_CREAT | O_RDWR | O_DIRECT | O_SYNC, 0666)) < 0) { perror(data_file_name.c_str()); exit(EXIT_FAILURE); } // Allocate the data file if ((errno = posix_fallocate(data_fd, 0, data_file_len)) != 0) { perror("posix_fallocate"); exit(EXIT_FAILURE); } // Go over all the chunk sizes for(oid_t chunk_size_itr = begin_chunk_size; chunk_size_itr <= end_chunk_size; chunk_size_itr++){ // READS for(oid_t trial_itr = 0; trial_itr < num_trials; trial_itr++) { } // WRITES for(oid_t trial_itr = 0; trial_itr < num_trials; trial_itr++) { } } // Close the pmem file close(data_fd); } } } // End test namespace } // End peloton namespace <|endoftext|>
<commit_before><commit_msg>parser: fclose the whitelist after load<commit_after><|endoftext|>
<commit_before>#include <cap/version.h> #include <pycap/property_tree_wrappers.h> #include <pycap/energy_storage_device_wrappers.h> #include <boost/python.hpp> #include <string> #include <memory> #include <map> BOOST_PYTHON_MODULE(_pycap) { boost::python::class_<pycap::ElectrochemicalImpedanceSpectroscopyData, std::shared_ptr<pycap::ElectrochemicalImpedanceSpectroscopyData>>("ElectrochemicalImpedanceSpectroscopyData") .def("impedance_spectroscopy", &pycap::ElectrochemicalImpedanceSpectroscopyData::impedance_spectroscopy) .def("measure_impedance", &pycap::ElectrochemicalImpedanceSpectroscopyData::measure_impedance) .def("get_frequency", &pycap::ElectrochemicalImpedanceSpectroscopyData::get_frequency) .def("get_complex_impedance", &pycap::ElectrochemicalImpedanceSpectroscopyData::get_complex_impedance) .def("clear", &pycap::ElectrochemicalImpedanceSpectroscopyData::clear) ; boost::python::class_<pycap::EnergyStorageDeviceWrap, std::shared_ptr<pycap::EnergyStorageDeviceWrap>, boost::noncopyable>("EnergyStorageDevice", "Wrappers for Cap.EnergyStorageDevice", boost::python::no_init) .def("__init__", boost::python::make_constructor(&pycap::build_energy_storage_device) ) .def("get_voltage", (&pycap::get_voltage), boost::python::args("self") ) .def("get_current", (&pycap::get_current), boost::python::args("self") ) .def("evolve_one_time_step_constant_current", boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_constant_current), boost::python::args("self", "time_step", "current") ) .def("evolve_one_time_step_constant_voltage", boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_constant_voltage), boost::python::args("self", "time_step", "voltage") ) .def("evolve_one_time_step_constant_power" , boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_constant_power ), boost::python::args("self", "time_step", "load" ) ) .def("evolve_one_time_step_constant_load" , boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_constant_load ), boost::python::args("self", "time_step", "power" ) ) .def("evolve_one_time_step_changing_current", boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_changing_current), boost::python::args("self", "time_step", "current") ) .def("evolve_one_time_step_changing_voltage", boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_changing_voltage), boost::python::args("self", "time_step", "voltage") ) .def("evolve_one_time_step_changing_power" , boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_changing_power ), boost::python::args("self", "time_step", "power" ) ) .def("evolve_one_time_step_changing_load" , boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_changing_load ), boost::python::args("self", "time_step", "load" ) ) .def("compute_equivalent_circuit", &pycap::compute_equivalent_circuit, "Return the PropertyTree to build an equivalent circuit model", boost::python::args("ptree") ) .staticmethod("compute_equivalent_circuit") // .def_pickle(pycap::serializable_class_pickle_support<cap::EnergyStorageDevice>()) ; boost::python::register_ptr_to_python<std::shared_ptr<cap::EnergyStorageDevice>>(); boost::python::scope().attr("__version__" ) = cap::version() ; boost::python::scope().attr("__git_branch__" ) = cap::git_branch() ; boost::python::scope().attr("__git_commit_hash__") = cap::git_commit_hash(); boost::python::class_<boost::property_tree::ptree,std::shared_ptr<boost::property_tree::ptree>>("PropertyTree", "Wrappers for Boost.PropertyTree") .def("get_double" , &pycap::get_double , "Get the double at the given path." , boost::python::args("self", "path") ) .def("get_string" , &pycap::get_string , "Get the string at the given path." , boost::python::args("self", "path") ) .def("get_int" , &pycap::get_int , "Get the integer at the given path." , boost::python::args("self", "path") ) .def("get_bool" , &pycap::get_bool , "Get the boolean at the given path." , boost::python::args("self", "path") ) .def("get_double_with_default_value", &pycap::get_double_with_default_value, "Get the double at the given path or return default_value." , boost::python::args("self", "path", "default_value") ) .def("get_string_with_default_value", &pycap::get_string_with_default_value, "Get the string at the given path or return default_value." , boost::python::args("self", "path", "default_value") ) .def("get_int_with_default_value" , &pycap::get_int_with_default_value , "Get the integer at the given path or return default_value." , boost::python::args("self", "path", "default_value") ) .def("get_bool_with_default_value" , &pycap::get_bool_with_default_value , "Get the boolean at the given path or return default_value." , boost::python::args("self", "path", "default_value") ) .def("put_double" , &pycap::put_double , "Set the node at the given path to the supplied value." , boost::python::args("self", "path", "value") ) .def("put_string" , &pycap::put_string , "Set the node at the given path to the supplied value." , boost::python::args("self", "path", "value") ) .def("put_int" , &pycap::put_int , "Set the node at the given path to the supplied value." , boost::python::args("self", "path", "value") ) .def("put_bool" , &pycap::put_bool , "Set the node at the given path to the supplied value." , boost::python::args("self", "path", "value") ) .def("get_array_double" , &pycap::get_array_double , "Get comma separated array of double." , boost::python::args("self", "path") ) .def("get_array_string" , &pycap::get_array_string , "Get comma separated array of string." , boost::python::args("self", "path") ) .def("get_array_int" , &pycap::get_array_int , "Get comma separated array of integer." , boost::python::args("self", "path") ) .def("get_array_bool" , &pycap::get_array_bool , "Get comma separated array of boolean." , boost::python::args("self", "path") ) .def("parse_xml" , &pycap::parse_xml , "Read the input file at XML format and populate the PropertyTree." , boost::python::args("self", "filename") ) .def("parse_json" , &pycap::parse_json , "Read the input file at JSON format and populate the PropertyTree.", boost::python::args("self", "filename") ) .def("parse_info" , &pycap::parse_info , "Read the input file at INFO format and populate the PropertyTree.", boost::python::args("self", "filename") ) .def("get_child" , &pycap::get_child , "Get the child at the given path, or throw ptree_bad_path." , boost::python::args("self", "path") ) .def_pickle(pycap::serializable_class_pickle_support<boost::property_tree::ptree>()) ; } <commit_msg>disable cpp signature in python docstring<commit_after>#include <cap/version.h> #include <pycap/property_tree_wrappers.h> #include <pycap/energy_storage_device_wrappers.h> #include <boost/python.hpp> #include <string> #include <memory> #include <map> BOOST_PYTHON_MODULE(_pycap) { // Deprecated stuff boost::python::class_<pycap::ElectrochemicalImpedanceSpectroscopyData, std::shared_ptr<pycap::ElectrochemicalImpedanceSpectroscopyData>>("ElectrochemicalImpedanceSpectroscopyData") .def("impedance_spectroscopy", &pycap::ElectrochemicalImpedanceSpectroscopyData::impedance_spectroscopy) .def("measure_impedance", &pycap::ElectrochemicalImpedanceSpectroscopyData::measure_impedance) .def("get_frequency", &pycap::ElectrochemicalImpedanceSpectroscopyData::get_frequency) .def("get_complex_impedance", &pycap::ElectrochemicalImpedanceSpectroscopyData::get_complex_impedance) .def("clear", &pycap::ElectrochemicalImpedanceSpectroscopyData::clear) ; boost::python::docstring_options doc_options; doc_options.enable_user_defined(); doc_options.disable_py_signatures(); doc_options.disable_cpp_signatures(); boost::python::class_<pycap::EnergyStorageDeviceWrap, std::shared_ptr<pycap::EnergyStorageDeviceWrap>, boost::noncopyable>("EnergyStorageDevice", "Wrappers for Cap.EnergyStorageDevice", boost::python::no_init) .def("__init__", boost::python::make_constructor(&pycap::build_energy_storage_device) ) .def("get_voltage", (&pycap::get_voltage), boost::python::args("self") ) .def("get_current", (&pycap::get_current), boost::python::args("self") ) .def("evolve_one_time_step_constant_current", boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_constant_current), boost::python::args("self", "time_step", "current") ) .def("evolve_one_time_step_constant_voltage", boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_constant_voltage), boost::python::args("self", "time_step", "voltage") ) .def("evolve_one_time_step_constant_power" , boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_constant_power ), boost::python::args("self", "time_step", "load" ) ) .def("evolve_one_time_step_constant_load" , boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_constant_load ), boost::python::args("self", "time_step", "power" ) ) .def("evolve_one_time_step_changing_current", boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_changing_current), boost::python::args("self", "time_step", "current") ) .def("evolve_one_time_step_changing_voltage", boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_changing_voltage), boost::python::args("self", "time_step", "voltage") ) .def("evolve_one_time_step_changing_power" , boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_changing_power ), boost::python::args("self", "time_step", "power" ) ) .def("evolve_one_time_step_changing_load" , boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_changing_load ), boost::python::args("self", "time_step", "load" ) ) .def("compute_equivalent_circuit", &pycap::compute_equivalent_circuit, "Return the PropertyTree to build an equivalent circuit model", boost::python::args("ptree") ) .staticmethod("compute_equivalent_circuit") // .def_pickle(pycap::serializable_class_pickle_support<cap::EnergyStorageDevice>()) ; boost::python::register_ptr_to_python<std::shared_ptr<cap::EnergyStorageDevice>>(); boost::python::scope().attr("__version__" ) = cap::version() ; boost::python::scope().attr("__git_branch__" ) = cap::git_branch() ; boost::python::scope().attr("__git_commit_hash__") = cap::git_commit_hash(); boost::python::class_<boost::property_tree::ptree,std::shared_ptr<boost::property_tree::ptree>>("PropertyTree", "Wrappers for Boost.PropertyTree") .def("get_double" , &pycap::get_double , "Get the double at the given path." , boost::python::args("self", "path") ) .def("get_string" , &pycap::get_string , "Get the string at the given path." , boost::python::args("self", "path") ) .def("get_int" , &pycap::get_int , "Get the integer at the given path." , boost::python::args("self", "path") ) .def("get_bool" , &pycap::get_bool , "Get the boolean at the given path." , boost::python::args("self", "path") ) .def("get_double_with_default_value", &pycap::get_double_with_default_value, "Get the double at the given path or return default_value." , boost::python::args("self", "path", "default_value") ) .def("get_string_with_default_value", &pycap::get_string_with_default_value, "Get the string at the given path or return default_value." , boost::python::args("self", "path", "default_value") ) .def("get_int_with_default_value" , &pycap::get_int_with_default_value , "Get the integer at the given path or return default_value." , boost::python::args("self", "path", "default_value") ) .def("get_bool_with_default_value" , &pycap::get_bool_with_default_value , "Get the boolean at the given path or return default_value." , boost::python::args("self", "path", "default_value") ) .def("put_double" , &pycap::put_double , "Set the node at the given path to the supplied value." , boost::python::args("self", "path", "value") ) .def("put_string" , &pycap::put_string , "Set the node at the given path to the supplied value." , boost::python::args("self", "path", "value") ) .def("put_int" , &pycap::put_int , "Set the node at the given path to the supplied value." , boost::python::args("self", "path", "value") ) .def("put_bool" , &pycap::put_bool , "Set the node at the given path to the supplied value." , boost::python::args("self", "path", "value") ) .def("get_array_double" , &pycap::get_array_double , "Get comma separated array of double." , boost::python::args("self", "path") ) .def("get_array_string" , &pycap::get_array_string , "Get comma separated array of string." , boost::python::args("self", "path") ) .def("get_array_int" , &pycap::get_array_int , "Get comma separated array of integer." , boost::python::args("self", "path") ) .def("get_array_bool" , &pycap::get_array_bool , "Get comma separated array of boolean." , boost::python::args("self", "path") ) .def("parse_xml" , &pycap::parse_xml , "Read the input file at XML format and populate the PropertyTree." , boost::python::args("self", "filename") ) .def("parse_json" , &pycap::parse_json , "Read the input file at JSON format and populate the PropertyTree.", boost::python::args("self", "filename") ) .def("parse_info" , &pycap::parse_info , "Read the input file at INFO format and populate the PropertyTree.", boost::python::args("self", "filename") ) .def("get_child" , &pycap::get_child , "Get the child at the given path, or throw ptree_bad_path." , boost::python::args("self", "path") ) .def_pickle(pycap::serializable_class_pickle_support<boost::property_tree::ptree>()) ; } <|endoftext|>
<commit_before>/* AFE Firmware for smart home devices LICENSE: https://github.com/tschaban/AFE-Firmware/blob/master/LICENSE DOC: http://smart-house.adrian.czabanowski.com/afe-firmware-pl/ */ #include "AFE-Switch.h" AFESwitch::AFESwitch(){}; AFESwitch::AFESwitch(uint8_t id) { begin(id); } void AFESwitch::begin(uint8_t id) { AFEDataAccess Data; SwitchConfiguration = Data.getSwitchConfiguration(id); pinMode(SwitchConfiguration.gpio, INPUT_PULLUP); state = digitalRead(SwitchConfiguration.gpio); previousState = state; Led.begin(0); _initialized = true; } boolean AFESwitch::getState() { return state; } boolean AFESwitch::isPressed() { if (pressed) { Led.blink(50); pressed = false; return true; } else { return false; } } boolean AFESwitch::is5s() { if (pressed4fiveSeconds) { pressed4fiveSeconds = false; return true; } else { return false; } } boolean AFESwitch::is10s() { if (pressed4tenSeconds) { pressed4tenSeconds = false; Led.blink(50); return true; } else { return false; } } void AFESwitch::listener() { if (_initialized) { boolean currentState = digitalRead(SwitchConfiguration.gpio); unsigned long time = millis(); if (currentState != previousState) { // buttons has been pressed if (startTime == 0) { // starting timer. used for switch sensitiveness startTime = time; } if (time - startTime >= SwitchConfiguration.sensitiveness) { // switch prssed, sensitiveness // taken into account, processing // event if (SwitchConfiguration.type == SWITCH_TYPE_MONO) { if (!_pressed) { // This is set only once when switch is pressed state = !state; _pressed = true; pressed = true; } /* Code only for Mulitifunction switch: pressed for 5 and 10 seconds */ if (SwitchConfiguration.functionality == SWITCH_MULTI) { if (time - startTime >= 10000 && !pressed4tenSeconds) { pressed4tenSeconds = true; } if (time - startTime >= 5000 && !_pressed4fiveSeconds) { Led.blink(500); _pressed4fiveSeconds = true; } } } else { // This is BI-stable code state = !state; previousState = currentState; pressed = true; } } } else if (currentState == previousState && startTime > 0) { /* Code only for Mulitifunction switch: pressed for 5 and 10 seconds */ if (SwitchConfiguration.functionality == SWITCH_MULTI) { if ( // SwitchConfiguration.type == SWITCH_TYPE_MONO && time - startTime >= 5000 && time - startTime < 10000) { pressed4fiveSeconds = true; } _pressed4fiveSeconds = false; } startTime = 0; _pressed = false; } } } uint8_t AFESwitch::getFunctionality() { return SwitchConfiguration.functionality; } <commit_msg>Removed LED signal<commit_after>/* AFE Firmware for smart home devices LICENSE: https://github.com/tschaban/AFE-Firmware/blob/master/LICENSE DOC: http://smart-house.adrian.czabanowski.com/afe-firmware-pl/ */ #include "AFE-Switch.h" AFESwitch::AFESwitch(){}; AFESwitch::AFESwitch(uint8_t id) { begin(id); } void AFESwitch::begin(uint8_t id) { AFEDataAccess Data; SwitchConfiguration = Data.getSwitchConfiguration(id); pinMode(SwitchConfiguration.gpio, INPUT_PULLUP); state = digitalRead(SwitchConfiguration.gpio); previousState = state; Led.begin(0); _initialized = true; } boolean AFESwitch::getState() { return state; } boolean AFESwitch::isPressed() { if (pressed) { pressed = false; return true; } else { return false; } } boolean AFESwitch::is5s() { if (pressed4fiveSeconds) { pressed4fiveSeconds = false; return true; } else { return false; } } boolean AFESwitch::is10s() { if (pressed4tenSeconds) { pressed4tenSeconds = false; return true; } else { return false; } } void AFESwitch::listener() { if (_initialized) { boolean currentState = digitalRead(SwitchConfiguration.gpio); unsigned long time = millis(); if (currentState != previousState) { // buttons has been pressed if (startTime == 0) { // starting timer. used for switch sensitiveness startTime = time; } if (time - startTime >= SwitchConfiguration.sensitiveness) { // switch prssed, sensitiveness // taken into account, processing // event if (SwitchConfiguration.type == SWITCH_TYPE_MONO) { if (!_pressed) { // This is set only once when switch is pressed state = !state; _pressed = true; pressed = true; } /* Code only for Mulitifunction switch: pressed for 5 and 10 seconds */ if (SwitchConfiguration.functionality == SWITCH_MULTI) { if (time - startTime >= 10000 && !pressed4tenSeconds) { pressed4tenSeconds = true; } if (time - startTime >= 5000 && !_pressed4fiveSeconds) { Led.blink(500); _pressed4fiveSeconds = true; } } } else { // This is BI-stable code state = !state; previousState = currentState; pressed = true; } } } else if (currentState == previousState && startTime > 0) { /* Code only for Mulitifunction switch: pressed for 5 and 10 seconds */ if (SwitchConfiguration.functionality == SWITCH_MULTI) { if ( // SwitchConfiguration.type == SWITCH_TYPE_MONO && time - startTime >= 5000 && time - startTime < 10000) { pressed4fiveSeconds = true; } _pressed4fiveSeconds = false; } startTime = 0; _pressed = false; } } } uint8_t AFESwitch::getFunctionality() { return SwitchConfiguration.functionality; } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #include <stdarg.h> #include "tlib/print.hpp" #include "tlib/file.hpp" namespace { size_t strlen(const char* c){ size_t s = 0; while(*c++){ ++s; } return s; } } //end of anonymous namespace void tlib::print(char c){ tlib::write(1, &c, 1, 0); } void tlib::print(const char* s){ tlib::write(1, s, strlen(s), 0); } void tlib::print(const std::string& s){ tlib::write(1, s.c_str(), s.size(), 0); } void log(const char* s){ asm volatile("mov rax, 2; mov rbx, %[s]; int 50" : //No outputs : [s] "g" (reinterpret_cast<size_t>(s)) : "rax", "rbx"); } void tlib::print(uint8_t v){ print(std::to_string(v)); } void tlib::print(uint16_t v){ print(std::to_string(v)); } void tlib::print(uint32_t v){ print(std::to_string(v)); } void tlib::print(uint64_t v){ print(std::to_string(v)); } void tlib::print(int8_t v){ print(std::to_string(v)); } void tlib::print(int16_t v){ print(std::to_string(v)); } void tlib::print(int32_t v){ print(std::to_string(v)); } void tlib::print(int64_t v){ print(std::to_string(v)); } void tlib::set_canonical(bool can){ size_t value = can; asm volatile("mov rax, 0x20; mov rbx, %[value]; int 50;" : : [value] "g" (value) : "rax", "rbx"); } void tlib::set_mouse(bool m){ size_t value = m; asm volatile("mov rax, 0x21; mov rbx, %[value]; int 50;" : : [value] "g" (value) : "rax", "rbx"); } size_t tlib::read_input(char* buffer, size_t max){ size_t value; asm volatile("mov rax, 0x10; mov rbx, %[buffer]; mov rcx, %[max]; int 50; mov %[read], rax" : [read] "=m" (value) : [buffer] "g" (buffer), [max] "g" (max) : "rax", "rbx", "rcx"); return value; } size_t tlib::read_input(char* buffer, size_t max, size_t ms){ size_t value; asm volatile("mov rax, 0x11; mov rbx, %[buffer]; mov rcx, %[max]; mov rdx, %[ms]; int 50; mov %[read], rax" : [read] "=m" (value) : [buffer] "g" (buffer), [max] "g" (max), [ms] "g" (ms) : "rax", "rbx", "rcx"); return value; } std::keycode tlib::read_input_raw(){ size_t value; asm volatile("mov rax, 0x12; int 50; mov %[input], rax" : [input] "=m" (value) : : "rax"); return static_cast<std::keycode>(value); } std::keycode tlib::read_input_raw(size_t ms){ size_t value; asm volatile("mov rax, 0x13; mov rbx, %[ms]; int 50; mov %[input], rax" : [input] "=m" (value) : [ms] "g" (ms) : "rax"); return static_cast<std::keycode>(value); } void tlib::clear(){ asm volatile("mov rax, 100; int 50;" : //No outputs : //No inputs : "rax"); } size_t tlib::get_columns(){ size_t value; asm volatile("mov rax, 101; int 50; mov %[columns], rax" : [columns] "=m" (value) : //No inputs : "rax"); return value; } size_t tlib::get_rows(){ size_t value; asm volatile("mov rax, 102; int 50; mov %[rows], rax" : [rows] "=m" (value) : //No inputs : "rax"); return value; } void tlib::print_line(){ print('\n'); } void tlib::print_line(const char* s){ print(s); print_line(); } void tlib::print_line(size_t v){ print(v); print_line(); } void tlib::print_line(const std::string& s){ print(s); print_line(); } void tlib::user_logf(const char* s, ...){ va_list va; va_start(va, s); char buffer[512]; vsprintf_raw(buffer, 512, s, va); log(buffer); va_end(va); } namespace tlib { #include "printf_def.hpp" void __printf(const std::string& formatted){ print(formatted); } void __printf_raw(const char* formatted){ print(formatted); } } // end of namespace tlib <commit_msg>Fix the fd<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #include <stdarg.h> #include "tlib/print.hpp" #include "tlib/file.hpp" namespace { size_t strlen(const char* c){ size_t s = 0; while(*c++){ ++s; } return s; } } //end of anonymous namespace void tlib::print(char c){ tlib::write(2, &c, 1, 0); } void tlib::print(const char* s){ tlib::write(2, s, strlen(s), 0); } void tlib::print(const std::string& s){ tlib::write(2, s.c_str(), s.size(), 0); } void log(const char* s){ asm volatile("mov rax, 2; mov rbx, %[s]; int 50" : //No outputs : [s] "g" (reinterpret_cast<size_t>(s)) : "rax", "rbx"); } void tlib::print(uint8_t v){ print(std::to_string(v)); } void tlib::print(uint16_t v){ print(std::to_string(v)); } void tlib::print(uint32_t v){ print(std::to_string(v)); } void tlib::print(uint64_t v){ print(std::to_string(v)); } void tlib::print(int8_t v){ print(std::to_string(v)); } void tlib::print(int16_t v){ print(std::to_string(v)); } void tlib::print(int32_t v){ print(std::to_string(v)); } void tlib::print(int64_t v){ print(std::to_string(v)); } void tlib::set_canonical(bool can){ size_t value = can; asm volatile("mov rax, 0x20; mov rbx, %[value]; int 50;" : : [value] "g" (value) : "rax", "rbx"); } void tlib::set_mouse(bool m){ size_t value = m; asm volatile("mov rax, 0x21; mov rbx, %[value]; int 50;" : : [value] "g" (value) : "rax", "rbx"); } size_t tlib::read_input(char* buffer, size_t max){ size_t value; asm volatile("mov rax, 0x10; mov rbx, %[buffer]; mov rcx, %[max]; int 50; mov %[read], rax" : [read] "=m" (value) : [buffer] "g" (buffer), [max] "g" (max) : "rax", "rbx", "rcx"); return value; } size_t tlib::read_input(char* buffer, size_t max, size_t ms){ size_t value; asm volatile("mov rax, 0x11; mov rbx, %[buffer]; mov rcx, %[max]; mov rdx, %[ms]; int 50; mov %[read], rax" : [read] "=m" (value) : [buffer] "g" (buffer), [max] "g" (max), [ms] "g" (ms) : "rax", "rbx", "rcx"); return value; } std::keycode tlib::read_input_raw(){ size_t value; asm volatile("mov rax, 0x12; int 50; mov %[input], rax" : [input] "=m" (value) : : "rax"); return static_cast<std::keycode>(value); } std::keycode tlib::read_input_raw(size_t ms){ size_t value; asm volatile("mov rax, 0x13; mov rbx, %[ms]; int 50; mov %[input], rax" : [input] "=m" (value) : [ms] "g" (ms) : "rax"); return static_cast<std::keycode>(value); } void tlib::clear(){ asm volatile("mov rax, 100; int 50;" : //No outputs : //No inputs : "rax"); } size_t tlib::get_columns(){ size_t value; asm volatile("mov rax, 101; int 50; mov %[columns], rax" : [columns] "=m" (value) : //No inputs : "rax"); return value; } size_t tlib::get_rows(){ size_t value; asm volatile("mov rax, 102; int 50; mov %[rows], rax" : [rows] "=m" (value) : //No inputs : "rax"); return value; } void tlib::print_line(){ print('\n'); } void tlib::print_line(const char* s){ print(s); print_line(); } void tlib::print_line(size_t v){ print(v); print_line(); } void tlib::print_line(const std::string& s){ print(s); print_line(); } void tlib::user_logf(const char* s, ...){ va_list va; va_start(va, s); char buffer[512]; vsprintf_raw(buffer, 512, s, va); log(buffer); va_end(va); } namespace tlib { #include "printf_def.hpp" void __printf(const std::string& formatted){ print(formatted); } void __printf_raw(const char* formatted){ print(formatted); } } // end of namespace tlib <|endoftext|>
<commit_before>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Clifford Wolf <[email protected]> * Copyright (C) 2018 Miodrag Milanovic <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #ifndef NO_GUI #include <QApplication> #include "application.h" #include "mainwindow.h" #endif #ifndef NO_PYTHON #include "pybindings.h" #endif #include <boost/algorithm/string/join.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/program_options.hpp> #include <fstream> #include <iostream> #include "command.h" #include "design_utils.h" #include "jsonparse.h" #include "jsonwrite.h" #include "log.h" #include "timing.h" #include "util.h" #include "version.h" NEXTPNR_NAMESPACE_BEGIN CommandHandler::CommandHandler(int argc, char **argv) : argc(argc), argv(argv) { log_streams.clear(); } bool CommandHandler::parseOptions() { options.add(getGeneralOptions()).add(getArchOptions()); try { po::parsed_options parsed = po::command_line_parser(argc, argv) .style(po::command_line_style::default_style ^ po::command_line_style::allow_guessing) .options(options) .positional(pos) .run(); po::store(parsed, vm); po::notify(vm); return true; } catch (std::exception &e) { std::cout << e.what() << "\n"; return false; } } bool CommandHandler::executeBeforeContext() { if (vm.count("help") || argc == 1) { std::cerr << boost::filesystem::basename(argv[0]) << " -- Next Generation Place and Route (git sha1 " GIT_COMMIT_HASH_STR ")\n"; std::cerr << options << "\n"; return argc != 1; } if (vm.count("version")) { std::cerr << boost::filesystem::basename(argv[0]) << " -- Next Generation Place and Route (git sha1 " GIT_COMMIT_HASH_STR ")\n"; return true; } validate(); if (vm.count("quiet")) { log_streams.push_back(std::make_pair(&std::cerr, LogLevel::WARNING_MSG)); } else { log_streams.push_back(std::make_pair(&std::cerr, LogLevel::LOG_MSG)); } if (vm.count("log")) { std::string logfilename = vm["log"].as<std::string>(); logfile.open(logfilename); if (!logfile.is_open()) log_error("Failed to open log file '%s' for writing.\n", logfilename.c_str()); log_streams.push_back(std::make_pair(&logfile, LogLevel::LOG_MSG)); } return false; } po::options_description CommandHandler::getGeneralOptions() { po::options_description general("General options"); general.add_options()("help,h", "show help"); general.add_options()("verbose,v", "verbose output"); general.add_options()("quiet,q", "quiet mode, only errors and warnings displayed"); general.add_options()("log,l", po::value<std::string>(), "log file, all log messages are written to this file regardless of -q"); general.add_options()("debug", "debug output"); general.add_options()("force,f", "keep running after errors"); #ifndef NO_GUI general.add_options()("gui", "start gui"); general.add_options()("gui-no-aa", "disable anti aliasing (use together with --gui option)"); #endif #ifndef NO_PYTHON general.add_options()("run", po::value<std::vector<std::string>>(), "python file to execute instead of default flow"); pos.add("run", -1); general.add_options()("pre-pack", po::value<std::vector<std::string>>(), "python file to run before packing"); general.add_options()("pre-place", po::value<std::vector<std::string>>(), "python file to run before placement"); general.add_options()("pre-route", po::value<std::vector<std::string>>(), "python file to run before routing"); general.add_options()("post-route", po::value<std::vector<std::string>>(), "python file to run after routing"); #endif general.add_options()("json", po::value<std::string>(), "JSON design file to ingest"); general.add_options()("write", po::value<std::string>(), "JSON design file to write"); general.add_options()("seed", po::value<int>(), "seed value for random number generator"); general.add_options()("randomize-seed,r", "randomize seed value for random number generator"); general.add_options()( "placer", po::value<std::string>(), std::string("placer algorithm to use; available: " + boost::algorithm::join(Arch::availablePlacers, ", ") + "; default: " + Arch::defaultPlacer) .c_str()); general.add_options()("slack_redist_iter", po::value<int>(), "number of iterations between slack redistribution"); general.add_options()("cstrweight", po::value<float>(), "placer weighting for relative constraint satisfaction"); general.add_options()("starttemp", po::value<float>(), "placer SA start temperature"); general.add_options()("placer-budgets", "use budget rather than criticality in placer timing weights"); general.add_options()("pack-only", "pack design only without placement or routing"); general.add_options()("ignore-loops", "ignore combinational loops in timing analysis"); general.add_options()("version,V", "show version"); general.add_options()("test", "check architecture database integrity"); general.add_options()("freq", po::value<double>(), "set target frequency for design in MHz"); general.add_options()("timing-allow-fail", "allow timing to fail in design"); general.add_options()("no-tmdriv", "disable timing-driven placement"); general.add_options()("save", po::value<std::string>(), "project file to write"); general.add_options()("load", po::value<std::string>(), "project file to read"); return general; } void CommandHandler::setupContext(Context *ctx) { if (vm.count("verbose")) { ctx->verbose = true; } if (vm.count("debug")) { ctx->verbose = true; ctx->debug = true; } if (vm.count("force")) { ctx->force = true; } if (vm.count("seed")) { ctx->rngseed(vm["seed"].as<int>()); } if (vm.count("randomize-seed")) { srand(time(NULL)); int r; do { r = rand(); } while (r == 0); ctx->rngseed(r); } if (vm.count("slack_redist_iter")) { ctx->slack_redist_iter = vm["slack_redist_iter"].as<int>(); if (vm.count("freq") && vm["freq"].as<double>() == 0) { ctx->auto_freq = true; #ifndef NO_GUI if (!vm.count("gui")) #endif log_warning("Target frequency not specified. Will optimise for max frequency.\n"); } } if (vm.count("ignore-loops")) { settings->set("timing/ignoreLoops", true); } if (vm.count("timing-allow-fail")) { settings->set("timing/allowFail", true); } if (vm.count("placer")) { std::string placer = vm["placer"].as<std::string>(); if (std::find(Arch::availablePlacers.begin(), Arch::availablePlacers.end(), placer) == Arch::availablePlacers.end()) log_error("Placer algorithm '%s' is not supported (available options: %s)\n", placer.c_str(), boost::algorithm::join(Arch::availablePlacers, ", ").c_str()); settings->set("placer", placer); } else { settings->set("placer", Arch::defaultPlacer); } if (vm.count("cstrweight")) { settings->set("placer1/constraintWeight", vm["cstrweight"].as<float>()); } if (vm.count("starttemp")) { settings->set("placer1/startTemp", vm["starttemp"].as<float>()); } if (vm.count("placer-budgets")) { settings->set("placer1/budgetBased", true); } if (vm.count("freq")) { auto freq = vm["freq"].as<double>(); if (freq > 0) ctx->target_freq = freq * 1e6; } ctx->timing_driven = true; if (vm.count("no-tmdriv")) ctx->timing_driven = false; } int CommandHandler::executeMain(std::unique_ptr<Context> ctx) { if (vm.count("test")) { ctx->archcheck(); return 0; } #ifndef NO_GUI if (vm.count("gui")) { Application a(argc, argv, (vm.count("gui-no-aa") > 0)); MainWindow w(std::move(ctx), chipArgs); try { if (vm.count("json")) { std::string filename = vm["json"].as<std::string>(); std::ifstream f(filename); if (!parse_json_file(f, filename, w.getContext())) log_error("Loading design failed.\n"); customAfterLoad(w.getContext()); w.notifyChangeContext(); w.updateLoaded(); } else if (vm.count("load")) { w.projectLoad(vm["load"].as<std::string>()); } else w.notifyChangeContext(); } catch (log_execution_error_exception) { // show error is handled by gui itself } w.show(); return a.exec(); } #endif if (vm.count("json")) { std::string filename = vm["json"].as<std::string>(); std::ifstream f(filename); if (!parse_json_file(f, filename, ctx.get())) log_error("Loading design failed.\n"); customAfterLoad(ctx.get()); } #ifndef NO_PYTHON init_python(argv[0], true); python_export_global("ctx", *ctx); if (vm.count("run")) { std::vector<std::string> files = vm["run"].as<std::vector<std::string>>(); for (auto filename : files) execute_python_file(filename.c_str()); } else #endif if (vm.count("json") || vm.count("load")) { run_script_hook("pre-pack"); if (!ctx->pack() && !ctx->force) log_error("Packing design failed.\n"); assign_budget(ctx.get()); ctx->check(); print_utilisation(ctx.get()); run_script_hook("pre-place"); if (!vm.count("pack-only")) { if (!ctx->place() && !ctx->force) log_error("Placing design failed.\n"); ctx->check(); run_script_hook("pre-route"); if (!ctx->route() && !ctx->force) log_error("Routing design failed.\n"); } run_script_hook("post-route"); customBitstream(ctx.get()); } if (vm.count("write")) { std::string filename = vm["write"].as<std::string>(); std::ofstream f(filename); if (!write_json_file(f, filename, ctx.get())) log_error("Loading design failed.\n"); } if (vm.count("save")) { project.save(ctx.get(), vm["save"].as<std::string>()); } #ifndef NO_PYTHON deinit_python(); #endif return had_nonfatal_error ? 1 : 0; } void CommandHandler::conflicting_options(const boost::program_options::variables_map &vm, const char *opt1, const char *opt2) { if (vm.count(opt1) && !vm[opt1].defaulted() && vm.count(opt2) && !vm[opt2].defaulted()) { std::string msg = "Conflicting options '" + std::string(opt1) + "' and '" + std::string(opt2) + "'."; log_error("%s\n", msg.c_str()); } } void CommandHandler::printFooter() { int warning_count = get_or_default(message_count_by_level, LogLevel::WARNING_MSG, 0), error_count = get_or_default(message_count_by_level, LogLevel::ERROR_MSG, 0); if (warning_count > 0 || error_count > 0) log_always("%d warning%s, %d error%s\n", warning_count, warning_count == 1 ? "" : "s", error_count, error_count == 1 ? "" : "s"); } int CommandHandler::exec() { try { if (!parseOptions()) return -1; if (executeBeforeContext()) return 0; std::unique_ptr<Context> ctx; if (vm.count("load") && vm.count("gui") == 0) { ctx = project.load(vm["load"].as<std::string>()); } else { ctx = createContext(); } settings = std::unique_ptr<Settings>(new Settings(ctx.get())); setupContext(ctx.get()); setupArchContext(ctx.get()); int rc = executeMain(std::move(ctx)); printFooter(); return rc; } catch (log_execution_error_exception) { printFooter(); return -1; } } void CommandHandler::run_script_hook(const std::string &name) { #ifndef NO_PYTHON if (vm.count(name)) { std::vector<std::string> files = vm[name].as<std::vector<std::string>>(); for (auto filename : files) execute_python_file(filename.c_str()); } #endif } NEXTPNR_NAMESPACE_END <commit_msg>Proper save message<commit_after>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Clifford Wolf <[email protected]> * Copyright (C) 2018 Miodrag Milanovic <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #ifndef NO_GUI #include <QApplication> #include "application.h" #include "mainwindow.h" #endif #ifndef NO_PYTHON #include "pybindings.h" #endif #include <boost/algorithm/string/join.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/program_options.hpp> #include <fstream> #include <iostream> #include "command.h" #include "design_utils.h" #include "jsonparse.h" #include "jsonwrite.h" #include "log.h" #include "timing.h" #include "util.h" #include "version.h" NEXTPNR_NAMESPACE_BEGIN CommandHandler::CommandHandler(int argc, char **argv) : argc(argc), argv(argv) { log_streams.clear(); } bool CommandHandler::parseOptions() { options.add(getGeneralOptions()).add(getArchOptions()); try { po::parsed_options parsed = po::command_line_parser(argc, argv) .style(po::command_line_style::default_style ^ po::command_line_style::allow_guessing) .options(options) .positional(pos) .run(); po::store(parsed, vm); po::notify(vm); return true; } catch (std::exception &e) { std::cout << e.what() << "\n"; return false; } } bool CommandHandler::executeBeforeContext() { if (vm.count("help") || argc == 1) { std::cerr << boost::filesystem::basename(argv[0]) << " -- Next Generation Place and Route (git sha1 " GIT_COMMIT_HASH_STR ")\n"; std::cerr << options << "\n"; return argc != 1; } if (vm.count("version")) { std::cerr << boost::filesystem::basename(argv[0]) << " -- Next Generation Place and Route (git sha1 " GIT_COMMIT_HASH_STR ")\n"; return true; } validate(); if (vm.count("quiet")) { log_streams.push_back(std::make_pair(&std::cerr, LogLevel::WARNING_MSG)); } else { log_streams.push_back(std::make_pair(&std::cerr, LogLevel::LOG_MSG)); } if (vm.count("log")) { std::string logfilename = vm["log"].as<std::string>(); logfile.open(logfilename); if (!logfile.is_open()) log_error("Failed to open log file '%s' for writing.\n", logfilename.c_str()); log_streams.push_back(std::make_pair(&logfile, LogLevel::LOG_MSG)); } return false; } po::options_description CommandHandler::getGeneralOptions() { po::options_description general("General options"); general.add_options()("help,h", "show help"); general.add_options()("verbose,v", "verbose output"); general.add_options()("quiet,q", "quiet mode, only errors and warnings displayed"); general.add_options()("log,l", po::value<std::string>(), "log file, all log messages are written to this file regardless of -q"); general.add_options()("debug", "debug output"); general.add_options()("force,f", "keep running after errors"); #ifndef NO_GUI general.add_options()("gui", "start gui"); general.add_options()("gui-no-aa", "disable anti aliasing (use together with --gui option)"); #endif #ifndef NO_PYTHON general.add_options()("run", po::value<std::vector<std::string>>(), "python file to execute instead of default flow"); pos.add("run", -1); general.add_options()("pre-pack", po::value<std::vector<std::string>>(), "python file to run before packing"); general.add_options()("pre-place", po::value<std::vector<std::string>>(), "python file to run before placement"); general.add_options()("pre-route", po::value<std::vector<std::string>>(), "python file to run before routing"); general.add_options()("post-route", po::value<std::vector<std::string>>(), "python file to run after routing"); #endif general.add_options()("json", po::value<std::string>(), "JSON design file to ingest"); general.add_options()("write", po::value<std::string>(), "JSON design file to write"); general.add_options()("seed", po::value<int>(), "seed value for random number generator"); general.add_options()("randomize-seed,r", "randomize seed value for random number generator"); general.add_options()( "placer", po::value<std::string>(), std::string("placer algorithm to use; available: " + boost::algorithm::join(Arch::availablePlacers, ", ") + "; default: " + Arch::defaultPlacer) .c_str()); general.add_options()("slack_redist_iter", po::value<int>(), "number of iterations between slack redistribution"); general.add_options()("cstrweight", po::value<float>(), "placer weighting for relative constraint satisfaction"); general.add_options()("starttemp", po::value<float>(), "placer SA start temperature"); general.add_options()("placer-budgets", "use budget rather than criticality in placer timing weights"); general.add_options()("pack-only", "pack design only without placement or routing"); general.add_options()("ignore-loops", "ignore combinational loops in timing analysis"); general.add_options()("version,V", "show version"); general.add_options()("test", "check architecture database integrity"); general.add_options()("freq", po::value<double>(), "set target frequency for design in MHz"); general.add_options()("timing-allow-fail", "allow timing to fail in design"); general.add_options()("no-tmdriv", "disable timing-driven placement"); general.add_options()("save", po::value<std::string>(), "project file to write"); general.add_options()("load", po::value<std::string>(), "project file to read"); return general; } void CommandHandler::setupContext(Context *ctx) { if (vm.count("verbose")) { ctx->verbose = true; } if (vm.count("debug")) { ctx->verbose = true; ctx->debug = true; } if (vm.count("force")) { ctx->force = true; } if (vm.count("seed")) { ctx->rngseed(vm["seed"].as<int>()); } if (vm.count("randomize-seed")) { srand(time(NULL)); int r; do { r = rand(); } while (r == 0); ctx->rngseed(r); } if (vm.count("slack_redist_iter")) { ctx->slack_redist_iter = vm["slack_redist_iter"].as<int>(); if (vm.count("freq") && vm["freq"].as<double>() == 0) { ctx->auto_freq = true; #ifndef NO_GUI if (!vm.count("gui")) #endif log_warning("Target frequency not specified. Will optimise for max frequency.\n"); } } if (vm.count("ignore-loops")) { settings->set("timing/ignoreLoops", true); } if (vm.count("timing-allow-fail")) { settings->set("timing/allowFail", true); } if (vm.count("placer")) { std::string placer = vm["placer"].as<std::string>(); if (std::find(Arch::availablePlacers.begin(), Arch::availablePlacers.end(), placer) == Arch::availablePlacers.end()) log_error("Placer algorithm '%s' is not supported (available options: %s)\n", placer.c_str(), boost::algorithm::join(Arch::availablePlacers, ", ").c_str()); settings->set("placer", placer); } else { settings->set("placer", Arch::defaultPlacer); } if (vm.count("cstrweight")) { settings->set("placer1/constraintWeight", vm["cstrweight"].as<float>()); } if (vm.count("starttemp")) { settings->set("placer1/startTemp", vm["starttemp"].as<float>()); } if (vm.count("placer-budgets")) { settings->set("placer1/budgetBased", true); } if (vm.count("freq")) { auto freq = vm["freq"].as<double>(); if (freq > 0) ctx->target_freq = freq * 1e6; } ctx->timing_driven = true; if (vm.count("no-tmdriv")) ctx->timing_driven = false; } int CommandHandler::executeMain(std::unique_ptr<Context> ctx) { if (vm.count("test")) { ctx->archcheck(); return 0; } #ifndef NO_GUI if (vm.count("gui")) { Application a(argc, argv, (vm.count("gui-no-aa") > 0)); MainWindow w(std::move(ctx), chipArgs); try { if (vm.count("json")) { std::string filename = vm["json"].as<std::string>(); std::ifstream f(filename); if (!parse_json_file(f, filename, w.getContext())) log_error("Loading design failed.\n"); customAfterLoad(w.getContext()); w.notifyChangeContext(); w.updateLoaded(); } else if (vm.count("load")) { w.projectLoad(vm["load"].as<std::string>()); } else w.notifyChangeContext(); } catch (log_execution_error_exception) { // show error is handled by gui itself } w.show(); return a.exec(); } #endif if (vm.count("json")) { std::string filename = vm["json"].as<std::string>(); std::ifstream f(filename); if (!parse_json_file(f, filename, ctx.get())) log_error("Loading design failed.\n"); customAfterLoad(ctx.get()); } #ifndef NO_PYTHON init_python(argv[0], true); python_export_global("ctx", *ctx); if (vm.count("run")) { std::vector<std::string> files = vm["run"].as<std::vector<std::string>>(); for (auto filename : files) execute_python_file(filename.c_str()); } else #endif if (vm.count("json") || vm.count("load")) { run_script_hook("pre-pack"); if (!ctx->pack() && !ctx->force) log_error("Packing design failed.\n"); assign_budget(ctx.get()); ctx->check(); print_utilisation(ctx.get()); run_script_hook("pre-place"); if (!vm.count("pack-only")) { if (!ctx->place() && !ctx->force) log_error("Placing design failed.\n"); ctx->check(); run_script_hook("pre-route"); if (!ctx->route() && !ctx->force) log_error("Routing design failed.\n"); } run_script_hook("post-route"); customBitstream(ctx.get()); } if (vm.count("write")) { std::string filename = vm["write"].as<std::string>(); std::ofstream f(filename); if (!write_json_file(f, filename, ctx.get())) log_error("Saving design failed.\n"); } if (vm.count("save")) { project.save(ctx.get(), vm["save"].as<std::string>()); } #ifndef NO_PYTHON deinit_python(); #endif return had_nonfatal_error ? 1 : 0; } void CommandHandler::conflicting_options(const boost::program_options::variables_map &vm, const char *opt1, const char *opt2) { if (vm.count(opt1) && !vm[opt1].defaulted() && vm.count(opt2) && !vm[opt2].defaulted()) { std::string msg = "Conflicting options '" + std::string(opt1) + "' and '" + std::string(opt2) + "'."; log_error("%s\n", msg.c_str()); } } void CommandHandler::printFooter() { int warning_count = get_or_default(message_count_by_level, LogLevel::WARNING_MSG, 0), error_count = get_or_default(message_count_by_level, LogLevel::ERROR_MSG, 0); if (warning_count > 0 || error_count > 0) log_always("%d warning%s, %d error%s\n", warning_count, warning_count == 1 ? "" : "s", error_count, error_count == 1 ? "" : "s"); } int CommandHandler::exec() { try { if (!parseOptions()) return -1; if (executeBeforeContext()) return 0; std::unique_ptr<Context> ctx; if (vm.count("load") && vm.count("gui") == 0) { ctx = project.load(vm["load"].as<std::string>()); } else { ctx = createContext(); } settings = std::unique_ptr<Settings>(new Settings(ctx.get())); setupContext(ctx.get()); setupArchContext(ctx.get()); int rc = executeMain(std::move(ctx)); printFooter(); return rc; } catch (log_execution_error_exception) { printFooter(); return -1; } } void CommandHandler::run_script_hook(const std::string &name) { #ifndef NO_PYTHON if (vm.count(name)) { std::vector<std::string> files = vm[name].as<std::vector<std::string>>(); for (auto filename : files) execute_python_file(filename.c_str()); } #endif } NEXTPNR_NAMESPACE_END <|endoftext|>
<commit_before>#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <asio.hpp> #include <cassert> #include <cstdlib> #include <ctime> #include <list> #include <iostream> #include "common.hxx" #include "service.hxx" #include "dispatch.hxx" using namespace std; static list<void (*)(void)> maintFuncs; static asio::io_service service; static asio::ip::udp::socket* sock4 = NULL, * sock6 = NULL; void addMaintFunc(void (*f)(void)) { maintFuncs.push_back(f); } void sendPacket(const asio::ip::udp::endpoint& endpoint, const byte* dat, unsigned len) { asio::ip::udp::socket* sock = endpoint.address().is_v4()? sock4 : sock6; assert(sock); try { sock->send_to(asio::buffer(dat, len), endpoint); } catch (const asio::system_error& err) { cerr << "Error sending to " << endpoint << ": " << err.what() << endl; } } bool initService() { try { sock4 = new asio::ip::udp::socket(service, asio::ip::udp::endpoint( asio::ip::address( asio::ip::address_v4::any()), IPV4PORT)); } catch (const asio::system_error& err) { cerr << "Unable to listen for IPv4: " << err.what() << endl; } try { sock6 = new asio::ip::udp::socket(service, asio::ip::udp::endpoint( asio::ip::address( asio::ip::address_v6::any()), IPV6PORT)); } catch (const asio::system_error& err) { cerr << "Unable to listen for IPv6: " << err.what() << endl; } return sock4 || sock6; } static byte readBuffer[65536]; static asio::ip::udp::endpoint readEndpoint; static void beginRead(asio::ip::udp::socket*); static void receivePacket(const asio::error_code& error, size_t size) { if (error) { cerr << "Error receiving packet: " << error.message(); return; } //0 works well enough, since we only need to test for equality, and this //avoids a race condition if we ever make things multithreaded. static time_t lastMaintRun = 0; time_t now = time(0); if (now != lastMaintRun) { for (list<void (*)(void)>::const_iterator it = maintFuncs.begin(); it != maintFuncs.end(); ++it) (*it)(); lastMaintRun = now; } dispatchPacket(readEndpoint, readBuffer, size); beginRead(readEndpoint.address().is_v4()? sock4 : sock6); } static void beginRead(asio::ip::udp::socket* sock) { assert(sock); sock->async_receive_from(asio::buffer(readBuffer, sizeof(readBuffer)), readEndpoint, receivePacket); } void runListenReadLoop() { if (sock4) beginRead(sock4); if (sock6) beginRead(sock6); while (true) { try { service.run(); cerr << "FATAL: service.run() returned normally!" << endl; assert(false); exit(-1); } catch (const asio::system_error& err) { cerr << "service.run() returned error: " << err.what() << endl; } } } <commit_msg>Handle errors better, and use simpler socket creation.<commit_after>#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <asio.hpp> #include <cassert> #include <cstdlib> #include <ctime> #include <list> #include <iostream> #include "common.hxx" #include "service.hxx" #include "dispatch.hxx" using namespace std; static list<void (*)(void)> maintFuncs; static asio::io_service service; static asio::ip::udp::socket* sock4 = NULL, * sock6 = NULL; void addMaintFunc(void (*f)(void)) { maintFuncs.push_back(f); } void sendPacket(const asio::ip::udp::endpoint& endpoint, const byte* dat, unsigned len) { asio::ip::udp::socket* sock = endpoint.address().is_v4()? sock4 : sock6; assert(sock); try { sock->send_to(asio::buffer(dat, len), endpoint); } catch (const asio::system_error& err) { cerr << "Error sending to " << endpoint << ": " << err.what() << endl; } } bool initService() { try { sock4 = new asio::ip::udp::socket(service, asio::ip::udp::endpoint( asio::ip::udp::v4(), IPV4PORT)); } catch (const asio::system_error& err) { cerr << "Unable to listen for IPv4: " << err.what() << endl; } try { sock6 = new asio::ip::udp::socket(service, asio::ip::udp::endpoint( asio::ip::udp::v6(), IPV6PORT)); } catch (const asio::system_error& err) { cerr << "Unable to listen for IPv6: " << err.what() << endl; } return sock4 || sock6; } static byte readBuffer[65536]; static asio::ip::udp::endpoint readEndpoint; static void beginRead(asio::ip::udp::socket*); static void receivePacket(const asio::error_code& error, size_t size) { if (error) { cerr << "Error receiving packet: " << error.message(); beginRead(readEndpoint.address().is_v4()? sock4 : sock6); return; } //0 works well enough, since we only need to test for equality, and this //avoids a race condition if we ever make things multithreaded. static time_t lastMaintRun = 0; time_t now = time(0); if (now != lastMaintRun) { for (list<void (*)(void)>::const_iterator it = maintFuncs.begin(); it != maintFuncs.end(); ++it) (*it)(); lastMaintRun = now; } dispatchPacket(readEndpoint, readBuffer, size); beginRead(readEndpoint.address().is_v4()? sock4 : sock6); } static void beginRead(asio::ip::udp::socket* sock) { assert(sock); sock->async_receive_from(asio::buffer(readBuffer, sizeof(readBuffer)), readEndpoint, receivePacket); } void runListenReadLoop() { if (sock4) beginRead(sock4); if (sock6) beginRead(sock6); while (true) { try { service.run(); cerr << "FATAL: service.run() returned normally!" << endl; assert(false); exit(-1); } catch (const asio::system_error& err) { cerr << "service.run() returned error: " << err.what() << endl; } } } <|endoftext|>
<commit_before>/** * Copyright (C) 2013 Aldebaran Robotics */ #include <string> #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include <boost/foreach.hpp> #include <qi/log.hpp> #include <qi/detail/log.hxx> #include <qi/applicationsession.hpp> #include "qicli.hpp" #define foreach BOOST_FOREACH qiLogCategory("qicli.qilog"); static void onMessage(const qi::AnyValue& msg) { qi::AnyReference ref = msg.asReference(); std::stringstream ss; ss << qi::log::logLevelToString(static_cast<qi::LogLevel>(ref[1].asInt32())) // level << " " << ref[3].asString() // category << " " << ref[0].asString() // source << " " << ref[5].asString(); // message std::cout << ss.str() << std::endl; } static void setFilter(const std::string& rules, qi::AnyObject listener) { std::string cat; qi::LogLevel level; for (auto &&p: qi::log::detail::parseFilterRules(rules)) { std::tie(cat, level) = std::move(p); listener.call<void>("addFilter", cat, static_cast<int>(level)); } } int subCmd_logView(int argc, char **argv, qi::ApplicationSession& app) { po::options_description desc("Usage: qicli log-view"); desc.add_options() ("help,h", "Print this help message and exit") ("verbose,v", "Set maximum logs verbosity shown to verbose.") ("debug,d", "Set maximum logs verbosity shown to debug.") ("level,l", po::value<int>()->default_value(4), "Change the log minimum level: [0-6] (default:4). This option accepts the same arguments' format than --qi-log-level.") ("filters,f", po::value<std::string>(), "Set log filtering options. This option accepts the same arguments' format than --qi-log-filters.") ; po::variables_map vm; if (!poDefault(po::command_line_parser(argc, argv).options(desc), vm, desc)) return 1; qiLogVerbose() << "Connecting to service directory"; app.startSession(); qi::SessionPtr s = app.session(); qiLogVerbose() << "Resolving services"; qi::AnyObject logger = s->service("LogManager"); qi::AnyObject listener = logger.call<qi::AnyObject>("getListener"); listener.call<void>("clearFilters"); if (vm.count("level")) { int level = vm["level"].as<int>(); if (level > 6) level = 6; else if (level <= 0) level = 0; listener.call<void>("addFilter", "*", level); } if (vm.count("verbose")) listener.call<void>("addFilter", "*", 5); if (vm.count("debug")) listener.call<void>("addFilter", "*", 6); if (vm.count("filters")) { std::string filters = vm["filters"].as<std::string>(); setFilter(filters, listener); } listener.connect("onLogMessage", &onMessage); app.run(); return 0; } int subCmd_logSend(int argc, char **argv, qi::ApplicationSession& app) { po::options_description desc("Usage: qicli log-send <message>"); desc.add_options() ("help,h", "Print this help message and exit") ("verbose,v", "Set sent message verbosity to verbose.") ("debug,d", "Set sent message verbosity to debug.") ("level,l", po::value<int>()->default_value(4), "Change the log minimum level: [0-6] (default:4). This option accepts the same arguments' format than --qi-log-level.") ("category,c", po::value<std::string>(), "Message's category (default: \"qicli.qilog.logsend\").") ("message,m", po::value<std::string>(), "Message to send.") ; po::positional_options_description positionalOptions; positionalOptions.add("message", -1); po::variables_map vm; if (!poDefault(po::command_line_parser(argc, argv) .options(desc).positional(positionalOptions), vm, desc)) return 1; qiLogVerbose() << "Connecting to service directory"; app.startSession(); qi::SessionPtr s = app.session(); qiLogVerbose() << "Resolving services"; qi::AnyObject logger = s->service("LogManager"); qi::os::timeval tv(qi::SystemClock::now()); std::string source(__FILE__); source += ':'; source += __FUNCTION__; source += ':'; source += boost::lexical_cast<std::string>(__LINE__); int level = 4; if (vm.count("level")) { level = vm["level"].as<int>(); if (level > 6) level = 6; else if (level <= 0) level = 0; } if (vm.count("verbose")) level = 5; if (vm.count("debug")) level = 6; std::string category = "qicli.qilog.logsend"; if (vm.count("category")) category = vm["category"].as<std::string>(); std::string location = qi::os::getMachineId() + ":" + boost::lexical_cast<std::string>(qi::os::getpid());; std::string message = ""; if (vm.count("message")) message = vm["message"].as<std::string>(); // timestamp qi::AnyReferenceVector timeVectRef; timeVectRef.push_back(qi::AnyReference::from(tv.tv_sec)); timeVectRef.push_back(qi::AnyReference::from(tv.tv_usec)); qi::AnyValue timeVal = qi::AnyValue::makeTuple(timeVectRef); qi::AnyReferenceVector msgVectRef; msgVectRef.push_back(qi::AnyReference::from(source)); msgVectRef.push_back(qi::AnyReference::from(level)); msgVectRef.push_back(timeVal.asReference()); //timestamp msgVectRef.push_back(qi::AnyReference::from(category)); msgVectRef.push_back(qi::AnyReference::from(location)); msgVectRef.push_back(qi::AnyReference::from(message)); msgVectRef.push_back(qi::AnyReference::from(0)); std::vector<qi::AnyValue> msgs; msgs.push_back(qi::AnyValue::makeTuple(msgVectRef)); logger.call<void>("log", qi::AnyValue::from(msgs)); logger.reset(); return 0; } <commit_msg>Rewrite qicli log-view using qicore type<commit_after>/** * Copyright (C) 2013 Aldebaran Robotics */ #include <string> #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include <boost/foreach.hpp> #include <qi/log.hpp> #include <qi/detail/log.hxx> #include <qi/applicationsession.hpp> #include <qicore/logmessage.hpp> #include <qicore/logmanager.hpp> #include <qicore/loglistener.hpp> #include "qicli.hpp" #define foreach BOOST_FOREACH qiLogCategory("qicli.qilog"); static void onMessage(const qi::LogMessage& msg) { std::stringstream ss; ss << qi::log::logLevelToString(static_cast<qi::LogLevel>(msg.level)) << " " << msg.category << " " << msg.source << " " << msg.message; std::cout << ss.str() << std::endl; } static void setFilter(const std::string& rules, qi::LogListenerPtr listener) { std::string cat; qi::LogLevel level; for (auto &&p: qi::log::detail::parseFilterRules(rules)) { std::tie(cat, level) = std::move(p); listener->addFilter(cat, level); } } int subCmd_logView(int argc, char **argv, qi::ApplicationSession& app) { po::options_description desc("Usage: qicli log-view"); desc.add_options() ("help,h", "Print this help message and exit") ("verbose,v", "Set maximum logs verbosity shown to verbose.") ("debug,d", "Set maximum logs verbosity shown to debug.") ("level,l", po::value<int>()->default_value(4), "Change the log minimum level: [0-6] (default:4). This option accepts the same arguments' format than --qi-log-level.") ("filters,f", po::value<std::string>(), "Set log filtering options. This option accepts the same arguments' format than --qi-log-filters.") ; po::variables_map vm; if (!poDefault(po::command_line_parser(argc, argv).options(desc), vm, desc)) return 1; qiLogVerbose() << "Connecting to service directory"; app.startSession(); qi::SessionPtr s = app.session(); qiLogVerbose() << "Resolving services"; app.loadModule("qicore"); qi::LogManagerPtr logger = app.session()->service("LogManager"); qi::LogListenerPtr listener = logger->createListener(); listener->clearFilters(); if (vm.count("level")) { int level = vm["level"].as<int>(); if (level > 6) level = 6; else if (level <= 0) level = 0; listener->addFilter("*", static_cast<qi::LogLevel>(level)); } if (vm.count("verbose")) listener->addFilter("*", qi::LogLevel_Verbose); if (vm.count("debug")) listener->addFilter("*", qi::LogLevel_Debug); if (vm.count("filters")) { std::string filters = vm["filters"].as<std::string>(); setFilter(filters, listener); } listener->onLogMessage.connect(&onMessage); app.run(); return 0; } int subCmd_logSend(int argc, char **argv, qi::ApplicationSession& app) { po::options_description desc("Usage: qicli log-send <message>"); desc.add_options() ("help,h", "Print this help message and exit") ("verbose,v", "Set sent message verbosity to verbose.") ("debug,d", "Set sent message verbosity to debug.") ("level,l", po::value<int>()->default_value(4), "Change the log minimum level: [0-6] (default:4). This option accepts the same arguments' format than --qi-log-level.") ("category,c", po::value<std::string>(), "Message's category (default: \"qicli.qilog.logsend\").") ("message,m", po::value<std::string>(), "Message to send.") ; po::positional_options_description positionalOptions; positionalOptions.add("message", -1); po::variables_map vm; if (!poDefault(po::command_line_parser(argc, argv) .options(desc).positional(positionalOptions), vm, desc)) return 1; qiLogVerbose() << "Connecting to service directory"; app.startSession(); qi::SessionPtr s = app.session(); qiLogVerbose() << "Resolving services"; qi::AnyObject logger = s->service("LogManager"); qi::os::timeval tv(qi::SystemClock::now()); std::string source(__FILE__); source += ':'; source += __FUNCTION__; source += ':'; source += boost::lexical_cast<std::string>(__LINE__); int level = 4; if (vm.count("level")) { level = vm["level"].as<int>(); if (level > 6) level = 6; else if (level <= 0) level = 0; } if (vm.count("verbose")) level = 5; if (vm.count("debug")) level = 6; std::string category = "qicli.qilog.logsend"; if (vm.count("category")) category = vm["category"].as<std::string>(); std::string location = qi::os::getMachineId() + ":" + boost::lexical_cast<std::string>(qi::os::getpid());; std::string message = ""; if (vm.count("message")) message = vm["message"].as<std::string>(); // timestamp qi::AnyReferenceVector timeVectRef; timeVectRef.push_back(qi::AnyReference::from(tv.tv_sec)); timeVectRef.push_back(qi::AnyReference::from(tv.tv_usec)); qi::AnyValue timeVal = qi::AnyValue::makeTuple(timeVectRef); qi::AnyReferenceVector msgVectRef; msgVectRef.push_back(qi::AnyReference::from(source)); msgVectRef.push_back(qi::AnyReference::from(level)); msgVectRef.push_back(timeVal.asReference()); //timestamp msgVectRef.push_back(qi::AnyReference::from(category)); msgVectRef.push_back(qi::AnyReference::from(location)); msgVectRef.push_back(qi::AnyReference::from(message)); msgVectRef.push_back(qi::AnyReference::from(0)); std::vector<qi::AnyValue> msgs; msgs.push_back(qi::AnyValue::makeTuple(msgVectRef)); logger.call<void>("log", qi::AnyValue::from(msgs)); logger.reset(); return 0; } <|endoftext|>
<commit_before>/* The radical of n, rad(n), is the product of the distinct prime factors of n. For example, 504 = 23 × 32 × 7, so rad(504) = 2 × 3 × 7 = 42. If we calculate rad(n) for 1 ≤ n ≤ 10, then sort them on rad(n), and sorting on n if the radical values are equal, we get: .... Let E(k) be the kth element in the sorted n column; for example, E(4) = 8 and E(6) = 9. If rad(n) is sorted for 1 ≤ n ≤ 100000, find E(10000). Solution comment: Using a sieve to generate all the radicals, then sorting the result. Quite fast, about ~7ms. Mostly spent sorting. */ #include <iostream> #include <array> #include <utility> #include <algorithm> #include "timing.hpp" int main() { euler::Timer timer{}; constexpr int N = 1e5 + 1; constexpr int target = 1e4; // Pairs are (rad(n), n). // Initialize all numbers with rad(n) = 1. std::array<std::pair<int, int>, N> rads; for (int i = 0; i < N; ++i) { rads[i] = {1, i}; } for (int i = 2; i < N; ++i) { // If rads[i].first == 1, then i is a prime, and rad(i) = i. if (rads[i].first == 1) { rads[i].first = i; // Then every multiple of k*i has a factor of i in its radical. for (int j = i + i; j < N; j += i) { rads[j].first *= i; } } } std::sort(rads.begin(), rads.end()); timer.stop(); printf("Answer: %d\n", rads[target].second); } <commit_msg>Optimize 124 to use selection rather than full sort.<commit_after>/* The radical of n, rad(n), is the product of the distinct prime factors of n. For example, 504 = 23 × 32 × 7, so rad(504) = 2 × 3 × 7 = 42. If we calculate rad(n) for 1 ≤ n ≤ 10, then sort them on rad(n), and sorting on n if the radical values are equal, we get: .... Let E(k) be the kth element in the sorted n column; for example, E(4) = 8 and E(6) = 9. If rad(n) is sorted for 1 ≤ n ≤ 100000, find E(10000). Solution comment: Using a sieve to generate all the radicals, then selecting out the result. Quite fast, about ~1.6ms. */ #include <iostream> #include <array> #include <utility> #include <algorithm> #include "timing.hpp" int main() { euler::Timer timer{}; constexpr int N = 1e5 + 1; constexpr int target = 1e4; // Pairs are (rad(n), n). // Initialize all numbers with rad(n) = 1. std::array<std::pair<int, int>, N> rads; for (int i = 0; i < N; ++i) { rads[i] = {1, i}; } for (int i = 2; i < N; ++i) { // If rads[i].first == 1, then i is a prime, and rad(i) = i. if (rads[i].first == 1) { rads[i].first = i; // Then every multiple of k*i has a factor of i in its radical. for (int j = i + i; j < N; j += i) { rads[j].first *= i; } } } // Find the nth smallest element. After this, rads[target] is that pair. std::nth_element(rads.begin(), rads.begin() + target, rads.end()); timer.stop(); printf("Answer: %d\n", rads[target].second); } <|endoftext|>
<commit_before>#ifndef __SGE_EXCEPTION_HPP #define __SGE_EXCEPTION_HPP #include <stdexcept> #include <string> namespace sge { class Exception : public std::runtime_error { public: Exception(const std::string &domain, const std::string &msg) throw() : runtime_error("[" + domain + "] " + msg) {} virtual ~Exception() throw() {} }; } #endif /* __SGE_EXCEPTION_HPP */ <commit_msg>fix exception destructor<commit_after>#ifndef __SGE_EXCEPTION_HPP #define __SGE_EXCEPTION_HPP #include <stdexcept> #include <string> namespace sge { class Exception : public std::runtime_error { public: Exception(const std::string &domain, const std::string &msg) throw() : runtime_error("[" + domain + "] " + msg) {} virtual ~Exception() noexcept {} }; } #endif /* __SGE_EXCEPTION_HPP */ <|endoftext|>
<commit_before>// Game_Music_Emu 0.5.5. http://www.slack.net/~ant/ #include "Spc_Emu.h" #include "blargg_endian.h" #include <stdlib.h> #include <string.h> /* Copyright (C) 2004-2006 Shay Green. This module is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This module 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 module; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "blargg_source.h" // TODO: support Spc_Filter's bass Spc_Emu::Spc_Emu() { set_type( gme_spc_type ); static const char* const names [Snes_Spc::voice_count] = { "DSP 1", "DSP 2", "DSP 3", "DSP 4", "DSP 5", "DSP 6", "DSP 7", "DSP 8" }; set_voice_names( names ); set_gain( 1.4 ); } Spc_Emu::~Spc_Emu() { } // Track info long const trailer_offset = 0x10200; byte const* Spc_Emu::trailer() const { return &file_data [min( file_size, trailer_offset )]; } long Spc_Emu::trailer_size() const { return max( 0L, file_size - trailer_offset ); } static void get_spc_xid6( byte const* begin, long size, track_info_t* out ) { // header byte const* end = begin + size; if ( size < 8 || memcmp( begin, "xid6", 4 ) ) { check( false ); return; } long info_size = get_le32( begin + 4 ); byte const* in = begin + 8; if ( end - in > info_size ) { debug_printf( "Extra data after SPC xid6 info\n" ); end = in + info_size; } int year = 0; char copyright [256 + 5]; int copyright_len = 0; int const year_len = 5; while ( end - in >= 4 ) { // header int id = in [0]; int data = in [3] * 0x100 + in [2]; int type = in [1]; int len = type ? data : 0; in += 4; if ( len > end - in ) { check( false ); break; // block goes past end of data } // handle specific block types char* field = 0; switch ( id ) { case 0x01: field = out->song; break; case 0x02: field = out->game; break; case 0x03: field = out->author; break; case 0x04: field = out->dumper; break; case 0x07: field = out->comment; break; case 0x14: year = data; break; //case 0x30: // intro length // Many SPCs have intro length set wrong for looped tracks, making it useless /* case 0x30: check( len == 4 ); if ( len >= 4 ) { out->intro_length = get_le32( in ) / 64; if ( out->length > 0 ) { long loop = out->length - out->intro_length; if ( loop >= 2000 ) out->loop_length = loop; } } break; */ case 0x13: copyright_len = min( len, (int) sizeof copyright - year_len ); memcpy( &copyright [year_len], in, copyright_len ); break; default: if ( id < 0x01 || (id > 0x07 && id < 0x10) || (id > 0x14 && id < 0x30) || id > 0x36 ) debug_printf( "Unknown SPC xid6 block: %X\n", (int) id ); break; } if ( field ) { check( type == 1 ); Gme_File::copy_field_( field, (char const*) in, len ); } // skip to next block in += len; // blocks are supposed to be 4-byte aligned with zero-padding... byte const* unaligned = in; while ( (in - begin) & 3 && in < end ) { if ( *in++ != 0 ) { // ...but some files have no padding in = unaligned; debug_printf( "SPC info tag wasn't properly padded to align\n" ); break; } } } char* p = &copyright [year_len]; if ( year ) { *--p = ' '; for ( int n = 4; n--; ) { *--p = char (year % 10 + '0'); year /= 10; } copyright_len += year_len; } if ( copyright_len ) Gme_File::copy_field_( out->copyright, p, copyright_len ); check( in == end ); } static void get_spc_info( Spc_Emu::header_t const& h, byte const* xid6, long xid6_size, track_info_t* out ) { // decode length (can be in text or binary format, sometimes ambiguous ugh) long len_secs = 0; for ( int i = 0; i < 3; i++ ) { unsigned n = h.len_secs [i] - '0'; if ( n > 9 ) { // ignore single-digit text lengths // (except if author field is present and begins at offset 1, ugh) if ( i == 1 && (h.author [0] || !h.author [1]) ) len_secs = 0; break; } len_secs *= 10; len_secs += n; } if ( !len_secs || len_secs > 0x1FFF ) len_secs = get_le16( h.len_secs ); if ( len_secs < 0x1FFF ) out->length = len_secs * 1000; int offset = (h.author [0] < ' ' || unsigned (h.author [0] - '0') <= 9); Gme_File::copy_field_( out->author, &h.author [offset], sizeof h.author - offset ); GME_COPY_FIELD( h, out, song ); GME_COPY_FIELD( h, out, game ); GME_COPY_FIELD( h, out, dumper ); GME_COPY_FIELD( h, out, comment ); if ( xid6_size ) get_spc_xid6( xid6, xid6_size, out ); } blargg_err_t Spc_Emu::track_info_( track_info_t* out, int ) const { get_spc_info( header(), trailer(), trailer_size(), out ); return 0; } static blargg_err_t check_spc_header( void const* header ) { if ( memcmp( header, "SNES-SPC700 Sound File Data", 27 ) ) return gme_wrong_file_type; return 0; } struct Spc_File : Gme_Info_ { Spc_Emu::header_t header; blargg_vector<byte> xid6; Spc_File() { set_type( gme_spc_type ); } blargg_err_t load_( Data_Reader& in ) { long file_size = in.remain(); if ( file_size < Snes_Spc::spc_file_size ) return gme_wrong_file_type; RETURN_ERR( in.read( &header, Spc_Emu::header_size ) ); RETURN_ERR( check_spc_header( header.tag ) ); long const xid6_offset = 0x10200; long xid6_size = file_size - xid6_offset; if ( xid6_size > 0 ) { RETURN_ERR( xid6.resize( xid6_size ) ); RETURN_ERR( in.skip( xid6_offset - Spc_Emu::header_size ) ); RETURN_ERR( in.read( xid6.begin(), xid6.size() ) ); } return 0; } blargg_err_t track_info_( track_info_t* out, int ) const { get_spc_info( header, xid6.begin(), xid6.size(), out ); return 0; } }; static Music_Emu* new_spc_emu () { return BLARGG_NEW Spc_Emu ; } static Music_Emu* new_spc_file() { return BLARGG_NEW Spc_File; } static gme_type_t_ const gme_spc_type_ = { "Super Nintendo", 1, &new_spc_emu, &new_spc_file, "SPC", 0 }; gme_type_t const gme_spc_type = &gme_spc_type_; // Setup blargg_err_t Spc_Emu::set_sample_rate_( long sample_rate ) { RETURN_ERR( apu.init() ); enable_accuracy( false ); if ( sample_rate != native_sample_rate ) { RETURN_ERR( resampler.buffer_size( native_sample_rate / 20 * 2 ) ); resampler.time_ratio( (double) native_sample_rate / sample_rate, 0.9965 ); } return 0; } void Spc_Emu::enable_accuracy_( bool b ) { Music_Emu::enable_accuracy_( b ); filter.enable( b ); } void Spc_Emu::mute_voices_( int m ) { Music_Emu::mute_voices_( m ); apu.mute_voices( m ); } blargg_err_t Spc_Emu::load_mem_( byte const* in, long size ) { assert( offsetof (header_t,unused2 [46]) == header_size ); file_data = in; file_size = size; set_voice_count( Snes_Spc::voice_count ); if ( size < Snes_Spc::spc_file_size ) return gme_wrong_file_type; return check_spc_header( in ); } // Emulation void Spc_Emu::set_tempo_( double t ) { apu.set_tempo( (int) (t * apu.tempo_unit) ); } blargg_err_t Spc_Emu::start_track_( int track ) { RETURN_ERR( Music_Emu::start_track_( track ) ); resampler.clear(); filter.clear(); RETURN_ERR( apu.load_spc( file_data, file_size ) ); filter.set_gain( (int) (gain() * SPC_Filter::gain_unit) ); apu.clear_echo(); return 0; } blargg_err_t Spc_Emu::play_and_filter( long count, sample_t out [] ) { RETURN_ERR( apu.play( count, out ) ); filter.run( out, count ); return 0; } blargg_err_t Spc_Emu::skip_( long count ) { if ( sample_rate() != native_sample_rate ) { count = long (count * resampler.ratio()) & ~1; count -= resampler.skip_input( count ); } // TODO: shouldn't skip be adjusted for the 64 samples read afterwards? if ( count > 0 ) { RETURN_ERR( apu.skip( count ) ); filter.clear(); } // eliminate pop due to resampler const int resampler_latency = 64; sample_t buf [resampler_latency]; return play_( resampler_latency, buf ); } blargg_err_t Spc_Emu::play_( long count, sample_t* out ) { if ( sample_rate() == native_sample_rate ) return play_and_filter( count, out ); long remain = count; while ( remain > 0 ) { remain -= resampler.read( &out [count - remain], remain ); if ( remain > 0 ) { long n = resampler.max_write(); RETURN_ERR( play_and_filter( n, resampler.buffer() ) ); resampler.write( n ); } } check( remain == 0 ); return 0; } <commit_msg>Fixed SPC not recognizing files less than 0x10200 bytes (just introduced in switch to snes_spc).<commit_after>// Game_Music_Emu 0.5.5. http://www.slack.net/~ant/ #include "Spc_Emu.h" #include "blargg_endian.h" #include <stdlib.h> #include <string.h> /* Copyright (C) 2004-2006 Shay Green. This module is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This module 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 module; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "blargg_source.h" // TODO: support Spc_Filter's bass Spc_Emu::Spc_Emu() { set_type( gme_spc_type ); static const char* const names [Snes_Spc::voice_count] = { "DSP 1", "DSP 2", "DSP 3", "DSP 4", "DSP 5", "DSP 6", "DSP 7", "DSP 8" }; set_voice_names( names ); set_gain( 1.4 ); } Spc_Emu::~Spc_Emu() { } // Track info long const trailer_offset = 0x10200; byte const* Spc_Emu::trailer() const { return &file_data [min( file_size, trailer_offset )]; } long Spc_Emu::trailer_size() const { return max( 0L, file_size - trailer_offset ); } static void get_spc_xid6( byte const* begin, long size, track_info_t* out ) { // header byte const* end = begin + size; if ( size < 8 || memcmp( begin, "xid6", 4 ) ) { check( false ); return; } long info_size = get_le32( begin + 4 ); byte const* in = begin + 8; if ( end - in > info_size ) { debug_printf( "Extra data after SPC xid6 info\n" ); end = in + info_size; } int year = 0; char copyright [256 + 5]; int copyright_len = 0; int const year_len = 5; while ( end - in >= 4 ) { // header int id = in [0]; int data = in [3] * 0x100 + in [2]; int type = in [1]; int len = type ? data : 0; in += 4; if ( len > end - in ) { check( false ); break; // block goes past end of data } // handle specific block types char* field = 0; switch ( id ) { case 0x01: field = out->song; break; case 0x02: field = out->game; break; case 0x03: field = out->author; break; case 0x04: field = out->dumper; break; case 0x07: field = out->comment; break; case 0x14: year = data; break; //case 0x30: // intro length // Many SPCs have intro length set wrong for looped tracks, making it useless /* case 0x30: check( len == 4 ); if ( len >= 4 ) { out->intro_length = get_le32( in ) / 64; if ( out->length > 0 ) { long loop = out->length - out->intro_length; if ( loop >= 2000 ) out->loop_length = loop; } } break; */ case 0x13: copyright_len = min( len, (int) sizeof copyright - year_len ); memcpy( &copyright [year_len], in, copyright_len ); break; default: if ( id < 0x01 || (id > 0x07 && id < 0x10) || (id > 0x14 && id < 0x30) || id > 0x36 ) debug_printf( "Unknown SPC xid6 block: %X\n", (int) id ); break; } if ( field ) { check( type == 1 ); Gme_File::copy_field_( field, (char const*) in, len ); } // skip to next block in += len; // blocks are supposed to be 4-byte aligned with zero-padding... byte const* unaligned = in; while ( (in - begin) & 3 && in < end ) { if ( *in++ != 0 ) { // ...but some files have no padding in = unaligned; debug_printf( "SPC info tag wasn't properly padded to align\n" ); break; } } } char* p = &copyright [year_len]; if ( year ) { *--p = ' '; for ( int n = 4; n--; ) { *--p = char (year % 10 + '0'); year /= 10; } copyright_len += year_len; } if ( copyright_len ) Gme_File::copy_field_( out->copyright, p, copyright_len ); check( in == end ); } static void get_spc_info( Spc_Emu::header_t const& h, byte const* xid6, long xid6_size, track_info_t* out ) { // decode length (can be in text or binary format, sometimes ambiguous ugh) long len_secs = 0; for ( int i = 0; i < 3; i++ ) { unsigned n = h.len_secs [i] - '0'; if ( n > 9 ) { // ignore single-digit text lengths // (except if author field is present and begins at offset 1, ugh) if ( i == 1 && (h.author [0] || !h.author [1]) ) len_secs = 0; break; } len_secs *= 10; len_secs += n; } if ( !len_secs || len_secs > 0x1FFF ) len_secs = get_le16( h.len_secs ); if ( len_secs < 0x1FFF ) out->length = len_secs * 1000; int offset = (h.author [0] < ' ' || unsigned (h.author [0] - '0') <= 9); Gme_File::copy_field_( out->author, &h.author [offset], sizeof h.author - offset ); GME_COPY_FIELD( h, out, song ); GME_COPY_FIELD( h, out, game ); GME_COPY_FIELD( h, out, dumper ); GME_COPY_FIELD( h, out, comment ); if ( xid6_size ) get_spc_xid6( xid6, xid6_size, out ); } blargg_err_t Spc_Emu::track_info_( track_info_t* out, int ) const { get_spc_info( header(), trailer(), trailer_size(), out ); return 0; } static blargg_err_t check_spc_header( void const* header ) { if ( memcmp( header, "SNES-SPC700 Sound File Data", 27 ) ) return gme_wrong_file_type; return 0; } struct Spc_File : Gme_Info_ { Spc_Emu::header_t header; blargg_vector<byte> xid6; Spc_File() { set_type( gme_spc_type ); } blargg_err_t load_( Data_Reader& in ) { long file_size = in.remain(); if ( file_size < Snes_Spc::spc_min_file_size ) return gme_wrong_file_type; RETURN_ERR( in.read( &header, Spc_Emu::header_size ) ); RETURN_ERR( check_spc_header( header.tag ) ); long const xid6_offset = 0x10200; long xid6_size = file_size - xid6_offset; if ( xid6_size > 0 ) { RETURN_ERR( xid6.resize( xid6_size ) ); RETURN_ERR( in.skip( xid6_offset - Spc_Emu::header_size ) ); RETURN_ERR( in.read( xid6.begin(), xid6.size() ) ); } return 0; } blargg_err_t track_info_( track_info_t* out, int ) const { get_spc_info( header, xid6.begin(), xid6.size(), out ); return 0; } }; static Music_Emu* new_spc_emu () { return BLARGG_NEW Spc_Emu ; } static Music_Emu* new_spc_file() { return BLARGG_NEW Spc_File; } static gme_type_t_ const gme_spc_type_ = { "Super Nintendo", 1, &new_spc_emu, &new_spc_file, "SPC", 0 }; gme_type_t const gme_spc_type = &gme_spc_type_; // Setup blargg_err_t Spc_Emu::set_sample_rate_( long sample_rate ) { RETURN_ERR( apu.init() ); enable_accuracy( false ); if ( sample_rate != native_sample_rate ) { RETURN_ERR( resampler.buffer_size( native_sample_rate / 20 * 2 ) ); resampler.time_ratio( (double) native_sample_rate / sample_rate, 0.9965 ); } return 0; } void Spc_Emu::enable_accuracy_( bool b ) { Music_Emu::enable_accuracy_( b ); filter.enable( b ); } void Spc_Emu::mute_voices_( int m ) { Music_Emu::mute_voices_( m ); apu.mute_voices( m ); } blargg_err_t Spc_Emu::load_mem_( byte const* in, long size ) { assert( offsetof (header_t,unused2 [46]) == header_size ); file_data = in; file_size = size; set_voice_count( Snes_Spc::voice_count ); if ( size < Snes_Spc::spc_min_file_size ) return gme_wrong_file_type; return check_spc_header( in ); } // Emulation void Spc_Emu::set_tempo_( double t ) { apu.set_tempo( (int) (t * apu.tempo_unit) ); } blargg_err_t Spc_Emu::start_track_( int track ) { RETURN_ERR( Music_Emu::start_track_( track ) ); resampler.clear(); filter.clear(); RETURN_ERR( apu.load_spc( file_data, file_size ) ); filter.set_gain( (int) (gain() * SPC_Filter::gain_unit) ); apu.clear_echo(); return 0; } blargg_err_t Spc_Emu::play_and_filter( long count, sample_t out [] ) { RETURN_ERR( apu.play( count, out ) ); filter.run( out, count ); return 0; } blargg_err_t Spc_Emu::skip_( long count ) { if ( sample_rate() != native_sample_rate ) { count = long (count * resampler.ratio()) & ~1; count -= resampler.skip_input( count ); } // TODO: shouldn't skip be adjusted for the 64 samples read afterwards? if ( count > 0 ) { RETURN_ERR( apu.skip( count ) ); filter.clear(); } // eliminate pop due to resampler const int resampler_latency = 64; sample_t buf [resampler_latency]; return play_( resampler_latency, buf ); } blargg_err_t Spc_Emu::play_( long count, sample_t* out ) { if ( sample_rate() == native_sample_rate ) return play_and_filter( count, out ); long remain = count; while ( remain > 0 ) { remain -= resampler.read( &out [count - remain], remain ); if ( remain > 0 ) { long n = resampler.max_write(); RETURN_ERR( play_and_filter( n, resampler.buffer() ) ); resampler.write( n ); } } check( remain == 0 ); return 0; } <|endoftext|>
<commit_before>//===- Support/PlatformUtility.cpp - Platform Specific Utilities ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llbuild/Basic/PlatformUtility.h" #if defined(_WIN32) #include "LeanWindows.h" #include <direct.h> #include <io.h> #else #include <stdio.h> #include <unistd.h> #endif using namespace llbuild; using namespace llbuild::basic; bool sys::chdir(const char *fileName) { #if defined(_WIN32) return SetCurrentDirectoryA(fileName); #else return ::chdir(fileName) == 0; #endif } int sys::close(int fileHandle) { #if defined(_WIN32) return ::_close(fileHandle); #else return ::close(fileHandle); #endif } int sys::lstat(const char *fileName, sys::StatStruct *buf) { #if defined(_WIN32) // We deliberately ignore lstat on Windows, and delegate // to stat. return ::_stat(fileName, buf); #else return ::lstat(fileName, buf); #endif } bool sys::mkdir(const char* fileName) { #if defined(_WIN32) return _mkdir(fileName) == 0; #else return ::mkdir(fileName, S_IRWXU | S_IRWXG | S_IRWXO) == 0; #endif } int sys::pclose(FILE *stream) { #if defined(_WIN32) return ::_pclose(stream); #else return ::pclose(stream); #endif } int sys::pipe(int ptHandles[2]) { #if defined(_WIN32) return ::_pipe(ptHandles, 0, 0); #else return ::pipe(ptHandles); #endif } FILE *sys::popen(const char *command, const char *mode) { #if defined(_WIN32) return ::_popen(command, mode); #else return ::popen(command, mode); #endif } int sys::read(int fileHandle, void *destinationBuffer, unsigned int maxCharCount) { #if defined(_WIN32) return ::_read(fileHandle, destinationBuffer, maxCharCount); #else return ::read(fileHandle, destinationBuffer, maxCharCount); #endif } int sys::rmdir(const char *path) { #if defined(_WIN32) return ::_rmdir(path); #else return ::rmdir(path); #endif } int sys::stat(const char *fileName, StatStruct *buf) { #if defined(_WIN32) return ::_stat(fileName, buf); #else return ::stat(fileName, buf); #endif } int sys::symlink(const char *source, const char *target) { #if defined(_WIN32) return ::_symlink(source, target); #else return ::symlink(source, target); #endif } int sys::unlink(const char *fileName) { #if defined(_WIN32) return ::_unlink(fileName); #else return ::unlink(fileName); #endif } int sys::write(int fileHandle, void *destinationBuffer, unsigned int maxCharCount) { #if defined(_WIN32) return ::_write(fileHandle, destinationBuffer, maxCharCount); #else return ::write(fileHandle, destinationBuffer, maxCharCount); #endif } <commit_msg>Fix Windows implementation of symlink<commit_after>//===- Support/PlatformUtility.cpp - Platform Specific Utilities ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llbuild/Basic/PlatformUtility.h" #if defined(_WIN32) #include "LeanWindows.h" #include <direct.h> #include <io.h> #else #include <stdio.h> #include <unistd.h> #endif using namespace llbuild; using namespace llbuild::basic; bool sys::chdir(const char *fileName) { #if defined(_WIN32) return SetCurrentDirectoryA(fileName); #else return ::chdir(fileName) == 0; #endif } int sys::close(int fileHandle) { #if defined(_WIN32) return ::_close(fileHandle); #else return ::close(fileHandle); #endif } int sys::lstat(const char *fileName, sys::StatStruct *buf) { #if defined(_WIN32) // We deliberately ignore lstat on Windows, and delegate // to stat. return ::_stat(fileName, buf); #else return ::lstat(fileName, buf); #endif } bool sys::mkdir(const char* fileName) { #if defined(_WIN32) return _mkdir(fileName) == 0; #else return ::mkdir(fileName, S_IRWXU | S_IRWXG | S_IRWXO) == 0; #endif } int sys::pclose(FILE *stream) { #if defined(_WIN32) return ::_pclose(stream); #else return ::pclose(stream); #endif } int sys::pipe(int ptHandles[2]) { #if defined(_WIN32) return ::_pipe(ptHandles, 0, 0); #else return ::pipe(ptHandles); #endif } FILE *sys::popen(const char *command, const char *mode) { #if defined(_WIN32) return ::_popen(command, mode); #else return ::popen(command, mode); #endif } int sys::read(int fileHandle, void *destinationBuffer, unsigned int maxCharCount) { #if defined(_WIN32) return ::_read(fileHandle, destinationBuffer, maxCharCount); #else return ::read(fileHandle, destinationBuffer, maxCharCount); #endif } int sys::rmdir(const char *path) { #if defined(_WIN32) return ::_rmdir(path); #else return ::rmdir(path); #endif } int sys::stat(const char *fileName, StatStruct *buf) { #if defined(_WIN32) return ::_stat(fileName, buf); #else return ::stat(fileName, buf); #endif } int sys::symlink(const char *source, const char *target) { #if defined(_WIN32) DWORD attributes = GetFileAttributesA(source); if (attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0) { return ::CreateSymbolicLinkA(source, target, SYMBOLIC_LINK_FLAG_DIRECTORY); } return ::CreateSymbolicLinkA(source, target, 0); #else return ::symlink(source, target); #endif } int sys::unlink(const char *fileName) { #if defined(_WIN32) return ::_unlink(fileName); #else return ::unlink(fileName); #endif } int sys::write(int fileHandle, void *destinationBuffer, unsigned int maxCharCount) { #if defined(_WIN32) return ::_write(fileHandle, destinationBuffer, maxCharCount); #else return ::write(fileHandle, destinationBuffer, maxCharCount); #endif } <|endoftext|>
<commit_before><?hh //strict /** * This file is part of hhpack\package. * * (c) Noritaka Horio <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace hhpack\package; function any<T>() : (function(T):bool) { return ($object) ==> true; } function startsWith<T as NamedObject>(string $keyword) : (function(T):bool) { return ($object) ==> preg_match('/^' . preg_quote($keyword, '/') . '/', $object->name()) === 1; } function endsWith<T as NamedObject>(string $keyword) : (function(T):bool) { return ($object) ==> preg_match('/' . preg_quote($keyword, '/') . '$/', $object->name()) === 1; } function implementsInterface(string $interfaceName) : (function(ClassObject):bool) { return ($object) ==> $object->implementsInterface($interfaceName); } function subclassOf(string $className) : (function(ClassObject):bool) { return ($object) ==> $object->isSubclassOf($className); } function classes() : (function(ClassObject):bool) { return ($object) ==> ($object->isTrait() || $object->isInterface()) === false; } function abstractClasses() : (function(ClassObject):bool) { return ($object) ==> $object->isAbstract(); } function traits() : (function(ClassObject):bool) { return ($object) ==> $object->isTrait(); } function interfaces() : (function(ClassObject):bool) { return ($object) ==> $object->isInterface(); } function instantiable() : (function(ClassObject):bool) { return ($object) ==> $object->isInstantiable(); } <commit_msg>add instantiator function<commit_after><?hh //strict /** * This file is part of hhpack\package. * * (c) Noritaka Horio <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace hhpack\package; function any<T>() : (function(T):bool) { return ($object) ==> true; } function startsWith<T as NamedObject>(string $keyword) : (function(T):bool) { return ($object) ==> preg_match('/^' . preg_quote($keyword, '/') . '/', $object->name()) === 1; } function endsWith<T as NamedObject>(string $keyword) : (function(T):bool) { return ($object) ==> preg_match('/' . preg_quote($keyword, '/') . '$/', $object->name()) === 1; } function implementsInterface(string $interfaceName) : (function(ClassObject):bool) { return ($object) ==> $object->implementsInterface($interfaceName); } function subclassOf(string $className) : (function(ClassObject):bool) { return ($object) ==> $object->isSubclassOf($className); } function classes() : (function(ClassObject):bool) { return ($object) ==> ($object->isTrait() || $object->isInterface()) === false; } function abstractClasses() : (function(ClassObject):bool) { return ($object) ==> $object->isAbstract(); } function traits() : (function(ClassObject):bool) { return ($object) ==> $object->isTrait(); } function interfaces() : (function(ClassObject):bool) { return ($object) ==> $object->isInterface(); } function instantiable() : (function(ClassObject):bool) { return ($object) ==> $object->isInstantiable(); } function instantiator<Tu>(array<mixed> $parameters = []) : (function(ClassObject):Tu) { return ($object) ==> $object->instantiate($parameters); } <|endoftext|>
<commit_before>//===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/CodeGen/CodeGenAction.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclGroup.h" #include "clang/CodeGen/BackendUtil.h" #include "clang/CodeGen/ModuleBuilder.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/Support/IRReader.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/Timer.h" using namespace clang; using namespace llvm; namespace clang { class BackendConsumer : public ASTConsumer { Diagnostic &Diags; BackendAction Action; const CodeGenOptions &CodeGenOpts; const TargetOptions &TargetOpts; const LangOptions &LangOpts; raw_ostream *AsmOutStream; ASTContext *Context; Timer LLVMIRGeneration; llvm::OwningPtr<CodeGenerator> Gen; llvm::OwningPtr<llvm::Module> TheModule; public: BackendConsumer(BackendAction action, Diagnostic &_Diags, const CodeGenOptions &compopts, const TargetOptions &targetopts, const LangOptions &langopts, bool TimePasses, const std::string &infile, raw_ostream *OS, LLVMContext &C) : Diags(_Diags), Action(action), CodeGenOpts(compopts), TargetOpts(targetopts), LangOpts(langopts), AsmOutStream(OS), LLVMIRGeneration("LLVM IR Generation Time"), Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)) { llvm::TimePassesIsEnabled = TimePasses; } llvm::Module *takeModule() { return TheModule.take(); } virtual void Initialize(ASTContext &Ctx) { Context = &Ctx; if (llvm::TimePassesIsEnabled) LLVMIRGeneration.startTimer(); Gen->Initialize(Ctx); TheModule.reset(Gen->GetModule()); if (llvm::TimePassesIsEnabled) LLVMIRGeneration.stopTimer(); } virtual void HandleTopLevelDecl(DeclGroupRef D) { PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(), Context->getSourceManager(), "LLVM IR generation of declaration"); if (llvm::TimePassesIsEnabled) LLVMIRGeneration.startTimer(); Gen->HandleTopLevelDecl(D); if (llvm::TimePassesIsEnabled) LLVMIRGeneration.stopTimer(); } virtual void HandleTranslationUnit(ASTContext &C) { { PrettyStackTraceString CrashInfo("Per-file LLVM IR generation"); if (llvm::TimePassesIsEnabled) LLVMIRGeneration.startTimer(); Gen->HandleTranslationUnit(C); if (llvm::TimePassesIsEnabled) LLVMIRGeneration.stopTimer(); } // Silently ignore if we weren't initialized for some reason. if (!TheModule) return; // Make sure IR generation is happy with the module. This is released by // the module provider. Module *M = Gen->ReleaseModule(); if (!M) { // The module has been released by IR gen on failures, do not double // free. TheModule.take(); return; } assert(TheModule.get() == M && "Unexpected module change during IR generation"); // Install an inline asm handler so that diagnostics get printed through // our diagnostics hooks. LLVMContext &Ctx = TheModule->getContext(); LLVMContext::InlineAsmDiagHandlerTy OldHandler = Ctx.getInlineAsmDiagnosticHandler(); void *OldContext = Ctx.getInlineAsmDiagnosticContext(); Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this); EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts, TheModule.get(), Action, AsmOutStream); Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext); } virtual void HandleTagDeclDefinition(TagDecl *D) { PrettyStackTraceDecl CrashInfo(D, SourceLocation(), Context->getSourceManager(), "LLVM IR generation of declaration"); Gen->HandleTagDeclDefinition(D); } virtual void CompleteTentativeDefinition(VarDecl *D) { Gen->CompleteTentativeDefinition(D); } virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) { Gen->HandleVTable(RD, DefinitionRequired); } static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context, unsigned LocCookie) { SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie); ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc); } void InlineAsmDiagHandler2(const llvm::SMDiagnostic &, SourceLocation LocCookie); }; } /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr /// buffer to be a valid FullSourceLoc. static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D, SourceManager &CSM) { // Get both the clang and llvm source managers. The location is relative to // a memory buffer that the LLVM Source Manager is handling, we need to add // a copy to the Clang source manager. const llvm::SourceMgr &LSM = *D.getSourceMgr(); // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr // already owns its one and clang::SourceManager wants to own its one. const MemoryBuffer *LBuf = LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc())); // Create the copy and transfer ownership to clang::SourceManager. llvm::MemoryBuffer *CBuf = llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(), LBuf->getBufferIdentifier()); FileID FID = CSM.createFileIDForMemBuffer(CBuf); // Translate the offset into the file. unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart(); SourceLocation NewLoc = CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset); return FullSourceLoc(NewLoc, CSM); } /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an /// error parsing inline asm. The SMDiagnostic indicates the error relative to /// the temporary memory buffer that the inline asm parser has set up. void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D, SourceLocation LocCookie) { // There are a couple of different kinds of errors we could get here. First, // we re-format the SMDiagnostic in terms of a clang diagnostic. // Strip "error: " off the start of the message string. StringRef Message = D.getMessage(); if (Message.startswith("error: ")) Message = Message.substr(7); // If the SMDiagnostic has an inline asm source location, translate it. FullSourceLoc Loc; if (D.getLoc() != SMLoc()) Loc = ConvertBackendLocation(D, Context->getSourceManager()); // If this problem has clang-level source location information, report the // issue as being an error in the source with a note showing the instantiated // code. if (LocCookie.isValid()) { Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message); if (D.getLoc().isValid()) Diags.Report(Loc, diag::note_fe_inline_asm_here); return; } // Otherwise, report the backend error as occurring in the generated .s file. // If Loc is invalid, we still need to report the error, it just gets no // location info. Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message); } // CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext) : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext), OwnsVMContext(!_VMContext) {} CodeGenAction::~CodeGenAction() { TheModule.reset(); if (OwnsVMContext) delete VMContext; } bool CodeGenAction::hasIRSupport() const { return true; } void CodeGenAction::EndSourceFileAction() { // If the consumer creation failed, do nothing. if (!getCompilerInstance().hasASTConsumer()) return; // Steal the module from the consumer. TheModule.reset(BEConsumer->takeModule()); } llvm::Module *CodeGenAction::takeModule() { return TheModule.take(); } llvm::LLVMContext *CodeGenAction::takeLLVMContext() { OwnsVMContext = false; return VMContext; } static raw_ostream *GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) { switch (Action) { case Backend_EmitAssembly: return CI.createDefaultOutputFile(false, InFile, "s"); case Backend_EmitLL: return CI.createDefaultOutputFile(false, InFile, "ll"); case Backend_EmitBC: return CI.createDefaultOutputFile(true, InFile, "bc"); case Backend_EmitNothing: return 0; case Backend_EmitMCNull: case Backend_EmitObj: return CI.createDefaultOutputFile(true, InFile, "o"); } assert(0 && "Invalid action!"); return 0; } ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { BackendAction BA = static_cast<BackendAction>(Act); llvm::OwningPtr<raw_ostream> OS(GetOutputStream(CI, InFile, BA)); if (BA != Backend_EmitNothing && !OS) return 0; BEConsumer = new BackendConsumer(BA, CI.getDiagnostics(), CI.getCodeGenOpts(), CI.getTargetOpts(), CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, OS.take(), *VMContext); return BEConsumer; } void CodeGenAction::ExecuteAction() { // If this is an IR file, we have to treat it specially. if (getCurrentFileKind() == IK_LLVM_IR) { BackendAction BA = static_cast<BackendAction>(Act); CompilerInstance &CI = getCompilerInstance(); raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA); if (BA != Backend_EmitNothing && !OS) return; bool Invalid; SourceManager &SM = CI.getSourceManager(); const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(), &Invalid); if (Invalid) return; // FIXME: This is stupid, IRReader shouldn't take ownership. llvm::MemoryBuffer *MainFileCopy = llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(), getCurrentFile().c_str()); llvm::SMDiagnostic Err; TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext)); if (!TheModule) { // Translate from the diagnostic info to the SourceManager location. SourceLocation Loc = SM.getLocation( SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(), Err.getColumnNo() + 1); // Get a custom diagnostic for the error. We strip off a leading // diagnostic code if there is one. StringRef Msg = Err.getMessage(); if (Msg.startswith("error: ")) Msg = Msg.substr(7); unsigned DiagID = CI.getDiagnostics().getCustomDiagID(Diagnostic::Error, Msg); CI.getDiagnostics().Report(Loc, DiagID); return; } EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), CI.getTargetOpts(), CI.getLangOpts(), TheModule.get(), BA, OS); return; } // Otherwise follow the normal AST path. this->ASTFrontendAction::ExecuteAction(); } // EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext) : CodeGenAction(Backend_EmitAssembly, _VMContext) {} EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext) : CodeGenAction(Backend_EmitBC, _VMContext) {} EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext) : CodeGenAction(Backend_EmitLL, _VMContext) {} EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext) : CodeGenAction(Backend_EmitNothing, _VMContext) {} EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext) : CodeGenAction(Backend_EmitMCNull, _VMContext) {} EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext) : CodeGenAction(Backend_EmitObj, _VMContext) {} <commit_msg>In CodeGenAction::ExecuteAction() use SourceManager::translateFileLineCol() instead of getLocation() since we don't care about expanded macro arguments.<commit_after>//===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/CodeGen/CodeGenAction.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclGroup.h" #include "clang/CodeGen/BackendUtil.h" #include "clang/CodeGen/ModuleBuilder.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/Support/IRReader.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/Timer.h" using namespace clang; using namespace llvm; namespace clang { class BackendConsumer : public ASTConsumer { Diagnostic &Diags; BackendAction Action; const CodeGenOptions &CodeGenOpts; const TargetOptions &TargetOpts; const LangOptions &LangOpts; raw_ostream *AsmOutStream; ASTContext *Context; Timer LLVMIRGeneration; llvm::OwningPtr<CodeGenerator> Gen; llvm::OwningPtr<llvm::Module> TheModule; public: BackendConsumer(BackendAction action, Diagnostic &_Diags, const CodeGenOptions &compopts, const TargetOptions &targetopts, const LangOptions &langopts, bool TimePasses, const std::string &infile, raw_ostream *OS, LLVMContext &C) : Diags(_Diags), Action(action), CodeGenOpts(compopts), TargetOpts(targetopts), LangOpts(langopts), AsmOutStream(OS), LLVMIRGeneration("LLVM IR Generation Time"), Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)) { llvm::TimePassesIsEnabled = TimePasses; } llvm::Module *takeModule() { return TheModule.take(); } virtual void Initialize(ASTContext &Ctx) { Context = &Ctx; if (llvm::TimePassesIsEnabled) LLVMIRGeneration.startTimer(); Gen->Initialize(Ctx); TheModule.reset(Gen->GetModule()); if (llvm::TimePassesIsEnabled) LLVMIRGeneration.stopTimer(); } virtual void HandleTopLevelDecl(DeclGroupRef D) { PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(), Context->getSourceManager(), "LLVM IR generation of declaration"); if (llvm::TimePassesIsEnabled) LLVMIRGeneration.startTimer(); Gen->HandleTopLevelDecl(D); if (llvm::TimePassesIsEnabled) LLVMIRGeneration.stopTimer(); } virtual void HandleTranslationUnit(ASTContext &C) { { PrettyStackTraceString CrashInfo("Per-file LLVM IR generation"); if (llvm::TimePassesIsEnabled) LLVMIRGeneration.startTimer(); Gen->HandleTranslationUnit(C); if (llvm::TimePassesIsEnabled) LLVMIRGeneration.stopTimer(); } // Silently ignore if we weren't initialized for some reason. if (!TheModule) return; // Make sure IR generation is happy with the module. This is released by // the module provider. Module *M = Gen->ReleaseModule(); if (!M) { // The module has been released by IR gen on failures, do not double // free. TheModule.take(); return; } assert(TheModule.get() == M && "Unexpected module change during IR generation"); // Install an inline asm handler so that diagnostics get printed through // our diagnostics hooks. LLVMContext &Ctx = TheModule->getContext(); LLVMContext::InlineAsmDiagHandlerTy OldHandler = Ctx.getInlineAsmDiagnosticHandler(); void *OldContext = Ctx.getInlineAsmDiagnosticContext(); Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this); EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts, TheModule.get(), Action, AsmOutStream); Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext); } virtual void HandleTagDeclDefinition(TagDecl *D) { PrettyStackTraceDecl CrashInfo(D, SourceLocation(), Context->getSourceManager(), "LLVM IR generation of declaration"); Gen->HandleTagDeclDefinition(D); } virtual void CompleteTentativeDefinition(VarDecl *D) { Gen->CompleteTentativeDefinition(D); } virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) { Gen->HandleVTable(RD, DefinitionRequired); } static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context, unsigned LocCookie) { SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie); ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc); } void InlineAsmDiagHandler2(const llvm::SMDiagnostic &, SourceLocation LocCookie); }; } /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr /// buffer to be a valid FullSourceLoc. static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D, SourceManager &CSM) { // Get both the clang and llvm source managers. The location is relative to // a memory buffer that the LLVM Source Manager is handling, we need to add // a copy to the Clang source manager. const llvm::SourceMgr &LSM = *D.getSourceMgr(); // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr // already owns its one and clang::SourceManager wants to own its one. const MemoryBuffer *LBuf = LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc())); // Create the copy and transfer ownership to clang::SourceManager. llvm::MemoryBuffer *CBuf = llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(), LBuf->getBufferIdentifier()); FileID FID = CSM.createFileIDForMemBuffer(CBuf); // Translate the offset into the file. unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart(); SourceLocation NewLoc = CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset); return FullSourceLoc(NewLoc, CSM); } /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an /// error parsing inline asm. The SMDiagnostic indicates the error relative to /// the temporary memory buffer that the inline asm parser has set up. void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D, SourceLocation LocCookie) { // There are a couple of different kinds of errors we could get here. First, // we re-format the SMDiagnostic in terms of a clang diagnostic. // Strip "error: " off the start of the message string. StringRef Message = D.getMessage(); if (Message.startswith("error: ")) Message = Message.substr(7); // If the SMDiagnostic has an inline asm source location, translate it. FullSourceLoc Loc; if (D.getLoc() != SMLoc()) Loc = ConvertBackendLocation(D, Context->getSourceManager()); // If this problem has clang-level source location information, report the // issue as being an error in the source with a note showing the instantiated // code. if (LocCookie.isValid()) { Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message); if (D.getLoc().isValid()) Diags.Report(Loc, diag::note_fe_inline_asm_here); return; } // Otherwise, report the backend error as occurring in the generated .s file. // If Loc is invalid, we still need to report the error, it just gets no // location info. Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message); } // CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext) : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext), OwnsVMContext(!_VMContext) {} CodeGenAction::~CodeGenAction() { TheModule.reset(); if (OwnsVMContext) delete VMContext; } bool CodeGenAction::hasIRSupport() const { return true; } void CodeGenAction::EndSourceFileAction() { // If the consumer creation failed, do nothing. if (!getCompilerInstance().hasASTConsumer()) return; // Steal the module from the consumer. TheModule.reset(BEConsumer->takeModule()); } llvm::Module *CodeGenAction::takeModule() { return TheModule.take(); } llvm::LLVMContext *CodeGenAction::takeLLVMContext() { OwnsVMContext = false; return VMContext; } static raw_ostream *GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) { switch (Action) { case Backend_EmitAssembly: return CI.createDefaultOutputFile(false, InFile, "s"); case Backend_EmitLL: return CI.createDefaultOutputFile(false, InFile, "ll"); case Backend_EmitBC: return CI.createDefaultOutputFile(true, InFile, "bc"); case Backend_EmitNothing: return 0; case Backend_EmitMCNull: case Backend_EmitObj: return CI.createDefaultOutputFile(true, InFile, "o"); } assert(0 && "Invalid action!"); return 0; } ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { BackendAction BA = static_cast<BackendAction>(Act); llvm::OwningPtr<raw_ostream> OS(GetOutputStream(CI, InFile, BA)); if (BA != Backend_EmitNothing && !OS) return 0; BEConsumer = new BackendConsumer(BA, CI.getDiagnostics(), CI.getCodeGenOpts(), CI.getTargetOpts(), CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, OS.take(), *VMContext); return BEConsumer; } void CodeGenAction::ExecuteAction() { // If this is an IR file, we have to treat it specially. if (getCurrentFileKind() == IK_LLVM_IR) { BackendAction BA = static_cast<BackendAction>(Act); CompilerInstance &CI = getCompilerInstance(); raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA); if (BA != Backend_EmitNothing && !OS) return; bool Invalid; SourceManager &SM = CI.getSourceManager(); const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(), &Invalid); if (Invalid) return; // FIXME: This is stupid, IRReader shouldn't take ownership. llvm::MemoryBuffer *MainFileCopy = llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(), getCurrentFile().c_str()); llvm::SMDiagnostic Err; TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext)); if (!TheModule) { // Translate from the diagnostic info to the SourceManager location. SourceLocation Loc = SM.translateFileLineCol( SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(), Err.getColumnNo() + 1); // Get a custom diagnostic for the error. We strip off a leading // diagnostic code if there is one. StringRef Msg = Err.getMessage(); if (Msg.startswith("error: ")) Msg = Msg.substr(7); unsigned DiagID = CI.getDiagnostics().getCustomDiagID(Diagnostic::Error, Msg); CI.getDiagnostics().Report(Loc, DiagID); return; } EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), CI.getTargetOpts(), CI.getLangOpts(), TheModule.get(), BA, OS); return; } // Otherwise follow the normal AST path. this->ASTFrontendAction::ExecuteAction(); } // EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext) : CodeGenAction(Backend_EmitAssembly, _VMContext) {} EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext) : CodeGenAction(Backend_EmitBC, _VMContext) {} EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext) : CodeGenAction(Backend_EmitLL, _VMContext) {} EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext) : CodeGenAction(Backend_EmitNothing, _VMContext) {} EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext) : CodeGenAction(Backend_EmitMCNull, _VMContext) {} EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext) : CodeGenAction(Backend_EmitObj, _VMContext) {} <|endoftext|>
<commit_before>/* * jcom.oscroute * External for Jamoma: parse and pass OpenSoundControl messages * By Tim Place, Copyright 2006 * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "Jamoma.h" #define MAX_ARGCOUNT 100 #define MAX_MESS_SIZE 2048 typedef struct _oscroute{ // Data Structure for this object t_object ob; // REQUIRED: Our object void *outlets[MAX_ARGCOUNT]; // my outlet array void *outlet_overflow; // this outlet doubles as the dumpout outlet t_symbol *arguments[MAX_ARGCOUNT]; // symbols to match long unsigned arglen[MAX_ARGCOUNT]; // strlen of symbols to match short num_args; long attr_strip; // ATTRIBUTE: 1 = strip leading slash off any messages void *proxy_inlet; // pointer to the second inlet (when present) } t_oscroute; // Prototypes for our methods: void *oscroute_new(t_symbol *s, long argc, t_atom *argv); void oscroute_free(t_oscroute *x); void oscroute_assist(t_oscroute *x, void *b, long msg, long arg, char *dst); void oscroute_bang(t_oscroute *x); void oscroute_int(t_oscroute *x, long n); void oscroute_float(t_oscroute *x, double f); void oscroute_list(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv); void oscroute_symbol(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv); //void oscroute_list(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv); // Globals t_class *oscroute_class; // Required: Global pointer for our class /************************************************************************************/ // Main() Function int JAMOMA_EXPORT_MAXOBJ main(void) { long attrflags = 0; t_class *c; t_object *attr; // Initialize Globals jamoma_init(); common_symbols_init(); // Define our class c = class_new("jcom.oscroute",(method)oscroute_new, (method)oscroute_free, sizeof(t_oscroute), (method)0L, A_GIMME, 0); // Make methods accessible for our class: class_addmethod(c, (method)oscroute_bang, "bang", 0L, 0L); class_addmethod(c, (method)oscroute_int, "int", A_DEFLONG, 0L); class_addmethod(c, (method)oscroute_float, "float", A_DEFFLOAT, 0L); class_addmethod(c, (method)oscroute_list, "list", A_GIMME, 0L); class_addmethod(c, (method)oscroute_symbol, "anything", A_GIMME, 0L); class_addmethod(c, (method)oscroute_assist, "assist", A_CANT, 0L); class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT, 0); // ATTRIBUTE: strip attr = attr_offset_new("strip", _sym_long, attrflags, (method)0, (method)0, calcoffset(t_oscroute, attr_strip)); class_addattr(c, attr); // Finalize our class class_register(CLASS_BOX, c); oscroute_class = c; return 0; } /************************************************************************************/ // Object Life void *oscroute_new(t_symbol *s, long argc, t_atom *argv) { short i; t_oscroute *x = (t_oscroute *)object_alloc(oscroute_class); if(x){ x->outlet_overflow = outlet_new(x, 0); // overflow outlet //object_obex_store((void *)x, _sym_dumpout, (object *)x->outlet_overflow); // dumpout x->num_args = argc; if(argc < 1){ // if no args are provided, we provide a way to set the arg using an inlet x->num_args = 1; x->arguments[0] = gensym("/nil"); x->arglen[0] = 4; x->proxy_inlet = proxy_new(x, 1, 0L); x->outlets[0] = outlet_new(x, 0); } else{ x->proxy_inlet = 0; for(i=x->num_args-1; i >= 0; i--){ x->outlets[i] = outlet_new(x, 0); // Create Outlet switch(argv[i].a_type){ case A_SYM: //atom_setsym(&(x->arguments[i]), atom_getsym(argv+i)); x->arguments[i] = atom_getsym(argv+i); x->arglen[i] = strlen(atom_getsym(argv+i)->s_name); break; case A_LONG: { char tempstr[256]; snprintf(tempstr, 256, "%ld", atom_getlong(argv+i)); x->arguments[i] = gensym(tempstr); x->arglen[i] = strlen(tempstr); } break; case A_FLOAT: { char tempstr[256]; snprintf(tempstr, 256, "%f", atom_getfloat(argv+i)); x->arguments[i] = gensym(tempstr); x->arglen[i] = strlen(tempstr); } break; default: error("jcom.oscroute - invalid arguments - all args must be symbols"); } } } //attr_args_process(x, argc, argv); //handle attribute args } return (x); // return the pointer to our new instantiation } void oscroute_free(t_oscroute *x) { if(x->proxy_inlet != 0) freeobject((t_object *)(x->proxy_inlet)); } /************************************************************************************/ // Methods bound to input/inlets // Method for Assistance Messages void oscroute_assist(t_oscroute *x, void *b, long msg, long arg, char *dst) { if(msg==1) // Inlet strcpy(dst, "Input"); else if(msg==2){ // Outlets if(arg < x->num_args) strcpy(dst, x->arguments[arg]->s_name); else strcpy(dst, "dumpout / overflow from non-matching input"); } } // BANG INPUT: STRAIGHT TO OVERFLOW void oscroute_bang(t_oscroute *x) { outlet_bang(x->outlet_overflow); } // INT INPUT: STRAIGHT TO OVERFLOW void oscroute_int(t_oscroute *x, long n) { outlet_int(x->outlet_overflow, n); } // FLOAT INPUT: STRAIGHT TO OVERFLOW void oscroute_float(t_oscroute *x, double f) { outlet_float(x->outlet_overflow, f); } // LIST INPUT: STRAIGHT TO OVERFLOW void oscroute_list(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv) { outlet_list(x->outlet_overflow, _sym_list, argc , argv); } void output_msg(t_oscroute *x, char *msg, int outlet, long argc, t_atom *argv) { t_symbol *output; if(msg == '\0') { if (argc == 0) { outlet_bang(x->outlets[outlet]); } else if (argc==1) { if (argv->a_type==A_LONG) outlet_int(x->outlets[outlet],argv->a_w.w_long); else if (argv->a_type==A_FLOAT) outlet_float(x->outlets[outlet],argv->a_w.w_float); else if (argv->a_type==A_SYM) outlet_anything(x->outlets[outlet],argv->a_w.w_sym,0,0); } else { if (argv->a_type==A_SYM) { output = argv->a_w.w_sym; argc--; argv++; } else { output = _sym_list; } outlet_anything(x->outlets[outlet], output, argc, argv); } } else outlet_anything(x->outlets[outlet], gensym(msg), argc, argv); } // SYMBOL INPUT void oscroute_symbol(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv) { t_symbol *output; char input[MAX_MESS_SIZE]; // our input string long inlet = proxy_getinlet((t_object *)x); // If the message comes in the second inlet, then set the string to match... if(inlet == 1){ x->arguments[0] = msg; x->arglen[0] = strlen(msg->s_name); return; } // Otherwise match the stored string(s) and output... strcpy(input, msg->s_name); // Make sure we are dealing with valid OSC input by looking for a leading slash if(input[0] != '/') { outlet_anything(x->outlet_overflow, msg, argc , argv); return; } char *wc, *c; bool overFlow = true; for (int pos=0; pos < x->num_args; pos++) { // Look for exact matches first. if (strncmp(msg->s_name, x->arguments[pos]->s_name, x->arglen[pos])==0) { // If incoming message is longer than argument... if (strlen(msg->s_name) > x->arglen[pos]){ // ...it is only a match if it continues with a slash if (input[x->arglen[pos]] == '/') { output = gensym(msg->s_name + x->arglen[pos]); outlet_anything(x->outlets[pos], output, argc , argv); overFlow = false; break; } } // If the incoming message is no longer we know that we have a match else { // We then have to check what message to return. // The message received has no arguments: if (argc == 0) { outlet_bang(x->outlets[pos]); overFlow = false; break; } // The message received has one argument only: else if (argc==1) { overFlow = false; // int argument if (argv->a_type==A_LONG) { outlet_int(x->outlets[pos],argv->a_w.w_long); break; } // float argument else if (argv->a_type==A_FLOAT) { outlet_float(x->outlets[pos],argv->a_w.w_float); break; } // something else else if (argv->a_type==A_SYM) { outlet_anything(x->outlets[pos],argv->a_w.w_sym,0,0); break; } } // There are two or more arguments: check if first is A_SYM else { if (argv->a_type==A_SYM) { output = argv->a_w.w_sym; argc--; argv++; } else output = _sym_list; outlet_anything(x->outlets[pos], output, argc , argv); overFlow = false; break; } } } } // XXX Putting this here makes crashes go away. It would be really good to know why. //cpost("temp hack to prevent optimizations that cause this object to crash in Deployment"); // If no exact matches, look for wildcards. for (int index=0; index < x->num_args; index++) { if(wc = strstr(x->arguments[index]->s_name, "*")) { // Does the argument have anything following the wildcard? if(*(wc+1) == '\0') { // Now compare the argument up to the asterisk to the message if(strncmp(msg->s_name, x->arguments[index]->s_name, x->arglen[index] - 1) == 0) { // Increment string past everything that matches including the asterisk char *temp = msg->s_name + (x->arglen[index] - 1); // Check for a slash, an asterisk causes us to strip off everything up to the next slash char *outMsg = strstr(temp, "/"); if(outMsg) output_msg(x, outMsg, index, argc, argv); else { // no slash, output everything following the message output_msg(x, NULL, index, argc, argv); } return; } else { // We break here because if the strncmp() fails it means we have a wildcard following an // OSC message i.e. /robot/* but the incoming message doesn't begin with /robot //break; } } else { // There is no NULL char after asterisk c = msg->s_name; while(wc && *(wc) == '*') { wc++; c++; } c += strlen(c) - strlen(wc); if(strncmp(c, wc, strlen(c)) == 0) { output_msg(x, c, index, argc, argv); return; } } } } // the message was never reckognised if(overFlow) outlet_anything(x->outlet_overflow, msg, argc , argv); } <commit_msg>commenting out the definition of attribute "strip", because it is unused in the code.<commit_after>/* * jcom.oscroute * External for Jamoma: parse and pass OpenSoundControl messages * By Tim Place, Copyright � 2006 * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "Jamoma.h" #define MAX_ARGCOUNT 100 #define MAX_MESS_SIZE 2048 typedef struct _oscroute{ // Data Structure for this object t_object ob; // REQUIRED: Our object void *outlets[MAX_ARGCOUNT]; // my outlet array void *outlet_overflow; // this outlet doubles as the dumpout outlet t_symbol *arguments[MAX_ARGCOUNT]; // symbols to match long unsigned arglen[MAX_ARGCOUNT]; // strlen of symbols to match short num_args; //long attr_strip; // ATTRIBUTE: 1 = strip leading slash off any messages void *proxy_inlet; // pointer to the second inlet (when present) } t_oscroute; // Prototypes for our methods: void *oscroute_new(t_symbol *s, long argc, t_atom *argv); void oscroute_free(t_oscroute *x); void oscroute_assist(t_oscroute *x, void *b, long msg, long arg, char *dst); void oscroute_bang(t_oscroute *x); void oscroute_int(t_oscroute *x, long n); void oscroute_float(t_oscroute *x, double f); void oscroute_list(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv); void oscroute_symbol(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv); //void oscroute_list(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv); // Globals t_class *oscroute_class; // Required: Global pointer for our class /************************************************************************************/ // Main() Function int JAMOMA_EXPORT_MAXOBJ main(void) { //long attrflags = 0; t_class *c; //t_object *attr; // Initialize Globals jamoma_init(); common_symbols_init(); // Define our class c = class_new("jcom.oscroute",(method)oscroute_new, (method)oscroute_free, sizeof(t_oscroute), (method)0L, A_GIMME, 0); // Make methods accessible for our class: class_addmethod(c, (method)oscroute_bang, "bang", 0L, 0L); class_addmethod(c, (method)oscroute_int, "int", A_DEFLONG, 0L); class_addmethod(c, (method)oscroute_float, "float", A_DEFFLOAT, 0L); class_addmethod(c, (method)oscroute_list, "list", A_GIMME, 0L); class_addmethod(c, (method)oscroute_symbol, "anything", A_GIMME, 0L); class_addmethod(c, (method)oscroute_assist, "assist", A_CANT, 0L); class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT, 0); // ATTRIBUTE: strip /*attr = attr_offset_new("strip", _sym_long, attrflags, (method)0, (method)0, calcoffset(t_oscroute, attr_strip)); class_addattr(c, attr); */ // Finalize our class class_register(CLASS_BOX, c); oscroute_class = c; return 0; } /************************************************************************************/ // Object Life void *oscroute_new(t_symbol *s, long argc, t_atom *argv) { short i; t_oscroute *x = (t_oscroute *)object_alloc(oscroute_class); if(x){ x->outlet_overflow = outlet_new(x, 0); // overflow outlet //object_obex_store((void *)x, _sym_dumpout, (object *)x->outlet_overflow); // dumpout x->num_args = argc; if(argc < 1){ // if no args are provided, we provide a way to set the arg using an inlet x->num_args = 1; x->arguments[0] = gensym("/nil"); x->arglen[0] = 4; x->proxy_inlet = proxy_new(x, 1, 0L); x->outlets[0] = outlet_new(x, 0); } else{ x->proxy_inlet = 0; for(i=x->num_args-1; i >= 0; i--){ x->outlets[i] = outlet_new(x, 0); // Create Outlet switch(argv[i].a_type){ case A_SYM: //atom_setsym(&(x->arguments[i]), atom_getsym(argv+i)); x->arguments[i] = atom_getsym(argv+i); x->arglen[i] = strlen(atom_getsym(argv+i)->s_name); break; case A_LONG: { char tempstr[256]; snprintf(tempstr, 256, "%ld", atom_getlong(argv+i)); x->arguments[i] = gensym(tempstr); x->arglen[i] = strlen(tempstr); } break; case A_FLOAT: { char tempstr[256]; snprintf(tempstr, 256, "%f", atom_getfloat(argv+i)); x->arguments[i] = gensym(tempstr); x->arglen[i] = strlen(tempstr); } break; default: error("jcom.oscroute - invalid arguments - all args must be symbols"); } } } //attr_args_process(x, argc, argv); //handle attribute args } return (x); // return the pointer to our new instantiation } void oscroute_free(t_oscroute *x) { if(x->proxy_inlet != 0) freeobject((t_object *)(x->proxy_inlet)); } /************************************************************************************/ // Methods bound to input/inlets // Method for Assistance Messages void oscroute_assist(t_oscroute *x, void *b, long msg, long arg, char *dst) { if(msg==1) // Inlet strcpy(dst, "Input"); else if(msg==2){ // Outlets if(arg < x->num_args) strcpy(dst, x->arguments[arg]->s_name); else strcpy(dst, "dumpout / overflow from non-matching input"); } } // BANG INPUT: STRAIGHT TO OVERFLOW void oscroute_bang(t_oscroute *x) { outlet_bang(x->outlet_overflow); } // INT INPUT: STRAIGHT TO OVERFLOW void oscroute_int(t_oscroute *x, long n) { outlet_int(x->outlet_overflow, n); } // FLOAT INPUT: STRAIGHT TO OVERFLOW void oscroute_float(t_oscroute *x, double f) { outlet_float(x->outlet_overflow, f); } // LIST INPUT: STRAIGHT TO OVERFLOW void oscroute_list(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv) { outlet_list(x->outlet_overflow, _sym_list, argc , argv); } void output_msg(t_oscroute *x, char *msg, int outlet, long argc, t_atom *argv) { t_symbol *output; if(msg == '\0') { if (argc == 0) { outlet_bang(x->outlets[outlet]); } else if (argc==1) { if (argv->a_type==A_LONG) outlet_int(x->outlets[outlet],argv->a_w.w_long); else if (argv->a_type==A_FLOAT) outlet_float(x->outlets[outlet],argv->a_w.w_float); else if (argv->a_type==A_SYM) outlet_anything(x->outlets[outlet],argv->a_w.w_sym,0,0); } else { if (argv->a_type==A_SYM) { output = argv->a_w.w_sym; argc--; argv++; } else { output = _sym_list; } outlet_anything(x->outlets[outlet], output, argc, argv); } } else outlet_anything(x->outlets[outlet], gensym(msg), argc, argv); } // SYMBOL INPUT void oscroute_symbol(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv) { t_symbol *output; char input[MAX_MESS_SIZE]; // our input string long inlet = proxy_getinlet((t_object *)x); // If the message comes in the second inlet, then set the string to match... if(inlet == 1){ x->arguments[0] = msg; x->arglen[0] = strlen(msg->s_name); return; } // Otherwise match the stored string(s) and output... strcpy(input, msg->s_name); // Make sure we are dealing with valid OSC input by looking for a leading slash if(input[0] != '/') { outlet_anything(x->outlet_overflow, msg, argc , argv); return; } char *wc, *c; bool overFlow = true; for (int pos=0; pos < x->num_args; pos++) { // Look for exact matches first. if (strncmp(msg->s_name, x->arguments[pos]->s_name, x->arglen[pos])==0) { // If incoming message is longer than argument... if (strlen(msg->s_name) > x->arglen[pos]){ // ...it is only a match if it continues with a slash if (input[x->arglen[pos]] == '/') { output = gensym(msg->s_name + x->arglen[pos]); outlet_anything(x->outlets[pos], output, argc , argv); overFlow = false; break; } } // If the incoming message is no longer we know that we have a match else { // We then have to check what message to return. // The message received has no arguments: if (argc == 0) { outlet_bang(x->outlets[pos]); overFlow = false; break; } // The message received has one argument only: else if (argc==1) { overFlow = false; // int argument if (argv->a_type==A_LONG) { outlet_int(x->outlets[pos],argv->a_w.w_long); break; } // float argument else if (argv->a_type==A_FLOAT) { outlet_float(x->outlets[pos],argv->a_w.w_float); break; } // something else else if (argv->a_type==A_SYM) { outlet_anything(x->outlets[pos],argv->a_w.w_sym,0,0); break; } } // There are two or more arguments: check if first is A_SYM else { if (argv->a_type==A_SYM) { output = argv->a_w.w_sym; argc--; argv++; } else output = _sym_list; outlet_anything(x->outlets[pos], output, argc , argv); overFlow = false; break; } } } } // XXX Putting this here makes crashes go away. It would be really good to know why. //cpost("temp hack to prevent optimizations that cause this object to crash in Deployment"); // If no exact matches, look for wildcards. for (int index=0; index < x->num_args; index++) { if(wc = strstr(x->arguments[index]->s_name, "*")) { // Does the argument have anything following the wildcard? if(*(wc+1) == '\0') { // Now compare the argument up to the asterisk to the message if(strncmp(msg->s_name, x->arguments[index]->s_name, x->arglen[index] - 1) == 0) { // Increment string past everything that matches including the asterisk char *temp = msg->s_name + (x->arglen[index] - 1); // Check for a slash, an asterisk causes us to strip off everything up to the next slash char *outMsg = strstr(temp, "/"); if(outMsg) output_msg(x, outMsg, index, argc, argv); else { // no slash, output everything following the message output_msg(x, NULL, index, argc, argv); } return; } else { // We break here because if the strncmp() fails it means we have a wildcard following an // OSC message i.e. /robot/* but the incoming message doesn't begin with /robot //break; } } else { // There is no NULL char after asterisk c = msg->s_name; while(wc && *(wc) == '*') { wc++; c++; } c += strlen(c) - strlen(wc); if(strncmp(c, wc, strlen(c)) == 0) { output_msg(x, c, index, argc, argv); return; } } } } // the message was never reckognised if(overFlow) outlet_anything(x->outlet_overflow, msg, argc , argv); } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkMetaImageStreamingWriterIOTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif #include <fstream> #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkMetaImageIO.h" int itkMetaImageStreamingWriterIOTest(int ac, char* av[]) { if(ac<3) { std::cerr << "Usage: " << av[0] << " input output" << std::endl; } // We remove the output file itksys::SystemTools::RemoveFile(av[2]); typedef unsigned short PixelType; typedef itk::Image<PixelType,3> ImageType; itk::MetaImageIO::Pointer metaImageIO = itk::MetaImageIO::New(); typedef itk::ImageFileReader<ImageType> ReaderType; typedef itk::ImageFileWriter< ImageType > WriterType; ReaderType::Pointer reader = ReaderType::New(); reader->SetImageIO(metaImageIO); reader->SetFileName(av[1]); reader->SetUseStreaming(true); metaImageIO->SetUseStreamedReading(true); ImageType::RegionType region; ImageType::SizeType size; ImageType::SizeType fullsize; ImageType::IndexType index; unsigned int m_NumberOfPieces = 10; // We decide how we want to read the image and we split accordingly // The image is read slice by slice reader->GenerateOutputInformation(); fullsize = reader->GetOutput()->GetLargestPossibleRegion().GetSize(); index.Fill(0); size[0] = fullsize[0]; size[1] = fullsize[1]; size[2] = 0; unsigned int zsize = fullsize[2]/m_NumberOfPieces; // Setup the writer WriterType::Pointer writer = WriterType::New(); writer->SetFileName(av[2]); for(unsigned int i=0;i<m_NumberOfPieces;i++) { std::cout << "Reading piece " << i+1 << " of " << m_NumberOfPieces << std::endl; index[2] += size[2]; // At the end we need to adjust the size to make sure // we are reading everything if(i == m_NumberOfPieces-1) { size[2] = fullsize[2]-index[2]; } else { size[2] = zsize; } region.SetIndex(index); region.SetSize(size); reader->GetOutput()->SetRequestedRegion(region); try { reader->Update(); } catch (itk::ExceptionObject &ex) { std::cout << "ERROR : " << ex << std::endl; return EXIT_FAILURE; } // Write the image itk::ImageIORegion ioregion(3); itk::ImageIORegion::IndexType index2; index2.push_back(region.GetIndex()[0]); index2.push_back(region.GetIndex()[1]); index2.push_back(region.GetIndex()[2]); ioregion.SetIndex(index2); itk::ImageIORegion::SizeType size2; size2.push_back(region.GetSize()[0]); size2.push_back(region.GetSize()[1]); size2.push_back(region.GetSize()[2]); ioregion.SetSize(size2); writer->SetIORegion(ioregion); writer->SetInput(reader->GetOutput()); try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } } // end for pieces return EXIT_SUCCESS; } <commit_msg>BUG: Pixel type is unsigned char<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkMetaImageStreamingWriterIOTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif #include <fstream> #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkMetaImageIO.h" int itkMetaImageStreamingWriterIOTest(int ac, char* av[]) { if(ac<3) { std::cerr << "Usage: " << av[0] << " input output" << std::endl; } // We remove the output file itksys::SystemTools::RemoveFile(av[2]); typedef unsigned char PixelType; typedef itk::Image<PixelType,3> ImageType; itk::MetaImageIO::Pointer metaImageIO = itk::MetaImageIO::New(); typedef itk::ImageFileReader<ImageType> ReaderType; typedef itk::ImageFileWriter< ImageType > WriterType; ReaderType::Pointer reader = ReaderType::New(); reader->SetImageIO(metaImageIO); reader->SetFileName(av[1]); reader->SetUseStreaming(true); metaImageIO->SetUseStreamedReading(true); ImageType::RegionType region; ImageType::SizeType size; ImageType::SizeType fullsize; ImageType::IndexType index; unsigned int m_NumberOfPieces = 10; // We decide how we want to read the image and we split accordingly // The image is read slice by slice reader->GenerateOutputInformation(); fullsize = reader->GetOutput()->GetLargestPossibleRegion().GetSize(); index.Fill(0); size[0] = fullsize[0]; size[1] = fullsize[1]; size[2] = 0; unsigned int zsize = fullsize[2]/m_NumberOfPieces; // Setup the writer WriterType::Pointer writer = WriterType::New(); writer->SetFileName(av[2]); for(unsigned int i=0;i<m_NumberOfPieces;i++) { std::cout << "Reading piece " << i+1 << " of " << m_NumberOfPieces << std::endl; index[2] += size[2]; // At the end we need to adjust the size to make sure // we are reading everything if(i == m_NumberOfPieces-1) { size[2] = fullsize[2]-index[2]; } else { size[2] = zsize; } region.SetIndex(index); region.SetSize(size); reader->GetOutput()->SetRequestedRegion(region); try { reader->Update(); } catch (itk::ExceptionObject &ex) { std::cout << "ERROR : " << ex << std::endl; return EXIT_FAILURE; } // Write the image itk::ImageIORegion ioregion(3); itk::ImageIORegion::IndexType index2; index2.push_back(region.GetIndex()[0]); index2.push_back(region.GetIndex()[1]); index2.push_back(region.GetIndex()[2]); ioregion.SetIndex(index2); itk::ImageIORegion::SizeType size2; size2.push_back(region.GetSize()[0]); size2.push_back(region.GetSize()[1]); size2.push_back(region.GetSize()[2]); ioregion.SetSize(size2); writer->SetIORegion(ioregion); writer->SetInput(reader->GetOutput()); try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } } // end for pieces return EXIT_SUCCESS; } <|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. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkExceptionObject.h" #include <fstream> #include <iostream> #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbTerraSarImageMetadataInterface.h" int otbTerraSarImageMetadataInterface(int argc, char* argv[]) { // Verify the number of parameters in the command line const char * inputFilename = argv[1]; const char * outputFilename = argv[2]; typedef otb::VectorImage<double, 2> InputImageType; typedef otb::ImageFileReader<InputImageType> ImageReaderType; typedef std::vector<double> DoubleVectorType; typedef std::vector<DoubleVectorType> DoubleVectorVectorType; typedef std::vector<unsigned int> UIntVectorType; typedef itk::ImageBase<2> ImageType; typedef ImageType::IndexType IndexType; typedef std::vector<IndexType> IndexVectorType; ImageReaderType::Pointer reader = ImageReaderType::New(); reader->SetFileName(inputFilename); reader->UpdateOutputInformation(); otb::TerraSarImageMetadataInterface::Pointer lImageMetadata = otb::TerraSarImageMetadataInterface::New(); std::ofstream file; file.open(outputFilename); file << "GetSensorID: " << lImageMetadata->GetSensorID() << std::endl; file << "GetMinute: " << lImageMetadata->GetMinute() << std::endl; file << "GetHour: " << lImageMetadata->GetHour() << std::endl; file << "GetDay: " << lImageMetadata->GetDay() << std::endl; file << "GetMonth: " << lImageMetadata->GetMonth() << std::endl; file << "GetYear: " << lImageMetadata->GetYear() << std::endl; file << "GetProductionDay: " << lImageMetadata->GetProductionDay() << std::endl; file << "GetProductionMonth: " << lImageMetadata->GetProductionMonth() << std::endl; file << "GetProductionYear: " << lImageMetadata->GetProductionYear() << std::endl; file << "GetCalibrationFactor: " << lImageMetadata->GetCalibrationFactor() << std::endl; file << "GetRadarFrequency: " << lImageMetadata->GetRadarFrequency() << std::endl; file << "GetPRF: " << lImageMetadata->GetPRF() << std::endl; file << std::endl; file << "Noise attributs: " << std::endl; UIntVectorType deg = lImageMetadata->GetNoisePolynomialDegrees(); DoubleVectorVectorType coeffs = lImageMetadata->GetNoisePolynomialCoefficientsList(); DoubleVectorType mins = lImageMetadata->GetNoiseValidityRangeMinList(); DoubleVectorType maxs = lImageMetadata->GetNoiseValidityRangeMaxList(); DoubleVectorType ref = lImageMetadata->GetNoiseReferencePointList(); DoubleVectorType time = lImageMetadata->GetNoiseTimeUTCList(); file << "GetNumberOfNoiseRecords: " << lImageMetadata->GetNumberOfNoiseRecords() << std::endl; for (unsigned int i = 0; i < deg.size(); i++) { file << "Noise Polynom " << i << " ( degree: " << deg[i] << ")" << std::endl; file << "coefficients: "; for (unsigned int j = 0; j < coeffs[i].size(); j++) { file << coeffs[i][j] << " "; } file << std::endl; file << "Min validity range: " << mins[i] << std::endl; file << "Min validity range: " << maxs[i] << std::endl; file << "Reference point: " << ref[i] << std::endl; file << "Time UTC: " << time[i] << std::endl; } file << "Incidence Angles attributs: " << std::endl; IndexType centerIndexType = lImageMetadata->GetCenterIncidenceAngleIndex(); file << "GetCenterIncidenceAngle: Value: " << lImageMetadata->GetCenterIncidenceAngle(); file << " Index: Row: " << centerIndexType[0] << " Column: " << centerIndexType[1] << std::endl; file << "GetNumberOfCornerIncidenceAngles: " << lImageMetadata->GetNumberOfCornerIncidenceAngles() << std::endl; DoubleVectorType cornerIncidenceAngles = lImageMetadata->GetCornersIncidenceAngles(); std::vector<IndexType> tabIndex = lImageMetadata->GetCornersIncidenceAnglesIndex(); file << "GetCornerIncidenceAngles: " << std::endl; for (unsigned int i = 0; i < cornerIncidenceAngles.size(); i++) { file << "Incidence Angle " << i << ": Value: " << cornerIncidenceAngles[i] << " Index: Row: " << tabIndex[i][0] << " Column: " << tabIndex[i][1] << std::endl; } file << "GetMeanIncidenceAngles: " << lImageMetadata->GetMeanIncidenceAngles() << std::endl; file.close(); return EXIT_SUCCESS; } <commit_msg>TEST: remove unused code<commit_after><|endoftext|>
<commit_before>// © Copyright (c) 2018 SqYtCO #include "graphiccore.h" #include "core.h" #include "openglwidget.h" #include "hashlifesystem.h" #include <QFileDialog> #include <QMessageBox> #include <QStandardPaths> #include <QLabel> #ifdef ENABLE_CALC_TIME_MEASUREMENT #include <QDebug> #include <chrono> #endif GraphicConfiguration GraphicCore::gconfig; OpenGLWidget* GraphicCore::opengl; QLabel* GraphicCore::gen_counter; std::unique_ptr<std::thread> GraphicCore::stepping_thread; std::atomic_bool GraphicCore::stepping_stop; bool GraphicCore::stepping_block; std::unique_ptr<std::thread> GraphicCore::generating_thread; std::atomic_bool GraphicCore::generating_stop; std::unique_ptr<std::thread> GraphicCore::calc_thread; std::atomic_bool GraphicCore::calc_stop; std::mutex GraphicCore::system_mutex; void GraphicCore::init() { // get correct config path QString config_path = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); if(config_path[config_path.size() - 1] != '/') config_path.append('/'); // set config paths Core::get_config()->set_config_path(config_path.toStdString()); gconfig.set_config_path(config_path.toStdString()); // create new system with correct configuration Core::new_system(); stepping_stop = true; stepping_block = false; generating_stop = true; } void GraphicCore::init_gui(OpenGLWidget* opengl, QLabel* gen_counter) { GraphicCore::opengl = opengl; GraphicCore::gen_counter = gen_counter; gen_counter->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); gen_counter->setAlignment(Qt::AlignRight | Qt::AlignBottom); gen_counter->setWindowFlags(Qt::SubWindow); gen_counter->setForegroundRole(QPalette::BrightText); update_generation_counter(); } void GraphicCore::reset_cells(Cell_State state) { Core::reset_cells(state); update_generation_counter(); update_opengl(); } void GraphicCore::new_system() { stop_step(); stop_generating(); wait_for_calculation(); // generate new system and fill with random cells if it is set Core::new_system(); update_generation_counter(); update_opengl(); } void GraphicCore::reset_movement() { opengl->reset_movement(); } void GraphicCore::update_generation_counter() { gen_counter->setVisible(!gconfig.get_hide_generation_counter()); gen_counter->setFont(QFont("", static_cast<int>(get_config()->get_generation_counter_size()))); gen_counter->setText(QString::number(Core::get_generation())); } void GraphicCore::update_opengl() { opengl->update(); } void GraphicCore::read_save() { QString selected_filter("Game of Life(*.gol)"); Core::load(QFileDialog::getOpenFileName(nullptr, QFileDialog::tr("Select a file to open..."), Core::get_config()->get_save_path().c_str(), QFileDialog::tr("All Files(*);;Game of Life(*.gol)"), &selected_filter).toStdString()); update_opengl(); update_generation_counter(); } void GraphicCore::write_save_as() { // ask for file name QString selected_filter("Game of Life(*.gol)"); QString file_name = QFileDialog::getSaveFileName(nullptr, QFileDialog::tr("Choose a file name to save..."), Core::get_config()->get_save_path().c_str(), QFileDialog::tr("All Files(*);;Game of Life(*.gol)"), &selected_filter); // return if no file name was entered if(file_name.isEmpty()) return; // write save; warning if writing fails if(!Core::save(file_name.toStdString())) QMessageBox::warning(nullptr, QMessageBox::tr("Write Error"), QMessageBox::tr("Writing Save Failed!\nPlease Check Your Permissions.")); } void GraphicCore::write_save() { // write save; warning if writing fails if(!Core::save()) QMessageBox::warning(nullptr, QMessageBox::tr("Write Error"), QMessageBox::tr("Writing Save Failed!\nPlease Check Your Permissions.")); } void GraphicCore::next_generations(std::size_t generations) { while(generations) { if(stepping_stop) break; else { system_mutex.lock(); generations -= Core::next_generation(generations); system_mutex.unlock(); } } stepping_stop = true; // send signals to main thread (update GUI) emit opengl->cell_changed(); emit opengl->start_update(); } void GraphicCore::step() { wait_for_calculation(); // stop last step stop_step(); // if thread is not blocked, start new step if(!stepping_block) { stepping_stop = false; stepping_thread.reset(new std::thread(next_generations, gconfig.get_generations_per_step())); } } void GraphicCore::stop_step() { stepping_stop = true; if(stepping_thread) { stepping_thread->join(); stepping_thread.reset(nullptr); } } void GraphicCore::start_generating() { if(generating_running()) return; wait_for_calculation(); stop_step(); stepping_block = true; if(generating_thread) generating_thread->join(); generating_stop = false; generating_thread.reset(new std::thread([&]() { while(!generating_stop) { std::this_thread::sleep_for(std::chrono::milliseconds(gconfig.get_delay())); system_mutex.lock(); #ifdef ENABLE_CALC_TIME_MEASUREMENT auto begin = std::chrono::high_resolution_clock::now(); #endif Core::next_generation(); #ifdef ENABLE_CALC_TIME_MEASUREMENT auto end = std::chrono::high_resolution_clock::now(); qDebug() << "calculating: " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << "µs"; #endif system_mutex.unlock(); emit opengl->cell_changed(); emit opengl->start_update(); } })); emit opengl->generating_start_stop(); } void GraphicCore::stop_generating() { if(generating_stop) return; generating_stop = true; if(generating_thread) generating_thread->join(); generating_thread.reset(nullptr); stepping_block = false; emit opengl->generating_start_stop(); } void GraphicCore::calc_next_generation() { if(generating_running()) return; wait_for_calculation(); calc_thread.reset(new std::thread([]() { system_mutex.lock(); Core::calc_next_generation(gconfig.get_generations_per_step()); system_mutex.unlock(); emit opengl->start_update(); })); } void GraphicCore::wait_for_calculation() { if(calc_thread) { calc_thread->join(); calc_thread.reset(nullptr); } } <commit_msg>lock_guard instead of manual mutex locking<commit_after>// © Copyright (c) 2018 SqYtCO #include "graphiccore.h" #include "core.h" #include "openglwidget.h" #include "hashlifesystem.h" #include <QFileDialog> #include <QMessageBox> #include <QStandardPaths> #include <QLabel> #ifdef ENABLE_CALC_TIME_MEASUREMENT #include <QDebug> #include <chrono> #endif GraphicConfiguration GraphicCore::gconfig; OpenGLWidget* GraphicCore::opengl; QLabel* GraphicCore::gen_counter; std::unique_ptr<std::thread> GraphicCore::stepping_thread; std::atomic_bool GraphicCore::stepping_stop; bool GraphicCore::stepping_block; std::unique_ptr<std::thread> GraphicCore::generating_thread; std::atomic_bool GraphicCore::generating_stop; std::unique_ptr<std::thread> GraphicCore::calc_thread; std::atomic_bool GraphicCore::calc_stop; std::mutex GraphicCore::system_mutex; void GraphicCore::init() { // get correct config path QString config_path = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); if(config_path[config_path.size() - 1] != '/') config_path.append('/'); // set config paths Core::get_config()->set_config_path(config_path.toStdString()); gconfig.set_config_path(config_path.toStdString()); // create new system with correct configuration Core::new_system(); stepping_stop = true; stepping_block = false; generating_stop = true; } void GraphicCore::init_gui(OpenGLWidget* opengl, QLabel* gen_counter) { GraphicCore::opengl = opengl; GraphicCore::gen_counter = gen_counter; gen_counter->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); gen_counter->setAlignment(Qt::AlignRight | Qt::AlignBottom); gen_counter->setWindowFlags(Qt::SubWindow); gen_counter->setForegroundRole(QPalette::BrightText); update_generation_counter(); } void GraphicCore::reset_cells(Cell_State state) { Core::reset_cells(state); update_generation_counter(); update_opengl(); } void GraphicCore::new_system() { stop_step(); stop_generating(); wait_for_calculation(); // generate new system and fill with random cells if it is set Core::new_system(); update_generation_counter(); update_opengl(); } void GraphicCore::reset_movement() { opengl->reset_movement(); } void GraphicCore::update_generation_counter() { gen_counter->setVisible(!gconfig.get_hide_generation_counter()); gen_counter->setFont(QFont("", static_cast<int>(get_config()->get_generation_counter_size()))); gen_counter->setText(QString::number(Core::get_generation())); } void GraphicCore::update_opengl() { opengl->update(); } void GraphicCore::read_save() { QString selected_filter("Game of Life(*.gol)"); Core::load(QFileDialog::getOpenFileName(nullptr, QFileDialog::tr("Select a file to open..."), Core::get_config()->get_save_path().c_str(), QFileDialog::tr("All Files(*);;Game of Life(*.gol)"), &selected_filter).toStdString()); update_opengl(); update_generation_counter(); } void GraphicCore::write_save_as() { // ask for file name QString selected_filter("Game of Life(*.gol)"); QString file_name = QFileDialog::getSaveFileName(nullptr, QFileDialog::tr("Choose a file name to save..."), Core::get_config()->get_save_path().c_str(), QFileDialog::tr("All Files(*);;Game of Life(*.gol)"), &selected_filter); // return if no file name was entered if(file_name.isEmpty()) return; // write save; warning if writing fails if(!Core::save(file_name.toStdString())) QMessageBox::warning(nullptr, QMessageBox::tr("Write Error"), QMessageBox::tr("Writing Save Failed!\nPlease Check Your Permissions.")); } void GraphicCore::write_save() { // write save; warning if writing fails if(!Core::save()) QMessageBox::warning(nullptr, QMessageBox::tr("Write Error"), QMessageBox::tr("Writing Save Failed!\nPlease Check Your Permissions.")); } void GraphicCore::next_generations(std::size_t generations) { while(generations) { if(stepping_stop) break; else { { std::lock_guard<decltype(system_mutex)> lock(system_mutex); generations -= Core::next_generation(generations); } } } stepping_stop = true; // send signals to main thread (update GUI) emit opengl->cell_changed(); emit opengl->start_update(); } void GraphicCore::step() { wait_for_calculation(); // stop last step stop_step(); // if thread is not blocked, start new step if(!stepping_block) { stepping_stop = false; stepping_thread.reset(new std::thread(next_generations, gconfig.get_generations_per_step())); } } void GraphicCore::stop_step() { stepping_stop = true; if(stepping_thread) { stepping_thread->join(); stepping_thread.reset(nullptr); } } void GraphicCore::start_generating() { if(generating_running()) return; wait_for_calculation(); stop_step(); stepping_block = true; if(generating_thread) generating_thread->join(); generating_stop = false; generating_thread.reset(new std::thread([&]() { while(!generating_stop) { std::this_thread::sleep_for(std::chrono::milliseconds(gconfig.get_delay())); #ifdef ENABLE_CALC_TIME_MEASUREMENT auto begin = std::chrono::high_resolution_clock::now(); #endif { std::lock_guard<decltype(system_mutex)> lock(system_mutex); Core::next_generation(); } #ifdef ENABLE_CALC_TIME_MEASUREMENT auto end = std::chrono::high_resolution_clock::now(); qDebug() << "calculating: " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << "µs"; #endif emit opengl->cell_changed(); emit opengl->start_update(); } })); emit opengl->generating_start_stop(); } void GraphicCore::stop_generating() { if(generating_stop) return; generating_stop = true; if(generating_thread) generating_thread->join(); generating_thread.reset(nullptr); stepping_block = false; emit opengl->generating_start_stop(); } void GraphicCore::calc_next_generation() { if(generating_running()) return; wait_for_calculation(); calc_thread.reset(new std::thread([]() { { std::lock_guard<decltype(system_mutex)> lock(system_mutex); Core::calc_next_generation(gconfig.get_generations_per_step()); } emit opengl->start_update(); })); } void GraphicCore::wait_for_calculation() { if(calc_thread) { calc_thread->join(); calc_thread.reset(nullptr); } } <|endoftext|>
<commit_before>/** * For conditions of distribution and use, see copyright notice in license.txt * * @file VoiceTransmissionModeWidget.cpp * @brief Widget for in-wolrd voice transmission mode selection * */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "VoiceTransmissionModeWidget.h" #include "CommunicationsService.h" #include "QSettings.h" #include "DebugOperatorNew.h" namespace CommUI { VoiceTransmissionModeWidget::VoiceTransmissionModeWidget(int initial_mode) : QWidget(0) { setupUi(this); switch(initial_mode) { case 0: offButton->setChecked(true); break; case 1: continousTransmissionButton->setChecked(true); break; case 2: pushToTalkButton->setChecked(true); break; case 3: toggleModeButton->setChecked(true); break; } connect(offButton, SIGNAL(clicked()), this, SLOT(DefineTransmissionMode())); connect(continousTransmissionButton, SIGNAL(clicked()), this, SLOT(DefineTransmissionMode())); connect(pushToTalkButton, SIGNAL(clicked()), this, SLOT(DefineTransmissionMode())); connect(toggleModeButton, SIGNAL(clicked()), this, SLOT(DefineTransmissionMode())); } void VoiceTransmissionModeWidget::DefineTransmissionMode() { if (offButton->isChecked()) emit TransmissionModeSelected(0); if (continousTransmissionButton->isChecked()) emit TransmissionModeSelected(1); if (pushToTalkButton->isChecked()) emit TransmissionModeSelected(2); if (toggleModeButton->isChecked()) emit TransmissionModeSelected(3); hide(); } } // CommUI <commit_msg>Fix linux build.<commit_after>/** * For conditions of distribution and use, see copyright notice in license.txt * * @file VoiceTransmissionModeWidget.cpp * @brief Widget for in-wolrd voice transmission mode selection * */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "VoiceTransmissionModeWidget.h" #include "CommunicationsService.h" #include <QSettings.h> #include "DebugOperatorNew.h" namespace CommUI { VoiceTransmissionModeWidget::VoiceTransmissionModeWidget(int initial_mode) : QWidget(0) { setupUi(this); switch(initial_mode) { case 0: offButton->setChecked(true); break; case 1: continousTransmissionButton->setChecked(true); break; case 2: pushToTalkButton->setChecked(true); break; case 3: toggleModeButton->setChecked(true); break; } connect(offButton, SIGNAL(clicked()), this, SLOT(DefineTransmissionMode())); connect(continousTransmissionButton, SIGNAL(clicked()), this, SLOT(DefineTransmissionMode())); connect(pushToTalkButton, SIGNAL(clicked()), this, SLOT(DefineTransmissionMode())); connect(toggleModeButton, SIGNAL(clicked()), this, SLOT(DefineTransmissionMode())); } void VoiceTransmissionModeWidget::DefineTransmissionMode() { if (offButton->isChecked()) emit TransmissionModeSelected(0); if (continousTransmissionButton->isChecked()) emit TransmissionModeSelected(1); if (pushToTalkButton->isChecked()) emit TransmissionModeSelected(2); if (toggleModeButton->isChecked()) emit TransmissionModeSelected(3); hide(); } } // CommUI <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: jvmargs.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 15:29:34 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER 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 __JVM #define __JVM #if STLPORT_VERSION < 321 #include <tools/presys.h> #include <vector.h> #include <tools/postsys.h> #else #include <cstdarg> #include <stl/vector> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #include "jni.h" using namespace ::rtl; #ifndef JNI_VERSION_1_2 #define JNI_VERSION_1_1 0x00010001 #define JNI_VERSION_1_2 0x00010002 #define JNI_EDETACHED (-2) /* thread detached from the VM */ #define JNI_EVERSION (-3) /* JNI version error */ #define JNI_ENOMEM (-4) /* not enough memory */ #define JNI_EEXIST (-5) /* VM already created */ #define JNI_EINVAL (-6) /* invalid arguments */ struct JNIInvokeInterface12_; struct JavaVM12_; typedef JavaVM12_ JavaVM12; #define JAVAVM JavaVM12 struct JNIInvokeInterface12_ { void *reserved0; void *reserved1; void *reserved2; jint (JNICALL *DestroyJavaVM)(JavaVM12 *vm); jint (JNICALL *AttachCurrentThread)(JavaVM12 *vm, void **penv, void *args); jint (JNICALL *DetachCurrentThread)(JavaVM12 *vm); jint (JNICALL *GetEnv)(JavaVM12 *vm, void **penv, jint version); }; struct JavaVM12_ { const struct JNIInvokeInterface12_ *functions; jint DestroyJavaVM() { return functions->DestroyJavaVM(this); } jint AttachCurrentThread(void **penv, void *args) { return functions->AttachCurrentThread(this, penv, args); } jint DetachCurrentThread() { return functions->DetachCurrentThread(this); } jint GetEnv(void **penv, jint version) { return functions->GetEnv(this, penv, version); } }; typedef struct JavaVMOption { char *optionString; void *extraInfo; } JavaVMOption; typedef struct JavaVMInitArgs { jint version; jint nOptions; JavaVMOption *options; jboolean ignoreUnrecognized; } JavaVMInitArgs; typedef struct JavaVMAttachArgs { jint version; char *name; jobject group; } JavaVMAttachArgs; #else #define JAVAVM JavaVM #endif typedef jint (JNICALL *JNIvfprintf)(FILE *fp, const char *format, va_list args); typedef void (JNICALL *JNIexit)(jint code); typedef void (JNICALL *JNIabort)(void); extern "C" { #ifdef OS2 typedef jint JNICALL0 JNI_InitArgs_Type(void *); typedef jint JNICALL0 JNI_CreateVM_Type(JAVAVM **, JNIEnv **, void *); #else typedef jint JNICALL JNI_InitArgs_Type(void *); typedef jint JNICALL JNI_CreateVM_Type(JAVAVM **, JNIEnv **, void *); #endif } class JVM { ::std::vector<JavaVMOption> p_props; JavaVMInitArgs javaVMInitArgs; JDK1_1InitArgs jDK1_1InitArgs; ::std::vector<OUString> props; sal_Bool debug; jint jiDebugPort; OUString usCompiler; protected: void pushPProp(OUString uString, void * extraInfo = NULL); public: JVM(JNI_InitArgs_Type * pVMInitArgs) ; ~JVM() ; void pushProp(const OUString & uString); void disableAsyncGC(jboolean jbFlag); void enableClassGC(jboolean jbFlag); void enableVerboseGC(jboolean jbFlag); void verbose(jboolean jbFlag); void setCompiler(const OUString & usCompiler); void nativeStackSize(jint jiSize); void javaStackSize(jint jiSize); void verifyMode(OUString uStr); void minHeapSize(jint jiSize); void maxHeapSize(jint jiSize); void setDebug(sal_Bool flag); void setDebugPort(jint jiDebugPort); void classPath(OString str); void vfprintf(JNIvfprintf vfprintf); void exit(JNIexit exit); void abort(JNIabort abort); sal_Bool getDebug(); OUString getCompiler(); const JavaVMInitArgs * getJavaVMInitArgs(); const JDK1_1InitArgs * getJDK1_1InitArgs(); }; #endif <commit_msg>cleaned<commit_after>/************************************************************************* * * $RCSfile: jvmargs.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: kr $ $Date: 2000-09-28 17:35:43 $ * * 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 __JVM_HXX #define __JVM_HXX #include <cstdarg> #include <stl/vector> #include <rtl/ustring> #include "jni.h" typedef jint (JNICALL *JNIvfprintf)(FILE *fp, const char *format, va_list args); typedef void (JNICALL *JNIexit)(jint code); typedef void (JNICALL *JNIabort)(void); extern "C" { typedef jint JNICALL JNI_InitArgs_Type(void *); typedef jint JNICALL JNI_CreateVM_Type(JavaVM **, JNIEnv **, void *); } namespace stoc_javavm { class JVM { ::std::vector<rtl::OUString> _props; ::rtl::OUString _runtimeLib; ::rtl::OUString _systemClasspath; ::rtl::OUString _userClasspath; sal_Bool _enabled; sal_Bool _is_debugPort; jint _debugPort; sal_Bool _is_disableAsyncGC; jint _disableAsyncGC; sal_Bool _is_enableClassGC; jint _enableClassGC; sal_Bool _is_enableVerboseGC; jint _enableVerboseGC; sal_Bool _is_checkSource; jint _checkSource; sal_Bool _is_nativeStackSize; jint _nativeStackSize; sal_Bool _is_javaStackSize; jint _javaStackSize; sal_Bool _is_minHeapSize; jint _minHeapSize; sal_Bool _is_maxHeapSize; jint _maxHeapSize; sal_Bool _is_verifyMode; jint _verifyMode; sal_Bool _is_print; JNIvfprintf _print; sal_Bool _is_exit; JNIexit _exit; sal_Bool _is_abort; JNIabort _abort; public: JVM() throw(); void pushProp(const ::rtl::OUString & uString) throw(); void setEnabled(sal_Bool sbFlag) throw(); void setDisableAsyncGC(jint jiFlag) throw(); void setEnableClassGC(jint jiFlag) throw(); void setEnableVerboseGC(jint jiFlag) throw(); void setCheckSource(jint jiFlag) throw(); void setNativeStackSize(jint jiSize) throw(); void setJavaStackSize(jint jiSize) throw(); void setVerifyMode(const ::rtl::OUString & mode) throw(); void setMinHeapSize(jint jiSize) throw(); void setMaxHeapSize(jint jiSize) throw(); void setDebugPort(jint jiDebugPort) throw(); void setSystemClasspath(const ::rtl::OUString & str) throw(); void setUserClasspath(const ::rtl::OUString & str) throw(); void setPrint(JNIvfprintf vfprintf) throw(); void setExit(JNIexit exit) throw(); void setAbort(JNIabort abort) throw(); void setRuntimeLib(const ::rtl::OUString & libName) throw(); void setArgs(JDK1_1InitArgs * pargs) const throw(); const ::rtl::OUString & getRuntimeLib() const throw(); sal_Bool isEnabled() const throw(); }; } #endif <|endoftext|>
<commit_before>#ifndef JEZUK_SAX2DOM_PARSER_H #define JEZUK_SAX2DOM_PARSER_H #include <SAX/XMLReader.hpp> #include <SAX/helpers/DefaultHandler.hpp> #include <SAX/helpers/AttributeTypes.hpp> #include <DOM/Simple/DOMImplementation.hpp> #include <DOM/Simple/NotationImpl.hpp> #include <DOM/Simple/EntityImpl.hpp> #include <DOM/Document.hpp> #include <DOM/DOMException.hpp> #include <DOM/SAX2DOM/DocumentTypeImpl.hpp> #include <map> #include <SAX/helpers/FeatureNames.hpp> #include <SAX/helpers/PropertyNames.hpp> #include <SAX/SAXParseException.hpp> namespace Arabica { namespace SAX2DOM { template<class stringT, class string_adaptorT = Arabica::default_string_adaptor<stringT>, class SAX_parser = Arabica::SAX::XMLReader<stringT, string_adaptorT> > class Parser : protected Arabica::SAX::DefaultHandler<stringT, string_adaptorT> { typedef Arabica::SAX::Attributes<stringT, string_adaptorT> AttributesT; typedef Arabica::SAX::EntityResolver<stringT, string_adaptorT> EntityResolverT; typedef Arabica::SAX::ErrorHandler<stringT, string_adaptorT> ErrorHandlerT; typedef Arabica::SAX::LexicalHandler<stringT, string_adaptorT> LexicalHandlerT; typedef Arabica::SAX::DeclHandler<stringT, string_adaptorT> DeclHandlerT; typedef Arabica::SAX::InputSource<stringT, string_adaptorT> InputSourceT; typedef Arabica::SimpleDOM::EntityImpl<stringT, string_adaptorT> EntityT; typedef Arabica::SimpleDOM::NotationImpl<stringT, string_adaptorT> NotationT; typedef Arabica::SimpleDOM::ElementImpl<stringT, string_adaptorT> ElementT; typedef typename ErrorHandlerT::SAXParseExceptionT SAXParseExceptionT; public: Parser() : entityResolver_(0), errorHandler_(0), documentType_(0) { Arabica::SAX::FeatureNames<stringT, string_adaptorT> fNames; features_.insert(std::make_pair(fNames.namespaces, true)); features_.insert(std::make_pair(fNames.namespace_prefixes, true)); features_.insert(std::make_pair(fNames.validation, false)); } // Parser void setEntityResolver(EntityResolverT& resolver) { entityResolver_ = &resolver; } EntityResolverT* getEntityResolver() const { return entityResolver_; } void setErrorHandler(ErrorHandlerT& handler) { errorHandler_ = &handler; } ErrorHandlerT* getErrorHandler() const { return errorHandler_; } void setFeature(const stringT& name, bool value) { typename Features::iterator f = features_.find(name); if(f == features_.end()) features_.insert(std::make_pair(name, value)); else f->second = value; } // setFeature bool getFeature(const stringT& name) const { typename Features::const_iterator f = features_.find(name); if(f == features_.end()) throw Arabica::SAX::SAXNotRecognizedException(std::string("Feature not recognized ") + string_adaptorT::asStdString(name)); return f->second; } // getFeature bool parse(const stringT& systemId) { InputSourceT is(systemId); return parse(is); } // loadDOM bool parse(InputSourceT& source) { Arabica::SAX::PropertyNames<stringT, string_adaptorT> pNames; DOM::DOMImplementation<stringT, string_adaptorT> di = Arabica::SimpleDOM::DOMImplementation<stringT, string_adaptorT>::getDOMImplementation(); document_ = di.createDocument(string_adaptorT::construct_from_utf8(""), string_adaptorT::construct_from_utf8(""), 0); currentNode_ = document_; inCDATA_ = false; inDTD_ = false; inEntity_ = 0; SAX_parser parser; parser.setContentHandler(*this); parser.setErrorHandler(*this); if(entityResolver_) parser.setEntityResolver(*entityResolver_); parser.setLexicalHandler(*this); parser.setDeclHandler(*this); setParserFeatures(parser); try { parser.parse(source); } catch(const DOM::DOMException& de) { document_ = 0; if(errorHandler_) { SAXParseExceptionT pe(de.what()); errorHandler_->fatalError(pe); } // if ... } // catch return (document_ != 0); } // loadDOM DOM::Document<stringT, string_adaptorT> getDocument() const { return document_; } // getDocument void reset() { currentNode_ = 0; document_ = 0; } // reset protected: DOM::Node<stringT, string_adaptorT>& currentNode() { return currentNode_; } private: // no implementations Parser(const Parser&); bool operator==(const Parser&) const; Parser& operator=(const Parser&); // instance variables DOM::Document<stringT, string_adaptorT> document_; DocumentType<stringT, string_adaptorT >* documentType_; DOM::Node<stringT, string_adaptorT> currentNode_; DOM::Node<stringT, string_adaptorT> cachedCurrent_; typedef std::map<stringT, bool> Features; Features features_; bool inCDATA_; bool inDTD_; int inEntity_; std::map<stringT, EntityT*> declaredEntities_; EntityResolverT* entityResolver_; ErrorHandlerT* errorHandler_; Arabica::SAX::AttributeTypes<stringT, string_adaptorT> attributeTypes_; protected: void setParserFeatures(SAX_parser& parser) const { for(typename Features::const_iterator f = features_.begin(), e = features_.end(); f != e; ++f) try { parser.setFeature(f->first, f->second); } catch(const Arabica::SAX::SAXException&) { } } // setParserFeatures /////////////////////////////////////////////////////////// // ContentHandler virtual void endDocument() { currentNode_ = 0; } // endDocument virtual void startElement(const stringT& namespaceURI, const stringT& localName, const stringT& qName, const AttributesT& atts) { if(currentNode_ == 0) return; try { DOM::Element<stringT, string_adaptorT> elem = document_.createElementNS(namespaceURI, qName); currentNode_.appendChild(elem); // attributes here for(int i = 0; i < atts.getLength(); ++i) { stringT qName = atts.getQName(i); if(string_adaptorT::empty(qName)) qName = atts.getLocalName(i); elem.setAttributeNS(atts.getURI(i), qName, atts.getValue(i)); } currentNode_ = elem; } catch(const DOM::DOMException& de) { reset(); if(errorHandler_) { SAXParseExceptionT pe(de.what()); errorHandler_->fatalError(pe); } // if ... } // catch } // startElement virtual void endElement(const stringT& namespaceURI, const stringT& localName, const stringT& qName) { if(currentNode_ == 0) return; currentNode_ = currentNode_.getParentNode(); } // endElement virtual void characters(const stringT& ch) { if(currentNode_ == 0) return; if(!inCDATA_) currentNode_.appendChild(document_.createTextNode(ch)); else currentNode_.appendChild(document_.createCDATASection(ch)); } // characters virtual void processingInstruction(const stringT& target, const stringT& data) { if(currentNode_ == 0) return; currentNode_.appendChild(document_.createProcessingInstruction(target, data)); } // processingInstruction virtual void skippedEntity(const stringT& name) { if(currentNode_ == 0 || inDTD_ == true) return; currentNode_.appendChild(document_.createEntityReference(name)); } // skippedEntity //////////////////////////////////////////////////// // ErrorHandler virtual void warning(const SAXParseExceptionT& e) { if(errorHandler_) errorHandler_->warning(e); } // warning virtual void error(const SAXParseExceptionT& e) { if(errorHandler_) errorHandler_->error(e); reset(); } // error virtual void fatalError(const SAXParseExceptionT& e) { if(errorHandler_) errorHandler_->fatalError(e); reset(); } // fatalError ///////////////////////////////////////////////////// // LexicalHandler virtual void startDTD(const stringT& name, const stringT& publicId, const stringT& systemId) { documentType_ = new DocumentType<stringT, string_adaptorT >(name, publicId, systemId); document_.insertBefore(documentType_, 0); inDTD_ = true; } // startDTD virtual void endDTD() { documentType_->setReadOnly(true); inDTD_ = false; } // endDTD virtual void startEntity(const stringT& name) { if(currentNode_ == 0) return; if(++inEntity_ == 1) { cachedCurrent_ = currentNode_; currentNode_ = declaredEntities_[name]; if(currentNode_ != 0 && currentNode_.hasChildNodes() == true) // already populated currentNode_ = 0; } } // startEntity virtual void endEntity(const stringT& name) { if(--inEntity_ == 0) currentNode_ = cachedCurrent_; currentNode_.appendChild(document_.createEntityReference(name)); } // endEntity virtual void startCDATA() { inCDATA_ = true; } // startCDATA virtual void endCDATA() { inCDATA_ = false; } // endCDATA virtual void comment(const stringT& text) { if(currentNode_ == 0) return; currentNode_.appendChild(document_.createComment(text)); } // comment ////////////////////////////////////////////////////////////////////// // DeclHandler virtual void elementDecl(const stringT& name, const stringT& model) { if(!documentType_) return; documentType_->addElement(name); } // elementDecl virtual void attributeDecl(const stringT& elementName, const stringT& attributeName, const stringT& type, const stringT& valueDefault, const stringT& value) { if(!documentType_) return; if(!string_adaptorT::empty(value)) documentType_->addDefaultAttr(elementName, attributeName, value); if(type == attributeTypes_.id) documentType_->addElementId(attributeName); } // attributeDecl virtual void internalEntityDecl(const stringT& name, const stringT& value) { if(!documentType_) return; EntityT* entity = new EntityT(0, name, string_adaptorT::construct_from_utf8(""), string_adaptorT::construct_from_utf8(""), string_adaptorT::construct_from_utf8("")); declaredEntities_.insert(std::make_pair(name, entity)); documentType_->addEntity(entity); DOM::Node<stringT, string_adaptorT> n = entity; n.appendChild(document_.createTextNode(value)); } // internalEntityDecl virtual void externalEntityDecl(const stringT& name, const stringT& publicId, const stringT& systemId) { if(!documentType_) return; EntityT* entity = new EntityT(0, name, publicId, systemId, string_adaptorT::construct_from_utf8("")); declaredEntities_.insert(std::make_pair(name, entity)); // we'll populate it later documentType_->addEntity(entity); } // externalEntityDecl ///////////////////////////////////////////////////////////////////////// // DTDHandler virtual void notationDecl(const stringT& name, const stringT& publicId, const stringT& systemId) { if(!documentType_) return; documentType_->addNotation(new NotationT(0, name, publicId, systemId)); } // notationDecl virtual void unparsedEntityDecl(const stringT& name, const stringT& publicId, const stringT& systemId, const stringT& notationName) { if(!documentType_) return; documentType_->addEntity(new EntityT(0, name, publicId, systemId, notationName)); } // unparsedEntityDecl }; // class Parser } // namespace SAX2DOM } // namespace Arabica #endif <commit_msg>Alex Ott's patch to kill an initialisation order warning<commit_after>#ifndef JEZUK_SAX2DOM_PARSER_H #define JEZUK_SAX2DOM_PARSER_H #include <SAX/XMLReader.hpp> #include <SAX/helpers/DefaultHandler.hpp> #include <SAX/helpers/AttributeTypes.hpp> #include <DOM/Simple/DOMImplementation.hpp> #include <DOM/Simple/NotationImpl.hpp> #include <DOM/Simple/EntityImpl.hpp> #include <DOM/Document.hpp> #include <DOM/DOMException.hpp> #include <DOM/SAX2DOM/DocumentTypeImpl.hpp> #include <map> #include <SAX/helpers/FeatureNames.hpp> #include <SAX/helpers/PropertyNames.hpp> #include <SAX/SAXParseException.hpp> namespace Arabica { namespace SAX2DOM { template<class stringT, class string_adaptorT = Arabica::default_string_adaptor<stringT>, class SAX_parser = Arabica::SAX::XMLReader<stringT, string_adaptorT> > class Parser : protected Arabica::SAX::DefaultHandler<stringT, string_adaptorT> { typedef Arabica::SAX::Attributes<stringT, string_adaptorT> AttributesT; typedef Arabica::SAX::EntityResolver<stringT, string_adaptorT> EntityResolverT; typedef Arabica::SAX::ErrorHandler<stringT, string_adaptorT> ErrorHandlerT; typedef Arabica::SAX::LexicalHandler<stringT, string_adaptorT> LexicalHandlerT; typedef Arabica::SAX::DeclHandler<stringT, string_adaptorT> DeclHandlerT; typedef Arabica::SAX::InputSource<stringT, string_adaptorT> InputSourceT; typedef Arabica::SimpleDOM::EntityImpl<stringT, string_adaptorT> EntityT; typedef Arabica::SimpleDOM::NotationImpl<stringT, string_adaptorT> NotationT; typedef Arabica::SimpleDOM::ElementImpl<stringT, string_adaptorT> ElementT; typedef typename ErrorHandlerT::SAXParseExceptionT SAXParseExceptionT; public: Parser() : documentType_(0), entityResolver_(0), errorHandler_(0) { Arabica::SAX::FeatureNames<stringT, string_adaptorT> fNames; features_.insert(std::make_pair(fNames.namespaces, true)); features_.insert(std::make_pair(fNames.namespace_prefixes, true)); features_.insert(std::make_pair(fNames.validation, false)); } // Parser void setEntityResolver(EntityResolverT& resolver) { entityResolver_ = &resolver; } EntityResolverT* getEntityResolver() const { return entityResolver_; } void setErrorHandler(ErrorHandlerT& handler) { errorHandler_ = &handler; } ErrorHandlerT* getErrorHandler() const { return errorHandler_; } void setFeature(const stringT& name, bool value) { typename Features::iterator f = features_.find(name); if(f == features_.end()) features_.insert(std::make_pair(name, value)); else f->second = value; } // setFeature bool getFeature(const stringT& name) const { typename Features::const_iterator f = features_.find(name); if(f == features_.end()) throw Arabica::SAX::SAXNotRecognizedException(std::string("Feature not recognized ") + string_adaptorT::asStdString(name)); return f->second; } // getFeature bool parse(const stringT& systemId) { InputSourceT is(systemId); return parse(is); } // loadDOM bool parse(InputSourceT& source) { Arabica::SAX::PropertyNames<stringT, string_adaptorT> pNames; DOM::DOMImplementation<stringT, string_adaptorT> di = Arabica::SimpleDOM::DOMImplementation<stringT, string_adaptorT>::getDOMImplementation(); document_ = di.createDocument(string_adaptorT::construct_from_utf8(""), string_adaptorT::construct_from_utf8(""), 0); currentNode_ = document_; inCDATA_ = false; inDTD_ = false; inEntity_ = 0; SAX_parser parser; parser.setContentHandler(*this); parser.setErrorHandler(*this); if(entityResolver_) parser.setEntityResolver(*entityResolver_); parser.setLexicalHandler(*this); parser.setDeclHandler(*this); setParserFeatures(parser); try { parser.parse(source); } catch(const DOM::DOMException& de) { document_ = 0; if(errorHandler_) { SAXParseExceptionT pe(de.what()); errorHandler_->fatalError(pe); } // if ... } // catch return (document_ != 0); } // loadDOM DOM::Document<stringT, string_adaptorT> getDocument() const { return document_; } // getDocument void reset() { currentNode_ = 0; document_ = 0; } // reset protected: DOM::Node<stringT, string_adaptorT>& currentNode() { return currentNode_; } private: // no implementations Parser(const Parser&); bool operator==(const Parser&) const; Parser& operator=(const Parser&); // instance variables DOM::Document<stringT, string_adaptorT> document_; DocumentType<stringT, string_adaptorT >* documentType_; DOM::Node<stringT, string_adaptorT> currentNode_; DOM::Node<stringT, string_adaptorT> cachedCurrent_; typedef std::map<stringT, bool> Features; Features features_; bool inCDATA_; bool inDTD_; int inEntity_; std::map<stringT, EntityT*> declaredEntities_; EntityResolverT* entityResolver_; ErrorHandlerT* errorHandler_; Arabica::SAX::AttributeTypes<stringT, string_adaptorT> attributeTypes_; protected: void setParserFeatures(SAX_parser& parser) const { for(typename Features::const_iterator f = features_.begin(), e = features_.end(); f != e; ++f) try { parser.setFeature(f->first, f->second); } catch(const Arabica::SAX::SAXException&) { } } // setParserFeatures /////////////////////////////////////////////////////////// // ContentHandler virtual void endDocument() { currentNode_ = 0; } // endDocument virtual void startElement(const stringT& namespaceURI, const stringT& localName, const stringT& qName, const AttributesT& atts) { if(currentNode_ == 0) return; try { DOM::Element<stringT, string_adaptorT> elem = document_.createElementNS(namespaceURI, qName); currentNode_.appendChild(elem); // attributes here for(int i = 0; i < atts.getLength(); ++i) { stringT qName = atts.getQName(i); if(string_adaptorT::empty(qName)) qName = atts.getLocalName(i); elem.setAttributeNS(atts.getURI(i), qName, atts.getValue(i)); } currentNode_ = elem; } catch(const DOM::DOMException& de) { reset(); if(errorHandler_) { SAXParseExceptionT pe(de.what()); errorHandler_->fatalError(pe); } // if ... } // catch } // startElement virtual void endElement(const stringT& namespaceURI, const stringT& localName, const stringT& qName) { if(currentNode_ == 0) return; currentNode_ = currentNode_.getParentNode(); } // endElement virtual void characters(const stringT& ch) { if(currentNode_ == 0) return; if(!inCDATA_) currentNode_.appendChild(document_.createTextNode(ch)); else currentNode_.appendChild(document_.createCDATASection(ch)); } // characters virtual void processingInstruction(const stringT& target, const stringT& data) { if(currentNode_ == 0) return; currentNode_.appendChild(document_.createProcessingInstruction(target, data)); } // processingInstruction virtual void skippedEntity(const stringT& name) { if(currentNode_ == 0 || inDTD_ == true) return; currentNode_.appendChild(document_.createEntityReference(name)); } // skippedEntity //////////////////////////////////////////////////// // ErrorHandler virtual void warning(const SAXParseExceptionT& e) { if(errorHandler_) errorHandler_->warning(e); } // warning virtual void error(const SAXParseExceptionT& e) { if(errorHandler_) errorHandler_->error(e); reset(); } // error virtual void fatalError(const SAXParseExceptionT& e) { if(errorHandler_) errorHandler_->fatalError(e); reset(); } // fatalError ///////////////////////////////////////////////////// // LexicalHandler virtual void startDTD(const stringT& name, const stringT& publicId, const stringT& systemId) { documentType_ = new DocumentType<stringT, string_adaptorT >(name, publicId, systemId); document_.insertBefore(documentType_, 0); inDTD_ = true; } // startDTD virtual void endDTD() { documentType_->setReadOnly(true); inDTD_ = false; } // endDTD virtual void startEntity(const stringT& name) { if(currentNode_ == 0) return; if(++inEntity_ == 1) { cachedCurrent_ = currentNode_; currentNode_ = declaredEntities_[name]; if(currentNode_ != 0 && currentNode_.hasChildNodes() == true) // already populated currentNode_ = 0; } } // startEntity virtual void endEntity(const stringT& name) { if(--inEntity_ == 0) currentNode_ = cachedCurrent_; currentNode_.appendChild(document_.createEntityReference(name)); } // endEntity virtual void startCDATA() { inCDATA_ = true; } // startCDATA virtual void endCDATA() { inCDATA_ = false; } // endCDATA virtual void comment(const stringT& text) { if(currentNode_ == 0) return; currentNode_.appendChild(document_.createComment(text)); } // comment ////////////////////////////////////////////////////////////////////// // DeclHandler virtual void elementDecl(const stringT& name, const stringT& model) { if(!documentType_) return; documentType_->addElement(name); } // elementDecl virtual void attributeDecl(const stringT& elementName, const stringT& attributeName, const stringT& type, const stringT& valueDefault, const stringT& value) { if(!documentType_) return; if(!string_adaptorT::empty(value)) documentType_->addDefaultAttr(elementName, attributeName, value); if(type == attributeTypes_.id) documentType_->addElementId(attributeName); } // attributeDecl virtual void internalEntityDecl(const stringT& name, const stringT& value) { if(!documentType_) return; EntityT* entity = new EntityT(0, name, string_adaptorT::construct_from_utf8(""), string_adaptorT::construct_from_utf8(""), string_adaptorT::construct_from_utf8("")); declaredEntities_.insert(std::make_pair(name, entity)); documentType_->addEntity(entity); DOM::Node<stringT, string_adaptorT> n = entity; n.appendChild(document_.createTextNode(value)); } // internalEntityDecl virtual void externalEntityDecl(const stringT& name, const stringT& publicId, const stringT& systemId) { if(!documentType_) return; EntityT* entity = new EntityT(0, name, publicId, systemId, string_adaptorT::construct_from_utf8("")); declaredEntities_.insert(std::make_pair(name, entity)); // we'll populate it later documentType_->addEntity(entity); } // externalEntityDecl ///////////////////////////////////////////////////////////////////////// // DTDHandler virtual void notationDecl(const stringT& name, const stringT& publicId, const stringT& systemId) { if(!documentType_) return; documentType_->addNotation(new NotationT(0, name, publicId, systemId)); } // notationDecl virtual void unparsedEntityDecl(const stringT& name, const stringT& publicId, const stringT& systemId, const stringT& notationName) { if(!documentType_) return; documentType_->addEntity(new EntityT(0, name, publicId, systemId, notationName)); } // unparsedEntityDecl }; // class Parser } // namespace SAX2DOM } // namespace Arabica #endif <|endoftext|>
<commit_before>#include "game/ht.h" #include "game/sdl/hosthelpers.h" #include "base/tick.h" #include "base/log.h" #include "base/thread.h" #include "base/md5.h" #include "game/httppackmanager.h" #include "game/httppackinfomanager.h" #include "game/httpservice.h" #include "game/completemanager.h" #include <sys/types.h> #include <errno.h> #include <SDL.h> namespace wi { SdlPackFileReader gpakr; HttpPackManager *gppackm; HttpPackInfoManager *gppim; CompleteManager *gpcptm; char *gpszUdid; bool HostInit() { HostHelpers::Init(); // gppackm = new HttpPackManager(gphttp, HostHelpers::GetMissionPacksDir(), HostHelpers::GetTempDir()); gppackm->InitFromInstalled(); gppim = new HttpPackInfoManager(gphttp, HostHelpers::GetMissionPackInfosDir(), HostHelpers::GetTempDir()); gpcptm = new CompleteManager(HostHelpers::GetCompletesDir()); gpcptm->Init(); // TODO(darrinm): get user id (gpszUdid) return true; } void HostExit() { delete gppim; delete gppackm; HostHelpers::Cleanup(); } const char *HostGetDeviceId() { // Hash it so query params aren't obnoxious MD5_CTX md5; MD5Init(&md5); const char *udid = HostHelpers::GetUdid(); MD5Update(&md5, (const byte *)udid, strlen(udid)); byte hash[16]; MD5Final(hash, &md5); return base::Format::ToHex(hash, 16); } void HostInitiateWebView(const char *title, const char *url) { return HostHelpers::InitiateWebView(title, url); } IChatController *HostGetChatController() { return HostHelpers::GetChatController(); } void HostInitiateAsk(const char *title, int max, const char *def, int keyboard, bool secure) { return HostHelpers::InitiateAsk(title, max, def, keyboard, secure); } void HostGetAskString(char *psz, int cb) { return HostHelpers::GetAskString(psz, cb); } void HostOpenUrl(const char *pszUrl) { HostHelpers::OpenUrl(pszUrl); } void HostSuspendModalLoop(DibBitmap *pbm) { // Wait for WI to become active again LOG() << "Entering SuspendModalLoop"; base::Thread& thread = base::Thread::current(); while (true) { base::Message msg; thread.Get(&msg); if (msg.id == kidmAppSetFocus) { break; } if (msg.id == kidmAppTerminate) { thread.Post(&msg); break; } thread.Dispatch(&msg); } LOG() << "Leaving SuspendModalLoop"; } bool ProcessSdlEvent(Event *pevt) { memset(pevt, 0, sizeof(*pevt)); SDL_Event event; switch (SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT)) { case -1: // App is exiting, or there is an error pevt->eType = appStopEvent; break; case 0: return false; } switch (event.type) { case SDL_MOUSEBUTTONDOWN: pevt->eType = penDownEvent; pevt->x = event.button.x; pevt->y = event.button.y; break; case SDL_MOUSEBUTTONUP: pevt->eType = penUpEvent; pevt->x = event.button.x; pevt->y = event.button.y; break; case SDL_MOUSEMOTION: pevt->eType = penMoveEvent; pevt->x = event.motion.x; pevt->y = event.motion.y; break; case SDL_KEYDOWN: pevt->eType = keyDownEvent; switch (event.key.keysym.sym) { case SDLK_UP: pevt->chr = chrPageUp; break; case SDLK_DOWN: pevt->chr = chrPageDown; break; case SDLK_LEFT: pevt->chr = chrLeft; break; case SDLK_RIGHT: pevt->chr = chrRight; break; case SDLK_BACKSPACE: pevt->chr = chrBackspace; break; case SDLK_DELETE: pevt->chr = chrDelete; break; #if 0 case SDLK_F7: if (gpavir == NULL) { gpavir = new AviRecorder(); Size siz; gpdisp->GetFrontDib()->GetSize(&siz); if (!gpavir->Start(siz.cx, siz.cy)) { delete gpavir; gpavir = NULL; } } break; case SDLK_F8: if (gpavir != NULL) { gpavir->Stop(); delete gpavir; gpavir = NULL; } break; #endif case SDLK_KP_MINUS: // numpad { int i = 0; for (; i < ARRAYSIZE(gatGameSpeeds); i++) if (gatGameSpeeds[i] == gtGameSpeed) break; i--; if (i < 0) i = 0; ggame.SetGameSpeed(gatGameSpeeds[i]); } break; case SDLK_KP_PLUS: // numpad { int i = 0; for (; i < ARRAYSIZE(gatGameSpeeds); i++) if (gatGameSpeeds[i] == gtGameSpeed) break; i++; if (i >= ARRAYSIZE(gatGameSpeeds)) i = ARRAYSIZE(gatGameSpeeds) - 1; ggame.SetGameSpeed(gatGameSpeeds[i]); } break; default: #ifdef DEBUG_HELPERS extern void DebugHelperKeyHandler(word vk); DebugHelperKeyHandler(pmsg->wParam); #endif pevt->chr = event.key.keysym.sym; break; } break; case SDL_QUIT: pevt->eType = appStopEvent; break; default: return false; } #if 0 // TODO(scottlu) - Add SDL processing for touch events. - Generate penMoveEvent2, penDownEvent2, penUpEvent2 - add pevt->ff |= kfEvtFinger - add SDL support for device turned off, or locked and return gameSuspendEvent. If no SDL support for this, post kidmAppKillFocus in native layer and translate into gameSuspendEvent in ProcessEvents. old code: case kidmAppKillFocus: pevt->eType = gameSuspendEvent; pevt->ff = 0; break; #endif #if 0 // TODO(darrinm) if (gpdisp != NULL) { int x = pevt->x; int y = pevt->y; SurfaceProperties props; HostHelpers::GetSurfaceProperties(&props); int cx = props.cxWidth; int cy = props.cyHeight; ModeInfo mode; gpdisp->GetMode(&mode); switch (mode.nDegreeOrientation) { case 0: // Screen rotated 90 degrees but coordinates unrotated pevt->x = y; pevt->y = (cy - 1) - x; break; case 90: pevt->x = (cy - 1) - y; pevt->y = x; break; case 180: pevt->x = (cx - 1) - x; pevt->y = (cy - 1) - y; break; case 270: pevt->x = y; pevt->y = (cx - 1) - x; break; } } #endif return true; } bool ProcessMessage(base::Message *pmsg, Event *pevt) { memset(pevt, sizeof(*pevt), 0); switch (pmsg->id) { case kidmNullEvent: pevt->eType = nullEvent; break; case kidmTransportEvent: pevt->eType = transportEvent; break; case kidmAskStringEvent: pevt->eType = askStringEvent; break; default: return false; } return true; } bool HostGetEvent(Event *pevt, long ctWait) { base::Thread& thread = base::Thread::current(); while (true) { base::Message msg; if (!thread.Get(&msg, ctWait)) { return false; } if (msg.handler != NULL) { thread.Dispatch(&msg); continue; } if (msg.id == kidmSdlEvent) { if (ProcessSdlEvent(pevt)) { return true; } continue; } if (ProcessMessage(&msg, pevt)) { return true; } } } void HostOutputDebugString(char *pszFormat, ...) { #ifdef DEBUG va_list va; va_start(va, pszFormat); HostHelpers::Log(pszFormat, va); va_end(va); #endif } long HostGetTickCount() { return (long)base::GetTickCount(); } long HostGetMillisecondCount() { return (long)base::GetMillisecondCount(); } long HostRunSpeedTests(DibBitmap *pbmSrc) { return 0; } dword HostGetCurrentKeyState(dword keyBit) { return 0; } bool HostIsPenDown() { return false; } void HostMessageBox(TCHAR *pszFormat, ...) { va_list va; va_start(va, pszFormat); HostHelpers::MessageBox(pszFormat, va); va_end(va); } void HostGetUserName(char *pszBuff, int cb) { strncpyz(pszBuff, "anonymous", cb); } bool HostGetOwnerName(char *pszBuff, int cb, bool fShowError) { strncpyz(pszBuff, "Player", cb); return true; } // UNDONE: prefix directory? FileHandle HostOpenFile(const char *pszFilename, word wf) { const char *pszMode; if (wf == kfOfRead) pszMode = "rb"; else if (wf == kfOfWrite) pszMode = "wb"; else if (wf == (kfOfRead | kfOfWrite)) pszMode = "rb+"; return (FileHandle)fopen((char *)pszFilename, pszMode); } void HostCloseFile(FileHandle hf) { fclose((FILE *)hf); } dword HostWriteFile(FileHandle hf, void *pv, dword cb) { return fwrite(pv, 1, cb, (FILE *)hf); } dword HostReadFile(FileHandle hf, void *pv, dword cb) { return fread(pv, 1, cb, (FILE *)hf); } void HostSleep(dword ct) { int cms = ct * 10; struct timeval tvWait; tvWait.tv_sec = cms / 1000; tvWait.tv_usec = (cms % 1000) * 1000; select(0, NULL, NULL, NULL, &tvWait); } void HostGetSilkRect(int irc, Rect *prc) { return; } // Figure out what kind of sound device exists, and return a SoundDevice for it SoundDevice *HostOpenSoundDevice() { return CreateSdlSoundDevice(); } SoundDevice::~SoundDevice() { } // Used for sound buffer maintenance requirements bool HostSoundServiceProc() { return true; } void HostGetCurrentDate(Date *pdate) { time_t result = time(NULL); struct tm *ptm = localtime(&result); pdate->nYear = ptm->tm_year + 1900; pdate->nMonth = ptm->tm_mon + 1; pdate->nDay = ptm->tm_mday; } bool HostSavePreferences(void *pv, int cb) { LOG() << HostHelpers::GetPrefsFilename(); FILE *pf = fopen(HostHelpers::GetPrefsFilename(), "wb"); if (pf == NULL) { LOG() << "error opening preferences! " << errno; return false; } if (fwrite(pv, cb, 1, pf) != 1) { LOG() << "error writing preferences! " << errno; fclose(pf); return false; } fclose(pf); return true; } int HostLoadPreferences(void *pv, int cb) { FILE *pf = fopen(HostHelpers::GetPrefsFilename(), "rb"); if (pf == NULL) { return -1; } // Read prefs int cbRead = (int)fread(pv, 1, cb, pf); fclose(pf); return cbRead; } const char *HostGetMainDataDir() { return HostHelpers::GetMainDataDir(); } const char *HostGetSaveGamesDir() { return HostHelpers::GetSaveGamesDir(); } void HostNotEnoughMemory(bool fStorage, dword cbFree, dword cbNeed) { HostMessageBox(TEXT((char *)"Need %ld bytes of memory but only %ld bytes are free!"), cbNeed, cbFree); } bool HostEnumAddonFiles(Enum *penm, char *pszAddonDir, int cbDir, char *pszAddon, int cb) { // PackManager is the way to do this now return false; } } // namespace wi <commit_msg>SDL host HostGetDeviceId() -> HostGenerateDeviceId()<commit_after>#include "game/ht.h" #include "game/sdl/hosthelpers.h" #include "base/tick.h" #include "base/log.h" #include "base/thread.h" #include "base/md5.h" #include "game/httppackmanager.h" #include "game/httppackinfomanager.h" #include "game/httpservice.h" #include "game/completemanager.h" #include <sys/types.h> #include <errno.h> #include <SDL.h> namespace wi { SdlPackFileReader gpakr; HttpPackManager *gppackm; HttpPackInfoManager *gppim; CompleteManager *gpcptm; char *gpszUdid; bool HostInit() { HostHelpers::Init(); // gppackm = new HttpPackManager(gphttp, HostHelpers::GetMissionPacksDir(), HostHelpers::GetTempDir()); gppackm->InitFromInstalled(); gppim = new HttpPackInfoManager(gphttp, HostHelpers::GetMissionPackInfosDir(), HostHelpers::GetTempDir()); gpcptm = new CompleteManager(HostHelpers::GetCompletesDir()); gpcptm->Init(); // TODO(darrinm): get user id (gpszUdid) return true; } void HostExit() { delete gppim; delete gppackm; HostHelpers::Cleanup(); } const char *HostGenerateDeviceId() { // Hash it so query params aren't obnoxious MD5_CTX md5; MD5Init(&md5); const char *udid = HostHelpers::GetUdid(); MD5Update(&md5, (const byte *)udid, strlen(udid)); byte hash[16]; MD5Final(hash, &md5); return base::Format::ToHex(hash, 16); } void HostInitiateWebView(const char *title, const char *url) { return HostHelpers::InitiateWebView(title, url); } IChatController *HostGetChatController() { return HostHelpers::GetChatController(); } void HostInitiateAsk(const char *title, int max, const char *def, int keyboard, bool secure) { return HostHelpers::InitiateAsk(title, max, def, keyboard, secure); } void HostGetAskString(char *psz, int cb) { return HostHelpers::GetAskString(psz, cb); } void HostOpenUrl(const char *pszUrl) { HostHelpers::OpenUrl(pszUrl); } void HostSuspendModalLoop(DibBitmap *pbm) { // Wait for WI to become active again LOG() << "Entering SuspendModalLoop"; base::Thread& thread = base::Thread::current(); while (true) { base::Message msg; thread.Get(&msg); if (msg.id == kidmAppSetFocus) { break; } if (msg.id == kidmAppTerminate) { thread.Post(&msg); break; } thread.Dispatch(&msg); } LOG() << "Leaving SuspendModalLoop"; } bool ProcessSdlEvent(Event *pevt) { memset(pevt, 0, sizeof(*pevt)); SDL_Event event; switch (SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT)) { case -1: // App is exiting, or there is an error pevt->eType = appStopEvent; break; case 0: return false; } switch (event.type) { case SDL_MOUSEBUTTONDOWN: pevt->eType = penDownEvent; pevt->x = event.button.x; pevt->y = event.button.y; break; case SDL_MOUSEBUTTONUP: pevt->eType = penUpEvent; pevt->x = event.button.x; pevt->y = event.button.y; break; case SDL_MOUSEMOTION: pevt->eType = penMoveEvent; pevt->x = event.motion.x; pevt->y = event.motion.y; break; case SDL_KEYDOWN: pevt->eType = keyDownEvent; switch (event.key.keysym.sym) { case SDLK_UP: pevt->chr = chrPageUp; break; case SDLK_DOWN: pevt->chr = chrPageDown; break; case SDLK_LEFT: pevt->chr = chrLeft; break; case SDLK_RIGHT: pevt->chr = chrRight; break; case SDLK_BACKSPACE: pevt->chr = chrBackspace; break; case SDLK_DELETE: pevt->chr = chrDelete; break; #if 0 case SDLK_F7: if (gpavir == NULL) { gpavir = new AviRecorder(); Size siz; gpdisp->GetFrontDib()->GetSize(&siz); if (!gpavir->Start(siz.cx, siz.cy)) { delete gpavir; gpavir = NULL; } } break; case SDLK_F8: if (gpavir != NULL) { gpavir->Stop(); delete gpavir; gpavir = NULL; } break; #endif case SDLK_KP_MINUS: // numpad { int i = 0; for (; i < ARRAYSIZE(gatGameSpeeds); i++) if (gatGameSpeeds[i] == gtGameSpeed) break; i--; if (i < 0) i = 0; ggame.SetGameSpeed(gatGameSpeeds[i]); } break; case SDLK_KP_PLUS: // numpad { int i = 0; for (; i < ARRAYSIZE(gatGameSpeeds); i++) if (gatGameSpeeds[i] == gtGameSpeed) break; i++; if (i >= ARRAYSIZE(gatGameSpeeds)) i = ARRAYSIZE(gatGameSpeeds) - 1; ggame.SetGameSpeed(gatGameSpeeds[i]); } break; default: #ifdef DEBUG_HELPERS extern void DebugHelperKeyHandler(word vk); DebugHelperKeyHandler(pmsg->wParam); #endif pevt->chr = event.key.keysym.sym; break; } break; case SDL_QUIT: pevt->eType = appStopEvent; break; default: return false; } #if 0 // TODO(scottlu) - Add SDL processing for touch events. - Generate penMoveEvent2, penDownEvent2, penUpEvent2 - add pevt->ff |= kfEvtFinger - add SDL support for device turned off, or locked and return gameSuspendEvent. If no SDL support for this, post kidmAppKillFocus in native layer and translate into gameSuspendEvent in ProcessEvents. old code: case kidmAppKillFocus: pevt->eType = gameSuspendEvent; pevt->ff = 0; break; #endif #if 0 // TODO(darrinm) if (gpdisp != NULL) { int x = pevt->x; int y = pevt->y; SurfaceProperties props; HostHelpers::GetSurfaceProperties(&props); int cx = props.cxWidth; int cy = props.cyHeight; ModeInfo mode; gpdisp->GetMode(&mode); switch (mode.nDegreeOrientation) { case 0: // Screen rotated 90 degrees but coordinates unrotated pevt->x = y; pevt->y = (cy - 1) - x; break; case 90: pevt->x = (cy - 1) - y; pevt->y = x; break; case 180: pevt->x = (cx - 1) - x; pevt->y = (cy - 1) - y; break; case 270: pevt->x = y; pevt->y = (cx - 1) - x; break; } } #endif return true; } bool ProcessMessage(base::Message *pmsg, Event *pevt) { memset(pevt, sizeof(*pevt), 0); switch (pmsg->id) { case kidmNullEvent: pevt->eType = nullEvent; break; case kidmTransportEvent: pevt->eType = transportEvent; break; case kidmAskStringEvent: pevt->eType = askStringEvent; break; default: return false; } return true; } bool HostGetEvent(Event *pevt, long ctWait) { base::Thread& thread = base::Thread::current(); while (true) { base::Message msg; if (!thread.Get(&msg, ctWait)) { return false; } if (msg.handler != NULL) { thread.Dispatch(&msg); continue; } if (msg.id == kidmSdlEvent) { if (ProcessSdlEvent(pevt)) { return true; } continue; } if (ProcessMessage(&msg, pevt)) { return true; } } } void HostOutputDebugString(char *pszFormat, ...) { #ifdef DEBUG va_list va; va_start(va, pszFormat); HostHelpers::Log(pszFormat, va); va_end(va); #endif } long HostGetTickCount() { return (long)base::GetTickCount(); } long HostGetMillisecondCount() { return (long)base::GetMillisecondCount(); } long HostRunSpeedTests(DibBitmap *pbmSrc) { return 0; } dword HostGetCurrentKeyState(dword keyBit) { return 0; } bool HostIsPenDown() { return false; } void HostMessageBox(TCHAR *pszFormat, ...) { va_list va; va_start(va, pszFormat); HostHelpers::MessageBox(pszFormat, va); va_end(va); } void HostGetUserName(char *pszBuff, int cb) { strncpyz(pszBuff, "anonymous", cb); } bool HostGetOwnerName(char *pszBuff, int cb, bool fShowError) { strncpyz(pszBuff, "Player", cb); return true; } // UNDONE: prefix directory? FileHandle HostOpenFile(const char *pszFilename, word wf) { const char *pszMode; if (wf == kfOfRead) pszMode = "rb"; else if (wf == kfOfWrite) pszMode = "wb"; else if (wf == (kfOfRead | kfOfWrite)) pszMode = "rb+"; return (FileHandle)fopen((char *)pszFilename, pszMode); } void HostCloseFile(FileHandle hf) { fclose((FILE *)hf); } dword HostWriteFile(FileHandle hf, void *pv, dword cb) { return fwrite(pv, 1, cb, (FILE *)hf); } dword HostReadFile(FileHandle hf, void *pv, dword cb) { return fread(pv, 1, cb, (FILE *)hf); } void HostSleep(dword ct) { int cms = ct * 10; struct timeval tvWait; tvWait.tv_sec = cms / 1000; tvWait.tv_usec = (cms % 1000) * 1000; select(0, NULL, NULL, NULL, &tvWait); } void HostGetSilkRect(int irc, Rect *prc) { return; } // Figure out what kind of sound device exists, and return a SoundDevice for it SoundDevice *HostOpenSoundDevice() { return CreateSdlSoundDevice(); } SoundDevice::~SoundDevice() { } // Used for sound buffer maintenance requirements bool HostSoundServiceProc() { return true; } void HostGetCurrentDate(Date *pdate) { time_t result = time(NULL); struct tm *ptm = localtime(&result); pdate->nYear = ptm->tm_year + 1900; pdate->nMonth = ptm->tm_mon + 1; pdate->nDay = ptm->tm_mday; } bool HostSavePreferences(void *pv, int cb) { LOG() << HostHelpers::GetPrefsFilename(); FILE *pf = fopen(HostHelpers::GetPrefsFilename(), "wb"); if (pf == NULL) { LOG() << "error opening preferences! " << errno; return false; } if (fwrite(pv, cb, 1, pf) != 1) { LOG() << "error writing preferences! " << errno; fclose(pf); return false; } fclose(pf); return true; } int HostLoadPreferences(void *pv, int cb) { FILE *pf = fopen(HostHelpers::GetPrefsFilename(), "rb"); if (pf == NULL) { return -1; } // Read prefs int cbRead = (int)fread(pv, 1, cb, pf); fclose(pf); return cbRead; } const char *HostGetMainDataDir() { return HostHelpers::GetMainDataDir(); } const char *HostGetSaveGamesDir() { return HostHelpers::GetSaveGamesDir(); } void HostNotEnoughMemory(bool fStorage, dword cbFree, dword cbNeed) { HostMessageBox(TEXT((char *)"Need %ld bytes of memory but only %ld bytes are free!"), cbNeed, cbFree); } bool HostEnumAddonFiles(Enum *penm, char *pszAddonDir, int cbDir, char *pszAddon, int cb) { // PackManager is the way to do this now return false; } } // namespace wi <|endoftext|>
<commit_before>/* Copyright (C) 2019 Marc Stevens. This file is part of fplll. fplll 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. fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */ #include <fplll/threadpool.h> FPLLL_BEGIN_NAMESPACE thread_pool::thread_pool threadpool(0); /* get and set number of threads in threadpool, both return the (new) number of threads */ int get_threads() { return threadpool.size() + 1; } int set_threads(int th) { if (th > std::thread::hardware_concurrency() || th == -1) th = std::thread::hardware_concurrency(); if (th < 1) th = 1; threadpool.resize(th - 1); return get_threads(); } FPLLL_END_NAMESPACE <commit_msg>Default # threads to machine's cores<commit_after>/* Copyright (C) 2019 Marc Stevens. This file is part of fplll. fplll 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. fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */ #include <fplll/threadpool.h> FPLLL_BEGIN_NAMESPACE thread_pool::thread_pool threadpool(std::thread::hardware_concurrency() - 1); /* get and set number of threads in threadpool, both return the (new) number of threads */ int get_threads() { return threadpool.size() + 1; } int set_threads(int th) { if (th > std::thread::hardware_concurrency() || th == -1) th = std::thread::hardware_concurrency(); if (th < 1) th = 1; threadpool.resize(th - 1); return get_threads(); } FPLLL_END_NAMESPACE <|endoftext|>
<commit_before>/******************************************************************************* * * X testing environment - Google Test environment feat. dummy x server * * Copyright (C) 2011, 2012 Canonical Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * ******************************************************************************/ #include "xorg/gtest/xorg-gtest_environment.h" #include "xorg/gtest/xorg-gtest_process.h" #include "defines.h" #include <sys/types.h> #include <unistd.h> #include <cerrno> #include <csignal> #include <cstdlib> #include <cstring> #include <iostream> #include <stdexcept> #include <X11/Xlib.h> struct xorg::testing::Environment::Private { Private() : path_to_conf(DUMMY_CONF_PATH), path_to_log_file(DEFAULT_XORG_LOGFILE), path_to_server(DEFAULT_XORG_SERVER), display(DEFAULT_DISPLAY) { } std::string path_to_conf; std::string path_to_log_file; std::string path_to_server; int display; Process process; }; xorg::testing::Environment::Environment() : d_(new Private) { } xorg::testing::Environment::~Environment() {} void xorg::testing::Environment::set_log_file(const std::string& path_to_log_file) { d_->path_to_log_file = path_to_log_file; } const std::string& xorg::testing::Environment::log_file() const { return d_->path_to_log_file; } void xorg::testing::Environment::set_conf_file(const std::string& path_conf_file) { d_->path_to_conf = path_conf_file; } const std::string& xorg::testing::Environment::conf_file() const { return d_->path_to_conf; } void xorg::testing::Environment::set_server(const std::string& path_to_server) { d_->path_to_server = path_to_server; } const std::string& xorg::testing::Environment::server() const { return d_->path_to_server; } void xorg::testing::Environment::set_display(int display_num) { d_->display = display_num; } int xorg::testing::Environment::display() const { return d_->display; } void xorg::testing::Environment::SetUp() { static char display_string[6]; snprintf(display_string, 6, ":%d", d_->display); Display* test_display = XOpenDisplay(display_string); if (test_display) { XCloseDisplay(test_display); std::string message; message += "A server is already running on "; message += display_string; message += "."; throw std::runtime_error(message); } d_->process.Start(d_->path_to_server, d_->path_to_server.c_str(), display_string, "-logfile", d_->path_to_log_file.c_str(), "-config", d_->path_to_conf.c_str(), NULL); Process::SetEnv("DISPLAY", display_string, true); for (int i = 0; i < 10; ++i) { test_display = XOpenDisplay(NULL); if (test_display) { XCloseDisplay(test_display); return; } int status; int pid = waitpid(d_->process.Pid(), &status, WNOHANG); if (pid == d_->process.Pid()) { std::string message; message += "X server failed to start on display "; message += display_string; message += ". Ensure that the \"dummy\" video driver is installed. " "If the X.org server is older than 1.12, " "tests will need to be run as root. Check "; message += d_->path_to_log_file; message += " for any errors"; throw std::runtime_error(message); } else if (pid == 0) { sleep(1); /* Give the dummy X server some time to start */ } else if (pid == -1) { throw std::runtime_error("Could not get status of dummy X server " "process"); } else { throw std::runtime_error("Invalid child PID returned by Process::Wait()"); } } throw std::runtime_error("Unable to open connection to dummy X server"); } void xorg::testing::Environment::TearDown() { if (d_->process.Terminate()) { for (int i = 0; i < 10; i++) { int status; int pid = waitpid(d_->process.Pid(), &status, WNOHANG); if (pid == d_->process.Pid()) return; sleep(1); /* Give the dummy X server more time to shut down */ } } Kill(); } void xorg::testing::Environment::Kill() { if (!d_->process.Kill()) std::cerr << "Warning: Failed to kill dummy Xorg server: " << std::strerror(errno) << "\n"; for (int i = 0; i < 10; i++) { int status; int pid = waitpid(d_->process.Pid(), &status, WNOHANG); if (pid == d_->process.Pid()) return; sleep(1); /* Give the dummy X server more time to shut down */ } std::cerr << "Warning: Dummy X server did not shut down\n"; } <commit_msg>Check if log file and old log file are writable before starting X server<commit_after>/******************************************************************************* * * X testing environment - Google Test environment feat. dummy x server * * Copyright (C) 2011, 2012 Canonical Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * ******************************************************************************/ #include "xorg/gtest/xorg-gtest_environment.h" #include "xorg/gtest/xorg-gtest_process.h" #include "defines.h" #include <sys/types.h> #include <unistd.h> #include <cerrno> #include <csignal> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <stdexcept> #include <X11/Xlib.h> struct xorg::testing::Environment::Private { Private() : path_to_conf(DUMMY_CONF_PATH), path_to_log_file(DEFAULT_XORG_LOGFILE), path_to_server(DEFAULT_XORG_SERVER), display(DEFAULT_DISPLAY) { } std::string path_to_conf; std::string path_to_log_file; std::string path_to_server; int display; Process process; }; xorg::testing::Environment::Environment() : d_(new Private) { } xorg::testing::Environment::~Environment() {} void xorg::testing::Environment::set_log_file(const std::string& path_to_log_file) { d_->path_to_log_file = path_to_log_file; } const std::string& xorg::testing::Environment::log_file() const { return d_->path_to_log_file; } void xorg::testing::Environment::set_conf_file(const std::string& path_conf_file) { d_->path_to_conf = path_conf_file; } const std::string& xorg::testing::Environment::conf_file() const { return d_->path_to_conf; } void xorg::testing::Environment::set_server(const std::string& path_to_server) { d_->path_to_server = path_to_server; } const std::string& xorg::testing::Environment::server() const { return d_->path_to_server; } void xorg::testing::Environment::set_display(int display_num) { d_->display = display_num; } int xorg::testing::Environment::display() const { return d_->display; } void xorg::testing::Environment::SetUp() { static char display_string[6]; snprintf(display_string, 6, ":%d", d_->display); Display* test_display = XOpenDisplay(display_string); if (test_display) { XCloseDisplay(test_display); std::string message; message += "A server is already running on "; message += display_string; message += "."; throw std::runtime_error(message); } /* The Xorg server won't start unless the log file and the old log file are * writable. */ std::ofstream log_test; log_test.open(d_->path_to_log_file.c_str(), std::ofstream::out); log_test.close(); if (log_test.fail()) { std::string message; message += "X.org server log file "; message += d_->path_to_log_file; message += " is not writable."; throw std::runtime_error(message); } std::string old_log_file = d_->path_to_log_file.c_str(); old_log_file += ".old"; log_test.open(old_log_file.c_str(), std::ofstream::out); log_test.close(); if (log_test.fail()) { std::string message; message += "X.org old server log file "; message += old_log_file; message += " is not writable."; throw std::runtime_error(message); } d_->process.Start(d_->path_to_server, d_->path_to_server.c_str(), display_string, "-logfile", d_->path_to_log_file.c_str(), "-config", d_->path_to_conf.c_str(), NULL); Process::SetEnv("DISPLAY", display_string, true); for (int i = 0; i < 10; ++i) { test_display = XOpenDisplay(NULL); if (test_display) { XCloseDisplay(test_display); return; } int status; int pid = waitpid(d_->process.Pid(), &status, WNOHANG); if (pid == d_->process.Pid()) { std::string message; message += "X server failed to start on display "; message += display_string; message += ". Ensure that the \"dummy\" video driver is installed. " "If the X.org server is older than 1.12, " "tests will need to be run as root. Check "; message += d_->path_to_log_file; message += " for any errors"; throw std::runtime_error(message); } else if (pid == 0) { sleep(1); /* Give the dummy X server some time to start */ } else if (pid == -1) { throw std::runtime_error("Could not get status of dummy X server " "process"); } else { throw std::runtime_error("Invalid child PID returned by Process::Wait()"); } } throw std::runtime_error("Unable to open connection to dummy X server"); } void xorg::testing::Environment::TearDown() { if (d_->process.Terminate()) { for (int i = 0; i < 10; i++) { int status; int pid = waitpid(d_->process.Pid(), &status, WNOHANG); if (pid == d_->process.Pid()) return; sleep(1); /* Give the dummy X server more time to shut down */ } } Kill(); } void xorg::testing::Environment::Kill() { if (!d_->process.Kill()) std::cerr << "Warning: Failed to kill dummy Xorg server: " << std::strerror(errno) << "\n"; for (int i = 0; i < 10; i++) { int status; int pid = waitpid(d_->process.Pid(), &status, WNOHANG); if (pid == d_->process.Pid()) return; sleep(1); /* Give the dummy X server more time to shut down */ } std::cerr << "Warning: Dummy X server did not shut down\n"; } <|endoftext|>
<commit_before>#include "sphere2.h" #include "utils.h" #include <cmath> namespace batoid { Sphere2::Sphere2(double R) : _R(R), _Rsq(R*R), _Rinv(1./R), _Rinvsq(1./R/R) {} #pragma omp declare target double Sphere2::_sag(double x, double y) const { if (_R != 0) return _R*(1-sqrt(1-(x*x + y*y)*_Rinvsq)); return 0.0; } void Sphere2::_normal(double x, double y, double& nx, double& ny, double& nz) const { double rsqr = x*x + y*y; if (_R == 0.0 || rsqr == 0.0) { nx = 0.0; ny = 0.0; nz = 1.0; } else { double r = sqrt(rsqr); double dzdr = _dzdr(r); double norm = 1/sqrt(1+dzdr*dzdr); nx = -x/r*dzdr*norm; ny = -y/r*dzdr*norm; nz = norm; } } bool Sphere2::_timeToIntersect( double x, double y, double z, double vx, double vy, double vz, double& dt ) const { double vr2 = vx*vx + vy*vy; double vz2 = vz*vz; double vrr0 = vx*x + vy*y; double r02 = x*x + y*y; double z0term = z-_R; double a = vz2 + vr2; double b = 2*vz*z0term + 2*vrr0; double c = z0term*z0term - _Rsq + r02; double discriminant = b*b - 4*a*c; double dt1; if (b > 0) { dt1 = (-b - sqrt(discriminant)) / (2*a); } else { dt1 = 2*c / (-b + sqrt(discriminant)); } double dt2 = c / (a*dt1); if (dt1 > 0) { dt = dt1; return true; } if (dt2 > 0) { dt = dt2; return true; } return false; } double Sphere2::_dzdr(double r) const { double rat = r*_Rinv; return rat/sqrt(1-rat*rat); } #pragma omp end declare target // void sphere2::_intersectInPlace(RayVector2& rv) const { // rv.r.syncToDevice(); // rv.v.syncToDevice(); // rv.t.syncToDevice(); // rv.vignetted.syncToDevice(); // rv.failed.syncToDevice(); // size_t size = rv.size; // double* xptr = rv.r.deviceData; // double* yptr = xptr + size; // double* zptr = yptr + size; // double* vxptr = rv.v.deviceData; // double* vyptr = vxptr + size; // double* vzptr = vyptr + size; // double* tptr = rv.t.deviceData; // bool* vigptr = rv.vignetted.deviceData; // bool* failptr = rv.failed.deviceData; // #pragma omp target is_device_ptr(xptr, yptr, zptr, vxptr, vyptr, vzptr, tptr, vigptr, failptr) // { // #pragma omp teams distribute parallel for // for(int i=0; i<size; i++) { // if (!failptr[i]) { // double dt = -zptr[i]/vzptr[i]; // if (!_allowReverse && dt < 0) { // failptr[i] = true; // vigptr[i] = true; // } else { // xptr[i] += vxptr[i] * dt; // yptr[i] += vyptr[i] * dt; // zptr[i] += vzptr[i] * dt; // tptr[i] += dt; // } // } // } // } // } // // void sphere2::_reflectInPlace(RayVector2& rv) const { // _intersectInPlace(rv); // size_t size = rv.size; // double* vzptr = rv.v.deviceData+2*size; // // #pragma omp target is_device_ptr(vzptr) // { // #pragma omp teams distribute parallel for // for(int i=0; i<size; i++) { // vzptr[i] *= -1; // } // } // } // // void sphere2::_refractInPlace(RayVector2& rv, const Medium2& m1, const Medium2& m2) const { // intersectInPlace(rv); // size_t size = rv.size; // double* vxptr = rv.v.deviceData; // double* vyptr = vxptr + size; // double* vzptr = vyptr + size; // double* wptr = rv.wavelength.deviceData; // // // DualView<double> n1(size); // // double* n1ptr = n1.deviceData; // // m1.getNMany(rv.wavelength, n1); // DualView<double> n2(size); // double* n2ptr = n2.deviceData; // m2.getNMany(rv.wavelength, n2); // // #pragma omp target is_device_ptr(n2ptr, vxptr, vyptr, vzptr) // { // #pragma omp teams distribute parallel for // for(int i=0; i<size; i++) { // double n1 = vxptr[i]*vxptr[i]; // n1 += vyptr[i]*vyptr[i]; // n1 += vzptr[i]*vzptr[i]; // n1 = 1/sqrt(n1); // // double discriminant = vzptr[i]*vzptr[i] * n1*n1; // discriminant -= (1-n2ptr[i]*n2ptr[i]/(n1*n1)); // // double norm = n1*n1*vxptr[i]*vxptr[i]; // norm += n1*n1*vyptr[i]*vyptr[i]; // norm += discriminant; // norm = sqrt(norm); // vxptr[i] = n1*vxptr[i]/norm/n2ptr[i]; // vyptr[i] = n1*vyptr[i]/norm/n2ptr[i]; // vzptr[i] = sqrt(discriminant)/norm/n2ptr[i]; // } // } // } // // Specializations // template<> // void Surface2CRTP<sphere2>::intersectInPlace(RayVector2& rv) const { // const sphere2* self = static_cast<const sphere2*>(this); // self->_intersectInPlace(rv); // } // // template<> // void Surface2CRTP<sphere2>::reflectInPlace(RayVector2& rv) const { // const sphere2* self = static_cast<const sphere2*>(this); // self->_reflectInPlace(rv); // } // // template<> // void Surface2CRTP<sphere2>::refractInPlace(RayVector2& rv, const Medium2& m1, const Medium2& m2) const { // const sphere2* self = static_cast<const sphere2*>(this); // self->_refractInPlace(rv, m1, m2); // } } <commit_msg>Cleanup sphere2<commit_after>#include "sphere2.h" #include "utils.h" #include <cmath> namespace batoid { Sphere2::Sphere2(double R) : _R(R), _Rsq(R*R), _Rinv(1./R), _Rinvsq(1./R/R) {} #pragma omp declare target double Sphere2::_sag(double x, double y) const { if (_R != 0) return _R*(1-sqrt(1-(x*x + y*y)*_Rinvsq)); return 0.0; } void Sphere2::_normal(double x, double y, double& nx, double& ny, double& nz) const { double rsqr = x*x + y*y; if (_R == 0.0 || rsqr == 0.0) { nx = 0.0; ny = 0.0; nz = 1.0; } else { double r = sqrt(rsqr); double dzdr = _dzdr(r); double norm = 1/sqrt(1+dzdr*dzdr); nx = -x/r*dzdr*norm; ny = -y/r*dzdr*norm; nz = norm; } } bool Sphere2::_timeToIntersect( double x, double y, double z, double vx, double vy, double vz, double& dt ) const { double vr2 = vx*vx + vy*vy; double vz2 = vz*vz; double vrr0 = vx*x + vy*y; double r02 = x*x + y*y; double z0term = z-_R; double a = vz2 + vr2; double b = 2*vz*z0term + 2*vrr0; double c = z0term*z0term - _Rsq + r02; double discriminant = b*b - 4*a*c; double dt1; if (b > 0) { dt1 = (-b - sqrt(discriminant)) / (2*a); } else { dt1 = 2*c / (-b + sqrt(discriminant)); } double dt2 = c / (a*dt1); if (dt1 > 0) { dt = dt1; return true; } if (dt2 > 0) { dt = dt2; return true; } return false; } double Sphere2::_dzdr(double r) const { double rat = r*_Rinv; return rat/sqrt(1-rat*rat); } #pragma omp end declare target } <|endoftext|>
<commit_before>// Copyright Joshua Boyce 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <[email protected]> #include "hadesmem/injector.hpp" #include <array> #include <iterator> #include <algorithm> #include "hadesmem/detail/warning_disable_prefix.hpp" #include <boost/filesystem.hpp> #include <boost/scope_exit.hpp> #include "hadesmem/detail/warning_disable_suffix.hpp" #include "hadesmem/call.hpp" #include "hadesmem/alloc.hpp" #include "hadesmem/error.hpp" #include "hadesmem/write.hpp" #include "hadesmem/module.hpp" #include "hadesmem/process.hpp" #include "hadesmem/detail/self_path.hpp" #include "hadesmem/detail/argv_quote.hpp" namespace hadesmem { HMODULE InjectDll(Process const& process, std::wstring const& path, int flags) { BOOST_ASSERT((flags & ~(InjectFlags::kInvalidFlagMaxValue - 1)) == 0); // Do not continue if Shim Engine is enabled for local process, // otherwise it could interfere with the address resolution. HMODULE const shim_eng_mod = GetModuleHandle(L"ShimEng.dll"); if (shim_eng_mod) { BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Shims enabled for local process.")); } boost::filesystem::path path_real(path); bool const path_resolution = !!(flags & InjectFlags::kPathResolution); if (path_resolution && path_real.is_relative()) { path_real = boost::filesystem::absolute(path_real, detail::GetSelfDirPath()); } path_real.make_preferred(); // Ensure target file exists // Note: Only performing this check when path resolution is enabled, // because otherwise we would need to perform the check in the context // of the remote process, which is not possible to do without // introducing race conditions and other potential problems. So we just // let LoadLibraryW do the check for us. if (path_resolution && !boost::filesystem::exists(path_real)) { BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Could not find module file.")); } std::wstring const path_string(path_real.native()); std::size_t const path_buf_size = (path_string.size() + 1) * sizeof(wchar_t); Allocator const lib_file_remote(&process, path_buf_size); WriteString(process, lib_file_remote.GetBase(), path_string); Module const kernel32_mod(&process, L"kernel32.dll"); LPCVOID const load_library = reinterpret_cast<LPCVOID>( reinterpret_cast<DWORD_PTR>(FindProcedure(kernel32_mod, "LoadLibraryW"))); typedef HMODULE (*LoadLibraryFuncT)(LPCWSTR lpFileName); std::pair<HMODULE, DWORD> const load_library_ret = Call<LoadLibraryFuncT>(process, load_library, CallConv::kWinApi, static_cast<LPCWSTR>(lib_file_remote.GetBase())); if (!load_library_ret.first) { BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Call to LoadLibraryW in remote process failed.") << ErrorCodeWinLast(load_library_ret.second)); } return load_library_ret.first; } void FreeDll(Process const& process, HMODULE module) { Module const kernel32_mod(&process, L"kernel32.dll"); LPCVOID const free_library = reinterpret_cast<LPCVOID>( reinterpret_cast<DWORD_PTR>(FindProcedure(kernel32_mod, "FreeLibrary"))); typedef BOOL (*FreeLibraryFuncT)(HMODULE hModule); std::pair<BOOL, DWORD> const free_library_ret = Call<FreeLibraryFuncT>(process, free_library, CallConv::kWinApi, module); if (!free_library_ret.first) { BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Call to FreeLibrary in remote process failed.") << ErrorCodeWinLast(free_library_ret.second)); } } // TODO: Configurable timeout. std::pair<DWORD_PTR, DWORD> CallExport(Process const& process, HMODULE module, std::string const& export_name, LPCVOID export_arg) { Module const module_remote(&process, module); LPCVOID const export_ptr = reinterpret_cast<LPCVOID>( reinterpret_cast<DWORD_PTR>(FindProcedure(module_remote, export_name))); return Call<DWORD_PTR(*)(LPCVOID)>(process, export_ptr, CallConv::kDefault, export_arg); } // Constructor CreateAndInjectData::CreateAndInjectData(Process const& process, HMODULE module, DWORD_PTR export_ret, DWORD export_last_error) : process_(process), module_(module), export_ret_(export_ret), export_last_error_(export_last_error) { } CreateAndInjectData::CreateAndInjectData(CreateAndInjectData const& other) : process_(other.process_), module_(other.module_), export_ret_(other.export_ret_), export_last_error_(other.export_last_error_) { } CreateAndInjectData& CreateAndInjectData::operator=( CreateAndInjectData const& other) { process_ = other.process_; module_ = other.module_; export_ret_ = other.export_ret_; export_last_error_ = other.export_last_error_; return *this; } CreateAndInjectData::CreateAndInjectData(CreateAndInjectData&& other) BOOST_NOEXCEPT : process_(std::move(other.process_)), module_(other.module_), export_ret_(other.export_ret_), export_last_error_(other.export_last_error_) { other.module_ = nullptr; other.export_ret_ = 0; other.export_last_error_ = 0; } CreateAndInjectData& CreateAndInjectData::operator=( CreateAndInjectData&& other) BOOST_NOEXCEPT { process_ = std::move(other.process_); module_ = other.module_; other.module_ = nullptr; export_ret_ = other.export_ret_; other.export_ret_ = 0; export_last_error_ = other.export_last_error_; other.export_last_error_ = 0; return *this; } CreateAndInjectData::~CreateAndInjectData() { } Process CreateAndInjectData::GetProcess() const { return process_; } HMODULE CreateAndInjectData::GetModule() const BOOST_NOEXCEPT { return module_; } DWORD_PTR CreateAndInjectData::GetExportRet() const BOOST_NOEXCEPT { return export_ret_; } DWORD CreateAndInjectData::GetExportLastError() const BOOST_NOEXCEPT { return export_last_error_; } CreateAndInjectData CreateAndInject( std::wstring const& path, std::wstring const& work_dir, std::vector<std::wstring> const& args, std::wstring const& module, std::string const& export_name, LPCVOID export_arg, int flags) { boost::filesystem::path const path_real(path); std::wstring command_line; detail::ArgvQuote(&command_line, path_real.native(), false); std::for_each(std::begin(args), std::end(args), [&] (std::wstring const& arg) { command_line += L' '; detail::ArgvQuote(&command_line, arg, false); }); std::vector<wchar_t> proc_args(std::begin(command_line), std::end(command_line)); proc_args.push_back(L'\0'); boost::filesystem::path work_dir_real; if (!work_dir.empty()) { work_dir_real = work_dir; } else if (path_real.has_parent_path()) { work_dir_real = path_real.parent_path(); } else { work_dir_real = L"./"; } STARTUPINFO start_info; ZeroMemory(&start_info, sizeof(start_info)); start_info.cb = sizeof(start_info); PROCESS_INFORMATION proc_info; ZeroMemory(&proc_info, sizeof(proc_info)); if (!::CreateProcess(path_real.c_str(), proc_args.data(), nullptr, nullptr, FALSE, CREATE_SUSPENDED, nullptr, work_dir_real.c_str(), &start_info, &proc_info)) { DWORD const last_error = ::GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Could not create process.") << ErrorCodeWinLast(last_error)); } BOOST_SCOPE_EXIT_ALL(&) { // WARNING: Handle is leaked if CloseHandle fails. BOOST_VERIFY(::CloseHandle(proc_info.hProcess)); BOOST_VERIFY(::CloseHandle(proc_info.hThread)); }; try { Process const process(proc_info.dwProcessId); // This is used to generate a 'nullsub' function, which is called in // the context of the remote process in order to 'force' a call to // ntdll.dll!LdrInitializeThunk. This is necessary because module // enumeration will fail if LdrInitializeThunk has not been called, // and Injector::InjectDll (and the APIs it uses) depend on the // module enumeration APIs. #if defined(_M_AMD64) std::array<BYTE, 1> return_instr = { { 0xC3 } }; #elif defined(_M_IX86) std::array<BYTE, 3> return_instr = { { 0xC2, 0x04, 0x00 } }; #else #error "[HadesMem] Unsupported architecture." #endif Allocator const stub_remote(&process, sizeof(return_instr)); Write(process, stub_remote.GetBase(), return_instr); LPTHREAD_START_ROUTINE stub_remote_pfn = reinterpret_cast<LPTHREAD_START_ROUTINE>( reinterpret_cast<DWORD_PTR>(stub_remote.GetBase())); HANDLE const remote_thread = ::CreateRemoteThread(process.GetHandle(), nullptr, 0, stub_remote_pfn, nullptr, 0, nullptr); if (!remote_thread) { DWORD const last_error = ::GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Could not create remote thread.") << ErrorCodeWinLast(last_error)); } BOOST_SCOPE_EXIT_ALL(&) { // WARNING: Handle is leaked if CloseHandle fails. BOOST_VERIFY(::CloseHandle(remote_thread)); }; // TODO: Add a sensible timeout. if (::WaitForSingleObject(remote_thread, INFINITE) != WAIT_OBJECT_0) { DWORD const last_error = ::GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Could not wait for remote thread.") << ErrorCodeWinLast(last_error)); } HMODULE const remote_module = InjectDll(process, module, flags); std::pair<DWORD_PTR, DWORD> export_ret(0, 0); if (!export_name.empty()) { // TODO: Configurable timeout. export_ret = CallExport(process, remote_module, export_name, export_arg); } if (::ResumeThread(proc_info.hThread) == static_cast<DWORD>(-1)) { DWORD const last_error = ::GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Could not resume process.") << ErrorCodeWinLast(last_error) << ErrorCodeWinRet(export_ret.first) << ErrorCodeWinOther(export_ret.second)); } return CreateAndInjectData(process, remote_module, export_ret.first, export_ret.second); } catch (std::exception const& /*e*/) { // Terminate process if injection failed, otherwise the 'zombie' process // would be leaked. TerminateProcess(proc_info.hProcess, 0); throw; } } } <commit_msg>* Remove comment from copypaste.<commit_after>// Copyright Joshua Boyce 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <[email protected]> #include "hadesmem/injector.hpp" #include <array> #include <iterator> #include <algorithm> #include "hadesmem/detail/warning_disable_prefix.hpp" #include <boost/filesystem.hpp> #include <boost/scope_exit.hpp> #include "hadesmem/detail/warning_disable_suffix.hpp" #include "hadesmem/call.hpp" #include "hadesmem/alloc.hpp" #include "hadesmem/error.hpp" #include "hadesmem/write.hpp" #include "hadesmem/module.hpp" #include "hadesmem/process.hpp" #include "hadesmem/detail/self_path.hpp" #include "hadesmem/detail/argv_quote.hpp" namespace hadesmem { HMODULE InjectDll(Process const& process, std::wstring const& path, int flags) { BOOST_ASSERT((flags & ~(InjectFlags::kInvalidFlagMaxValue - 1)) == 0); // Do not continue if Shim Engine is enabled for local process, // otherwise it could interfere with the address resolution. HMODULE const shim_eng_mod = GetModuleHandle(L"ShimEng.dll"); if (shim_eng_mod) { BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Shims enabled for local process.")); } boost::filesystem::path path_real(path); bool const path_resolution = !!(flags & InjectFlags::kPathResolution); if (path_resolution && path_real.is_relative()) { path_real = boost::filesystem::absolute(path_real, detail::GetSelfDirPath()); } path_real.make_preferred(); // Ensure target file exists // Note: Only performing this check when path resolution is enabled, // because otherwise we would need to perform the check in the context // of the remote process, which is not possible to do without // introducing race conditions and other potential problems. So we just // let LoadLibraryW do the check for us. if (path_resolution && !boost::filesystem::exists(path_real)) { BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Could not find module file.")); } std::wstring const path_string(path_real.native()); std::size_t const path_buf_size = (path_string.size() + 1) * sizeof(wchar_t); Allocator const lib_file_remote(&process, path_buf_size); WriteString(process, lib_file_remote.GetBase(), path_string); Module const kernel32_mod(&process, L"kernel32.dll"); LPCVOID const load_library = reinterpret_cast<LPCVOID>( reinterpret_cast<DWORD_PTR>(FindProcedure(kernel32_mod, "LoadLibraryW"))); typedef HMODULE (*LoadLibraryFuncT)(LPCWSTR lpFileName); std::pair<HMODULE, DWORD> const load_library_ret = Call<LoadLibraryFuncT>(process, load_library, CallConv::kWinApi, static_cast<LPCWSTR>(lib_file_remote.GetBase())); if (!load_library_ret.first) { BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Call to LoadLibraryW in remote process failed.") << ErrorCodeWinLast(load_library_ret.second)); } return load_library_ret.first; } void FreeDll(Process const& process, HMODULE module) { Module const kernel32_mod(&process, L"kernel32.dll"); LPCVOID const free_library = reinterpret_cast<LPCVOID>( reinterpret_cast<DWORD_PTR>(FindProcedure(kernel32_mod, "FreeLibrary"))); typedef BOOL (*FreeLibraryFuncT)(HMODULE hModule); std::pair<BOOL, DWORD> const free_library_ret = Call<FreeLibraryFuncT>(process, free_library, CallConv::kWinApi, module); if (!free_library_ret.first) { BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Call to FreeLibrary in remote process failed.") << ErrorCodeWinLast(free_library_ret.second)); } } // TODO: Configurable timeout. std::pair<DWORD_PTR, DWORD> CallExport(Process const& process, HMODULE module, std::string const& export_name, LPCVOID export_arg) { Module const module_remote(&process, module); LPCVOID const export_ptr = reinterpret_cast<LPCVOID>( reinterpret_cast<DWORD_PTR>(FindProcedure(module_remote, export_name))); return Call<DWORD_PTR(*)(LPCVOID)>(process, export_ptr, CallConv::kDefault, export_arg); } CreateAndInjectData::CreateAndInjectData(Process const& process, HMODULE module, DWORD_PTR export_ret, DWORD export_last_error) : process_(process), module_(module), export_ret_(export_ret), export_last_error_(export_last_error) { } CreateAndInjectData::CreateAndInjectData(CreateAndInjectData const& other) : process_(other.process_), module_(other.module_), export_ret_(other.export_ret_), export_last_error_(other.export_last_error_) { } CreateAndInjectData& CreateAndInjectData::operator=( CreateAndInjectData const& other) { process_ = other.process_; module_ = other.module_; export_ret_ = other.export_ret_; export_last_error_ = other.export_last_error_; return *this; } CreateAndInjectData::CreateAndInjectData(CreateAndInjectData&& other) BOOST_NOEXCEPT : process_(std::move(other.process_)), module_(other.module_), export_ret_(other.export_ret_), export_last_error_(other.export_last_error_) { other.module_ = nullptr; other.export_ret_ = 0; other.export_last_error_ = 0; } CreateAndInjectData& CreateAndInjectData::operator=( CreateAndInjectData&& other) BOOST_NOEXCEPT { process_ = std::move(other.process_); module_ = other.module_; other.module_ = nullptr; export_ret_ = other.export_ret_; other.export_ret_ = 0; export_last_error_ = other.export_last_error_; other.export_last_error_ = 0; return *this; } CreateAndInjectData::~CreateAndInjectData() { } Process CreateAndInjectData::GetProcess() const { return process_; } HMODULE CreateAndInjectData::GetModule() const BOOST_NOEXCEPT { return module_; } DWORD_PTR CreateAndInjectData::GetExportRet() const BOOST_NOEXCEPT { return export_ret_; } DWORD CreateAndInjectData::GetExportLastError() const BOOST_NOEXCEPT { return export_last_error_; } CreateAndInjectData CreateAndInject( std::wstring const& path, std::wstring const& work_dir, std::vector<std::wstring> const& args, std::wstring const& module, std::string const& export_name, LPCVOID export_arg, int flags) { boost::filesystem::path const path_real(path); std::wstring command_line; detail::ArgvQuote(&command_line, path_real.native(), false); std::for_each(std::begin(args), std::end(args), [&] (std::wstring const& arg) { command_line += L' '; detail::ArgvQuote(&command_line, arg, false); }); std::vector<wchar_t> proc_args(std::begin(command_line), std::end(command_line)); proc_args.push_back(L'\0'); boost::filesystem::path work_dir_real; if (!work_dir.empty()) { work_dir_real = work_dir; } else if (path_real.has_parent_path()) { work_dir_real = path_real.parent_path(); } else { work_dir_real = L"./"; } STARTUPINFO start_info; ZeroMemory(&start_info, sizeof(start_info)); start_info.cb = sizeof(start_info); PROCESS_INFORMATION proc_info; ZeroMemory(&proc_info, sizeof(proc_info)); if (!::CreateProcess(path_real.c_str(), proc_args.data(), nullptr, nullptr, FALSE, CREATE_SUSPENDED, nullptr, work_dir_real.c_str(), &start_info, &proc_info)) { DWORD const last_error = ::GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Could not create process.") << ErrorCodeWinLast(last_error)); } BOOST_SCOPE_EXIT_ALL(&) { // WARNING: Handle is leaked if CloseHandle fails. BOOST_VERIFY(::CloseHandle(proc_info.hProcess)); BOOST_VERIFY(::CloseHandle(proc_info.hThread)); }; try { Process const process(proc_info.dwProcessId); // This is used to generate a 'nullsub' function, which is called in // the context of the remote process in order to 'force' a call to // ntdll.dll!LdrInitializeThunk. This is necessary because module // enumeration will fail if LdrInitializeThunk has not been called, // and Injector::InjectDll (and the APIs it uses) depend on the // module enumeration APIs. #if defined(_M_AMD64) std::array<BYTE, 1> return_instr = { { 0xC3 } }; #elif defined(_M_IX86) std::array<BYTE, 3> return_instr = { { 0xC2, 0x04, 0x00 } }; #else #error "[HadesMem] Unsupported architecture." #endif Allocator const stub_remote(&process, sizeof(return_instr)); Write(process, stub_remote.GetBase(), return_instr); LPTHREAD_START_ROUTINE stub_remote_pfn = reinterpret_cast<LPTHREAD_START_ROUTINE>( reinterpret_cast<DWORD_PTR>(stub_remote.GetBase())); HANDLE const remote_thread = ::CreateRemoteThread(process.GetHandle(), nullptr, 0, stub_remote_pfn, nullptr, 0, nullptr); if (!remote_thread) { DWORD const last_error = ::GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Could not create remote thread.") << ErrorCodeWinLast(last_error)); } BOOST_SCOPE_EXIT_ALL(&) { // WARNING: Handle is leaked if CloseHandle fails. BOOST_VERIFY(::CloseHandle(remote_thread)); }; // TODO: Add a sensible timeout. if (::WaitForSingleObject(remote_thread, INFINITE) != WAIT_OBJECT_0) { DWORD const last_error = ::GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Could not wait for remote thread.") << ErrorCodeWinLast(last_error)); } HMODULE const remote_module = InjectDll(process, module, flags); std::pair<DWORD_PTR, DWORD> export_ret(0, 0); if (!export_name.empty()) { // TODO: Configurable timeout. export_ret = CallExport(process, remote_module, export_name, export_arg); } if (::ResumeThread(proc_info.hThread) == static_cast<DWORD>(-1)) { DWORD const last_error = ::GetLastError(); BOOST_THROW_EXCEPTION(HadesMemError() << ErrorString("Could not resume process.") << ErrorCodeWinLast(last_error) << ErrorCodeWinRet(export_ret.first) << ErrorCodeWinOther(export_ret.second)); } return CreateAndInjectData(process, remote_module, export_ret.first, export_ret.second); } catch (std::exception const& /*e*/) { // Terminate process if injection failed, otherwise the 'zombie' process // would be leaked. TerminateProcess(proc_info.hProcess, 0); throw; } } } <|endoftext|>
<commit_before> /* * Copyright 2016 The OpenMx Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "omxFitFunction.h" #include "Compute.h" #include "EnableWarnings.h" struct ssMLFitState : omxFitFunction { bool returnRowLikelihoods; bool populateRowDiagnostics; omxMatrix *cov; omxMatrix *smallRow; omxMatrix *contRow; omxMatrix *rowLikelihoods; omxMatrix *RCX; virtual ~ssMLFitState(); virtual void init(); virtual void compute(int ffcompute, FitContext *fc); virtual void populateAttr(SEXP algebra); }; void ssMLFitState::populateAttr(SEXP algebra) { ssMLFitState *argStruct = this; if(argStruct->populateRowDiagnostics){ SEXP rowLikelihoodsExt; omxMatrix *rowLikelihoodsInt = argStruct->rowLikelihoods; Rf_protect(rowLikelihoodsExt = Rf_allocVector(REALSXP, rowLikelihoodsInt->rows)); for(int row = 0; row < rowLikelihoodsInt->rows; row++) REAL(rowLikelihoodsExt)[row] = omxMatrixElement(rowLikelihoodsInt, row, 0); Rf_setAttrib(algebra, Rf_install("likelihoods"), rowLikelihoodsExt); } } void ssMLFitState::compute(int want, FitContext *fc) { if (want & (FF_COMPUTE_INITIAL_FIT | FF_COMPUTE_PREOPTIMIZE)) return; auto *oo = this; ssMLFitState *state = this; auto dataColumns = expectation->getDataColumns(); omxData *data = expectation->data; int rowcount = data->rows; omxSetExpectationComponent(expectation, "Reset", NULL); Eigen::VectorXi contRemove(cov->cols); for (int row=0; row < rowcount; ++row) { mxLogSetCurrentRow(row); omxDataRow(data, row, dataColumns, smallRow); omxSetExpectationComponent(expectation, "y", smallRow); expectation->loadDefVars(row); omxExpectationCompute(fc, expectation, NULL); int numCont = 0; for(int j = 0; j < dataColumns.size(); j++) { if (omxDataElementMissing(data, row, dataColumns[j])) { contRemove[j] = 1; } else { contRemove[j] = 0; ++numCont; } } if (!numCont) { omxSetMatrixElement(rowLikelihoods, row, 0, 1.0); continue; } omxMatrix *smallMeans = omxGetExpectationComponent(expectation, "means"); omxRemoveElements(smallMeans, contRemove.data()); omxMatrix *smallCov = omxGetExpectationComponent(expectation, "inverse"); if(OMX_DEBUG_ROWS(row)) { omxPrint(smallCov, "Inverse of Local Covariance Matrix in state space model"); } //Get covInfo from state space expectation int info = (int) omxGetExpectationComponent(expectation, "covInfo")->data[0]; if(info!=0) { EigenMatrixAdaptor Ecov(smallCov); if (Ecov.rows() > 50) { if (fc) fc->recordIterationError("%s: expected covariance matrix is " "not positive-definite in data row %d", oo->name(), row); } else { std::string empty = std::string(""); std::string buf = mxStringifyMatrix("covariance", Ecov, empty); if (fc) fc->recordIterationError("%s: expected covariance matrix is " "not positive-definite in data row %d; Details:\n%s", oo->name(), row, buf.c_str()); } omxSetMatrixElement(oo->matrix, 0, 0, NA_REAL); return; } double determinant = *omxGetExpectationComponent(expectation, "determinant")->data; if(OMX_DEBUG_ROWS(row)) { mxLog("0.5*log(det(Cov)) is: %3.3f", determinant);} omxCopyMatrix(contRow, smallRow); omxRemoveElements(contRow, contRemove.data()); // Reduce the row to just continuous. double minusoned = -1.0; int onei = 1; F77_CALL(daxpy)(&(contRow->cols), &minusoned, smallMeans->data, &onei, contRow->data, &onei); /* Calculate Row Likelihood */ /* Mathematically: (2*pi)^cols * 1/sqrt(determinant(ExpectedCov)) * (dataRow %*% (solve(ExpectedCov)) %*% t(dataRow))^(1/2) */ //EigenMatrixAdaptor EsmallCov(smallCov); //mxPrintMat("smallcov", EsmallCov); //omxPrint(contRow, "contRow"); double zerod = 0.0; char u = 'U'; double oned = 1.0; F77_CALL(dsymv)(&u, &(smallCov->rows), &oned, smallCov->data, &(smallCov->cols), contRow->data, &onei, &zerod, RCX->data, &onei); // RCX is the continuous-column mahalanobis distance. double Q = F77_CALL(ddot)(&(contRow->cols), contRow->data, &onei, RCX->data, &onei); double rowLikelihood = pow(2 * M_PI, -.5 * numCont) * (1.0/exp(determinant)) * exp(-.5 * Q); omxSetMatrixElement(rowLikelihoods, row, 0, rowLikelihood); } if (!state->returnRowLikelihoods) { double sum = 0.0; // floating-point addition is not associative, // so we serialized the following reduction operation. for(int i = 0; i < data->rows; i++) { double prob = omxVectorElement(state->rowLikelihoods, i); //mxLog("[%d] %g", i, -2.0 * log(prob)); sum += log(prob); } if(OMX_DEBUG) {mxLog("%s: total likelihood is %3.3f", oo->name(), sum);} omxSetMatrixElement(oo->matrix, 0, 0, -2.0 * sum); } else { omxCopyMatrix(oo->matrix, state->rowLikelihoods); } } ssMLFitState::~ssMLFitState() { ssMLFitState *state = this; omxFreeMatrix(state->smallRow); omxFreeMatrix(state->contRow); omxFreeMatrix(state->rowLikelihoods); } omxFitFunction *ssMLFitInit() { return new ssMLFitState; } void ssMLFitState::init() { auto *oo = this; auto *state = this; oo->openmpUser = false; oo->canDuplicate = true; state->returnRowLikelihoods = Rf_asInteger(R_do_slot(oo->rObj, Rf_install("vector"))); units = returnRowLikelihoods? FIT_UNITS_PROBABILITY : FIT_UNITS_MINUS2LL; state->populateRowDiagnostics = Rf_asInteger(R_do_slot(oo->rObj, Rf_install("rowDiagnostics"))); omxState *currentState = oo->matrix->currentState; state->rowLikelihoods = omxInitMatrix(expectation->data->rows, 1, TRUE, currentState); state->cov = omxGetExpectationComponent(expectation, "cov"); int covCols = state->cov->cols; state->smallRow = omxInitMatrix(1, covCols, TRUE, currentState); state->contRow = omxInitMatrix(covCols, 1, TRUE, currentState); state->RCX = omxInitMatrix(1, covCols, TRUE, currentState); } <commit_msg>Add runtime diagnostics for state space ML fit function<commit_after> /* * Copyright 2016 The OpenMx Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "omxFitFunction.h" #include "Compute.h" #include "EnableWarnings.h" struct ssMLFitState : omxFitFunction { int verbose; bool returnRowLikelihoods; bool populateRowDiagnostics; omxMatrix *cov; omxMatrix *smallRow; omxMatrix *contRow; omxMatrix *rowLikelihoods; omxMatrix *RCX; virtual ~ssMLFitState(); virtual void init(); virtual void compute(int ffcompute, FitContext *fc); virtual void populateAttr(SEXP algebra); }; void ssMLFitState::populateAttr(SEXP algebra) { ssMLFitState *argStruct = this; if(argStruct->populateRowDiagnostics){ SEXP rowLikelihoodsExt; omxMatrix *rowLikelihoodsInt = argStruct->rowLikelihoods; Rf_protect(rowLikelihoodsExt = Rf_allocVector(REALSXP, rowLikelihoodsInt->rows)); for(int row = 0; row < rowLikelihoodsInt->rows; row++) REAL(rowLikelihoodsExt)[row] = omxMatrixElement(rowLikelihoodsInt, row, 0); Rf_setAttrib(algebra, Rf_install("likelihoods"), rowLikelihoodsExt); } } void ssMLFitState::compute(int want, FitContext *fc) { if (want & (FF_COMPUTE_INITIAL_FIT | FF_COMPUTE_PREOPTIMIZE)) return; auto *oo = this; ssMLFitState *state = this; auto dataColumns = expectation->getDataColumns(); omxData *data = expectation->data; int rowcount = data->rows; omxSetExpectationComponent(expectation, "Reset", NULL); Eigen::VectorXi contRemove(cov->cols); for (int row=0; row < rowcount; ++row) { mxLogSetCurrentRow(row); omxDataRow(data, row, dataColumns, smallRow); if (verbose >= 2) { mxLog("row %d", row); omxPrint(smallRow, "row"); } omxSetExpectationComponent(expectation, "y", smallRow); expectation->loadDefVars(row); omxExpectationCompute(fc, expectation, NULL); int numCont = 0; for(int j = 0; j < dataColumns.size(); j++) { if (omxDataElementMissing(data, row, dataColumns[j])) { contRemove[j] = 1; } else { contRemove[j] = 0; ++numCont; } } if (!numCont) { omxSetMatrixElement(rowLikelihoods, row, 0, 1.0); continue; } omxMatrix *smallMeans = omxGetExpectationComponent(expectation, "means"); omxRemoveElements(smallMeans, contRemove.data()); omxMatrix *smallCov = omxGetExpectationComponent(expectation, "inverse"); if(OMX_DEBUG_ROWS(row)) { omxPrint(smallCov, "Inverse of Local Covariance Matrix in state space model"); } //Get covInfo from state space expectation int info = (int) omxGetExpectationComponent(expectation, "covInfo")->data[0]; if(info!=0) { EigenMatrixAdaptor Ecov(smallCov); if (Ecov.rows() > 50) { if (fc) fc->recordIterationError("%s: expected covariance matrix is " "not positive-definite in data row %d", oo->name(), row); } else { std::string empty = std::string(""); std::string buf = mxStringifyMatrix("covariance", Ecov, empty); if (fc) fc->recordIterationError("%s: expected covariance matrix is " "not positive-definite in data row %d; Details:\n%s", oo->name(), row, buf.c_str()); } omxSetMatrixElement(oo->matrix, 0, 0, NA_REAL); return; } double determinant = *omxGetExpectationComponent(expectation, "determinant")->data; if(OMX_DEBUG_ROWS(row)) { mxLog("0.5*log(det(Cov)) is: %3.3f", determinant);} omxCopyMatrix(contRow, smallRow); omxRemoveElements(contRow, contRemove.data()); // Reduce the row to just continuous. if (verbose >= 2) { omxPrint(contRow, "contRow"); omxPrint(smallMeans, "smallMeans"); } double minusoned = -1.0; int onei = 1; F77_CALL(daxpy)(&(contRow->cols), &minusoned, smallMeans->data, &onei, contRow->data, &onei); /* Calculate Row Likelihood */ /* Mathematically: (2*pi)^cols * 1/sqrt(determinant(ExpectedCov)) * (dataRow %*% (solve(ExpectedCov)) %*% t(dataRow))^(1/2) */ double zerod = 0.0; char u = 'U'; double oned = 1.0; F77_CALL(dsymv)(&u, &(smallCov->rows), &oned, smallCov->data, &(smallCov->cols), contRow->data, &onei, &zerod, RCX->data, &onei); // RCX is the continuous-column mahalanobis distance. double Q = F77_CALL(ddot)(&(contRow->cols), contRow->data, &onei, RCX->data, &onei); if (verbose >= 2) { EigenMatrixAdaptor EsmallCov(smallCov); EsmallCov.derived() = EsmallCov.selfadjointView<Eigen::Upper>(); mxPrintMat("smallcov", EsmallCov); omxPrint(contRow, "contRow"); mxLog("Q=%f", Q); } double rowLikelihood = pow(2 * M_PI, -.5 * numCont) * (1.0/exp(determinant)) * exp(-.5 * Q); omxSetMatrixElement(rowLikelihoods, row, 0, rowLikelihood); } if (!state->returnRowLikelihoods) { double sum = 0.0; // floating-point addition is not associative, // so we serialized the following reduction operation. for(int i = 0; i < data->rows; i++) { double prob = omxVectorElement(state->rowLikelihoods, i); //mxLog("[%d] %g", i, -2.0 * log(prob)); sum += log(prob); } if(OMX_DEBUG) {mxLog("%s: total likelihood is %3.3f", oo->name(), sum);} omxSetMatrixElement(oo->matrix, 0, 0, -2.0 * sum); } else { omxCopyMatrix(oo->matrix, state->rowLikelihoods); } } ssMLFitState::~ssMLFitState() { ssMLFitState *state = this; omxFreeMatrix(state->smallRow); omxFreeMatrix(state->contRow); omxFreeMatrix(state->rowLikelihoods); } omxFitFunction *ssMLFitInit() { return new ssMLFitState; } void ssMLFitState::init() { auto *oo = this; auto *state = this; oo->openmpUser = false; oo->canDuplicate = true; ProtectedSEXP Rverbose(R_do_slot(rObj, Rf_install("verbose"))); verbose = Rf_asInteger(Rverbose); state->returnRowLikelihoods = Rf_asInteger(R_do_slot(oo->rObj, Rf_install("vector"))); units = returnRowLikelihoods? FIT_UNITS_PROBABILITY : FIT_UNITS_MINUS2LL; state->populateRowDiagnostics = Rf_asInteger(R_do_slot(oo->rObj, Rf_install("rowDiagnostics"))); omxState *currentState = oo->matrix->currentState; state->rowLikelihoods = omxInitMatrix(expectation->data->rows, 1, TRUE, currentState); state->cov = omxGetExpectationComponent(expectation, "cov"); int covCols = state->cov->cols; state->smallRow = omxInitMatrix(1, covCols, TRUE, currentState); state->contRow = omxInitMatrix(covCols, 1, TRUE, currentState); state->RCX = omxInitMatrix(1, covCols, TRUE, currentState); } <|endoftext|>
<commit_before>#include "lua_shape.h" #include "lua_context.h" #include "lua_check.h" #include "core/logging.h" namespace bones { static const char * kMetaTableShape = "__mt_shape"; static const char * kMethodSetStroke = "setStroke"; static const char * kMethodsetStrokeEffect = "setStrokeEffect"; static const char * kMethodsetStrokeWidth = "setStrokeWidth"; static const char * kMethodsetColor = "setColor"; static const char * kMethodsetBorder = "setBorder"; static const char * kMethodsetCircle = "setCircle"; static const char * kMethodsetRect = "setRect"; static const char * kMethodsetLine = "setLine"; static const char * kMethodsetPoint = "setPoint"; static int SetStroke(lua_State * l) { lua_settop(l, 2); lua_pushnil(l); lua_copy(l, 1, -1); LuaShape * shape = static_cast<LuaShape *>( LuaContext::CallGetCObject(l)); if (shape) shape->setStroke(!!(lua_toboolean(l, 2))); return 0; } static int SetColor(lua_State * l) { lua_settop(l, 2); lua_pushnil(l); lua_copy(l, 1, -1); LuaShape * shape = static_cast<LuaShape *>( LuaContext::CallGetCObject(l)); if (shape) { if (lua_isinteger(l, 2)) shape->setColor(static_cast<BonesColor>(lua_tointeger(l, 2))); } return 0; } static int SetRect(lua_State * l) {//(self, rx, ry, l, t, r, b) || (self) auto count = lua_gettop(l); lua_settop(l, 7); lua_pushnil(l); lua_copy(l, 1, -1); LuaShape * shape = static_cast<LuaShape *>( LuaContext::CallGetCObject(l)); if (shape) { if (count == 1) shape->setRect(0, 0, nullptr); else if (count == 3) shape->setRect( static_cast<BonesScalar>(lua_tonumber(l, 2)), static_cast<BonesScalar>(lua_tonumber(l, 3)), nullptr); else { BonesRect rect = { static_cast<BonesScalar>(lua_tonumber(l, 4)), static_cast<BonesScalar>(lua_tonumber(l, 5)), static_cast<BonesScalar>(lua_tonumber(l, 6)), static_cast<BonesScalar>(lua_tonumber(l, 7)) }; shape->setRect( static_cast<BonesScalar>(lua_tonumber(l, 2)), static_cast<BonesScalar>(lua_tonumber(l, 3)), &rect); } } return 0; } LuaShape::LuaShape(Shape * co) :LuaObject(co), notify_(nullptr) { LUA_HANDLER_INIT(); createLuaTable(); } void LuaShape::createMetaTable(lua_State * l) { if (!LuaObject::createMetaTable(l, kMetaTableShape)) { lua_pushcfunction(l, &SetStroke); lua_setfield(l, -2, kMethodSetStroke); lua_pushcfunction(l, &SetRect); lua_setfield(l, -2, kMethodsetRect); lua_pushcfunction(l, &SetColor); lua_setfield(l, -2, kMethodsetColor); } } void LuaShape::setStroke(bool stroke) { object_->setStyle(stroke ? Shape::kStroke : Shape::kFill); } void LuaShape::setStrokeEffect(size_t count, BonesScalar * intervals, BonesScalar offset) { auto effect = Core::createDashEffect(count, intervals, offset); object_->setStrokeEffect(effect); Core::destroyEffect(effect); } void LuaShape::setStrokeWidth(BonesScalar stroke_width) { object_->setStrokeWidth(stroke_width); } void LuaShape::setColor(BonesColor color) { object_->setColor(color); } void LuaShape::setColor(BonesShader shader) { object_->setShader(static_cast<SkShader *>(shader)); } void LuaShape::setCircle(const BonesPoint & center, BonesScalar radius) { Point p; p.set(center.x, center.y); object_->set(p, radius); } void LuaShape::setRect(BonesScalar rx, BonesScalar ry, const BonesRect * rect) { Rect * r = nullptr; Rect re; if (rect) { re.setLTRB(rect->left, rect->top, rect->right, rect->bottom); r = &re; } object_->set(rx, ry, r); } void LuaShape::setLine(const BonesPoint & start, const BonesPoint & end) { Point pts, pte; pts.set(start.x, start.y); pte.set(end.x, end.y); object_->set(pts, pte); } void LuaShape::setPoint(const BonesPoint & pt) { Point p; p.set(pt.x, pt.y); object_->set(p); } void LuaShape::setOval(const BonesRect * oval) { Rect * r = nullptr; Rect re; if (oval) { re.setLTRB(oval->left, oval->top, oval->right, oval->bottom); r = &re; } object_->set(r); } void LuaShape::setArc( BonesScalar start, BonesScalar sweep, bool use_center, const BonesRect * oval) { Rect * r = nullptr; Rect re; if (oval) { re.setLTRB(oval->left, oval->top, oval->right, oval->bottom); r = &re; } object_->set(r, start, sweep, use_center); } } <commit_msg>Update LuaShape<commit_after>#include "lua_shape.h" #include "lua_context.h" #include "lua_check.h" #include "core/logging.h" namespace bones { static const char * kMetaTableShape = "__mt_shape"; static const char * kMethodSetStroke = "setStroke"; static const char * kMethodsetStrokeEffect = "setStrokeEffect"; static const char * kMethodsetStrokeWidth = "setStrokeWidth"; static const char * kMethodsetColor = "setColor"; static const char * kMethodsetCircle = "setCircle"; static const char * kMethodsetRect = "setRect"; static const char * kMethodsetLine = "setLine"; static const char * kMethodsetPoint = "setPoint"; static const char * kMethodsetOval = "setOval"; static const char * kMethodsetArc = "setArc"; static int SetStroke(lua_State * l) { lua_settop(l, 2); lua_pushnil(l); lua_copy(l, 1, -1); LuaShape * shape = static_cast<LuaShape *>( LuaContext::CallGetCObject(l)); if (shape) shape->setStroke(!!(lua_toboolean(l, 2))); return 0; } static int SetStrokeEffect(lua_State * l) { auto count = lua_gettop(l); if (count > 2) { auto intervals_count = static_cast<size_t>(lua_tointeger(l, 2)); lua_settop(l, intervals_count + 3); lua_pushnil(l); lua_copy(l, 1, -1); LuaShape * shape = static_cast<LuaShape *>( LuaContext::CallGetCObject(l)); if (shape) { std::vector<BonesScalar> intervals; for (size_t i = 1; i <= intervals_count; ++i) intervals.push_back(static_cast<BonesScalar>(lua_tonumber(l, 2 + i))); shape->setStrokeEffect(intervals_count, &intervals[0], static_cast<BonesScalar>(lua_tonumber(l, 3 + intervals_count))); } } return 0; } static int SetStrokeWidth(lua_State * l) { lua_settop(l, 2); lua_pushnil(l); lua_copy(l, 1, -1); LuaShape * shape = static_cast<LuaShape *>( LuaContext::CallGetCObject(l)); if (shape) shape->setStrokeWidth(static_cast<BonesScalar>(lua_tonumber(l, 2))); return 0; } static int SetColor(lua_State * l) { lua_settop(l, 2); lua_pushnil(l); lua_copy(l, 1, -1); LuaShape * shape = static_cast<LuaShape *>( LuaContext::CallGetCObject(l)); if (shape) { if (lua_isinteger(l, 2)) shape->setColor(static_cast<BonesColor>(lua_tointeger(l, 2))); else if (lua_islightuserdata(l, 2)) shape->setColor(static_cast<BonesShader>(lua_touserdata(l, 2))); } return 0; } static int SetCircle(lua_State * l) { lua_settop(l, 4); lua_pushnil(l); lua_copy(l, 1, -1); LuaShape * shape = static_cast<LuaShape *>( LuaContext::CallGetCObject(l)); if (shape) { BonesPoint center = { static_cast<BonesScalar>(lua_tonumber(l, 2)), static_cast<BonesScalar>(lua_tonumber(l, 3)) }; shape->setCircle(center, static_cast<BonesScalar>(lua_tonumber(l, 4))); } return 0; } static int SetRect(lua_State * l) {//(self, rx, ry, l, t, r, b) || (self) auto count = lua_gettop(l); lua_settop(l, 7); lua_pushnil(l); lua_copy(l, 1, -1); LuaShape * shape = static_cast<LuaShape *>( LuaContext::CallGetCObject(l)); if (shape) { if (count == 1) shape->setRect(0, 0, nullptr); else if (count == 3) shape->setRect( static_cast<BonesScalar>(lua_tonumber(l, 2)), static_cast<BonesScalar>(lua_tonumber(l, 3)), nullptr); else { BonesRect rect = { static_cast<BonesScalar>(lua_tonumber(l, 4)), static_cast<BonesScalar>(lua_tonumber(l, 5)), static_cast<BonesScalar>(lua_tonumber(l, 6)), static_cast<BonesScalar>(lua_tonumber(l, 7)) }; shape->setRect( static_cast<BonesScalar>(lua_tonumber(l, 2)), static_cast<BonesScalar>(lua_tonumber(l, 3)), &rect); } } return 0; } static int SetLine(lua_State * l) { lua_settop(l, 5); lua_pushnil(l); lua_copy(l, 1, -1); LuaShape * shape = static_cast<LuaShape *>( LuaContext::CallGetCObject(l)); if (shape) { BonesPoint start = { static_cast<BonesScalar>(lua_tonumber(l, 2)), static_cast<BonesScalar>(lua_tonumber(l, 3)) }; BonesPoint end = { static_cast<BonesScalar>(lua_tonumber(l, 4)), static_cast<BonesScalar>(lua_tonumber(l, 5)) }; shape->setLine(start, end); } return 0; } static int SetPoint(lua_State * l) { lua_settop(l, 3); lua_pushnil(l); lua_copy(l, 1, -1); LuaShape * shape = static_cast<LuaShape *>( LuaContext::CallGetCObject(l)); if (shape) { BonesPoint pt = { static_cast<BonesScalar>(lua_tonumber(l, 2)), static_cast<BonesScalar>(lua_tonumber(l, 3)) }; shape->setPoint(pt); } return 0; } static int SetOval(lua_State * l) { auto count = lua_gettop(l); lua_settop(l, 5); lua_pushnil(l); lua_copy(l, 1, -1); LuaShape * shape = static_cast<LuaShape *>( LuaContext::CallGetCObject(l)); if (shape) { if (count == 1) shape->setOval(nullptr); else { BonesRect oval = { static_cast<BonesScalar>(lua_tonumber(l, 2)), static_cast<BonesScalar>(lua_tonumber(l, 3)), static_cast<BonesScalar>(lua_tonumber(l, 4)), static_cast<BonesScalar>(lua_tonumber(l, 5)) }; shape->setOval(&oval); } } return 0; } static int SetArc(lua_State * l) { auto count = lua_gettop(l); lua_settop(l, 8); lua_pushnil(l); lua_copy(l, 1, -1); LuaShape * shape = static_cast<LuaShape *>( LuaContext::CallGetCObject(l)); if (shape) { auto start = static_cast<BonesScalar>(lua_tonumber(l, 2)); auto sweep = static_cast<BonesScalar>(lua_tonumber(l, 3)); auto center = !!lua_toboolean(l, 4); if (count == 4) shape->setArc(start, sweep, center, nullptr); else { BonesRect oval = { static_cast<BonesScalar>(lua_tonumber(l, 5)), static_cast<BonesScalar>(lua_tonumber(l, 6)), static_cast<BonesScalar>(lua_tonumber(l, 7)), static_cast<BonesScalar>(lua_tonumber(l, 8)) }; shape->setArc(start, sweep, center, &oval); } } return 0; } LuaShape::LuaShape(Shape * co) :LuaObject(co), notify_(nullptr) { LUA_HANDLER_INIT(); createLuaTable(); } void LuaShape::createMetaTable(lua_State * l) { if (!LuaObject::createMetaTable(l, kMetaTableShape)) { lua_pushcfunction(l, &SetStroke); lua_setfield(l, -2, kMethodSetStroke); lua_pushcfunction(l, &SetStrokeEffect); lua_setfield(l, -2, kMethodsetStrokeEffect); lua_pushcfunction(l, &SetStrokeWidth); lua_setfield(l, -2, kMethodsetStrokeWidth); lua_pushcfunction(l, &SetColor); lua_setfield(l, -2, kMethodsetColor); lua_pushcfunction(l, &SetCircle); lua_setfield(l, -2, kMethodsetCircle); lua_pushcfunction(l, &SetRect); lua_setfield(l, -2, kMethodsetRect); lua_pushcfunction(l, &SetLine); lua_setfield(l, -2, kMethodsetLine); lua_pushcfunction(l, &SetPoint); lua_setfield(l, -2, kMethodsetPoint); lua_pushcfunction(l, &SetOval); lua_setfield(l, -2, kMethodsetOval); lua_pushcfunction(l, &SetArc); lua_setfield(l, -2, kMethodsetArc); } } void LuaShape::setStroke(bool stroke) { object_->setStyle(stroke ? Shape::kStroke : Shape::kFill); } void LuaShape::setStrokeEffect(size_t count, BonesScalar * intervals, BonesScalar offset) { auto effect = Core::createDashEffect(count, intervals, offset); object_->setStrokeEffect(effect); Core::destroyEffect(effect); } void LuaShape::setStrokeWidth(BonesScalar stroke_width) { object_->setStrokeWidth(stroke_width); } void LuaShape::setColor(BonesColor color) { object_->setColor(color); } void LuaShape::setColor(BonesShader shader) { object_->setShader(static_cast<SkShader *>(shader)); } void LuaShape::setCircle(const BonesPoint & center, BonesScalar radius) { Point p; p.set(center.x, center.y); object_->set(p, radius); } void LuaShape::setRect(BonesScalar rx, BonesScalar ry, const BonesRect * rect) { Rect * r = nullptr; Rect re; if (rect) { re.setLTRB(rect->left, rect->top, rect->right, rect->bottom); r = &re; } object_->set(rx, ry, r); } void LuaShape::setLine(const BonesPoint & start, const BonesPoint & end) { Point pts, pte; pts.set(start.x, start.y); pte.set(end.x, end.y); object_->set(pts, pte); } void LuaShape::setPoint(const BonesPoint & pt) { Point p; p.set(pt.x, pt.y); object_->set(p); } void LuaShape::setOval(const BonesRect * oval) { Rect * r = nullptr; Rect re; if (oval) { re.setLTRB(oval->left, oval->top, oval->right, oval->bottom); r = &re; } object_->set(r); } void LuaShape::setArc( BonesScalar start, BonesScalar sweep, bool use_center, const BonesRect * oval) { Rect * r = nullptr; Rect re; if (oval) { re.setLTRB(oval->left, oval->top, oval->right, oval->bottom); r = &re; } object_->set(r, start, sweep, use_center); } } <|endoftext|>
<commit_before>//===-- ManagedStatic.cpp - Static Global wrapper -------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Chris Lattner and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the ManagedStatic class and llvm_shutdown(). // //===----------------------------------------------------------------------===// #include "llvm/Support/ManagedStatic.h" #include <cassert> using namespace llvm; static const ManagedStaticBase *StaticList = 0; void ManagedStaticBase::RegisterManagedStatic(void *ObjPtr, void (*Deleter)(void*)) const { assert(Ptr == 0 && DeleterFn == 0 && Next == 0 && "Partially init static?"); Ptr = ObjPtr; DeleterFn = Deleter; // Add to list of managed statics. Next = StaticList; StaticList = this; } void ManagedStaticBase::destroy() const { assert(Ptr && DeleterFn && "ManagedStatic not initialized correctly!"); assert(StaticList == this && "Not destroyed in reverse order of construction?"); // Unlink from list. StaticList = Next; Next = 0; // Destroy memory. DeleterFn(Ptr); // Cleanup. Ptr = 0; DeleterFn = 0; } /// llvm_shutdown - Deallocate and destroy all ManagedStatic variables. void llvm_shutdown() { while (StaticList) StaticList->destroy(); } <commit_msg>Define this in the correct n/s<commit_after>//===-- ManagedStatic.cpp - Static Global wrapper -------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Chris Lattner and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the ManagedStatic class and llvm_shutdown(). // //===----------------------------------------------------------------------===// #include "llvm/Support/ManagedStatic.h" #include <cassert> using namespace llvm; static const ManagedStaticBase *StaticList = 0; void ManagedStaticBase::RegisterManagedStatic(void *ObjPtr, void (*Deleter)(void*)) const { assert(Ptr == 0 && DeleterFn == 0 && Next == 0 && "Partially init static?"); Ptr = ObjPtr; DeleterFn = Deleter; // Add to list of managed statics. Next = StaticList; StaticList = this; } void ManagedStaticBase::destroy() const { assert(Ptr && DeleterFn && "ManagedStatic not initialized correctly!"); assert(StaticList == this && "Not destroyed in reverse order of construction?"); // Unlink from list. StaticList = Next; Next = 0; // Destroy memory. DeleterFn(Ptr); // Cleanup. Ptr = 0; DeleterFn = 0; } /// llvm_shutdown - Deallocate and destroy all ManagedStatic variables. void llvm::llvm_shutdown() { while (StaticList) StaticList->destroy(); } <|endoftext|>
<commit_before>#ifndef TILEPLUGIN_HPP #define TILEPLUGIN_HPP #include "engine/plugins/plugin_base.hpp" #include "osrm/json_container.hpp" #include "util/tile_bbox.hpp" #include <protozero/varint.hpp> #include <protozero/pbf_writer.hpp> #include <string> #include <cmath> /* * This plugin generates Mapbox Vector tiles that show the internal * routing geometry and speed values on all road segments. * You can use this along with a vector-tile viewer, like Mapbox GL, * to display maps that show the exact road network that * OSRM is routing. This is very useful for debugging routing * errors */ namespace osrm { namespace engine { namespace plugins { // from mapnik/well_known_srs.hpp static const double EARTH_RADIUS = 6378137.0; static const double EARTH_DIAMETER = EARTH_RADIUS * 2.0; static const double EARTH_CIRCUMFERENCE = EARTH_DIAMETER * M_PI; static const double MAXEXTENT = EARTH_CIRCUMFERENCE / 2.0; static const double M_PI_by2 = M_PI / 2; static const double D2R = M_PI / 180; static const double R2D = 180 / M_PI; static const double M_PIby360 = M_PI / 360; static const double MAXEXTENTby180 = MAXEXTENT / 180; static const double MAX_LATITUDE = R2D * (2 * std::atan(std::exp(180 * D2R)) - M_PI_by2); // from mapnik-vector-tile namespace detail_pbf { inline unsigned encode_length(unsigned len) { return (len << 3u) | 2u; } } inline void lonlat2merc(double & x, double & y) { if (x > 180) x = 180; else if (x < -180) x = -180; if (y > MAX_LATITUDE) y = MAX_LATITUDE; else if (y < -MAX_LATITUDE) y = -MAX_LATITUDE; x = x * MAXEXTENTby180; y = std::log(std::tan((90 + y) * M_PIby360)) * R2D; y = y * MAXEXTENTby180; } const static int tile_size_ = 256; void from_pixels(double shift, double & x, double & y) { double b = shift/2.0; x = (x - b)/(shift/360.0); double g = (y - b)/-(shift/(2 * M_PI)); y = R2D * (2.0 * std::atan(std::exp(g)) - M_PI_by2); } void xyz(int x, int y, int z, double & minx, double & miny, double & maxx, double & maxy) { minx = x * tile_size_; miny = (y + 1.0) * tile_size_; maxx = (x + 1.0) * tile_size_; maxy = y * tile_size_; double shift = std::pow(2.0,z) * tile_size_; from_pixels(shift,minx,miny); from_pixels(shift,maxx,maxy); lonlat2merc(minx,miny); lonlat2merc(maxx,maxy); } void xyz2wsg84(int x, int y, int z, double & minx, double & miny, double & maxx, double & maxy) { minx = x * tile_size_; miny = (y + 1.0) * tile_size_; maxx = (x + 1.0) * tile_size_; maxy = y * tile_size_; double shift = std::pow(2.0,z) * tile_size_; from_pixels(shift,minx,miny); from_pixels(shift,maxx,maxy); } // emulates mapbox::box2d class bbox { public: double minx; double miny; double maxx; double maxy; bbox(double _minx,double _miny,double _maxx,double _maxy) : minx(_minx), miny(_miny), maxx(_maxx), maxy(_maxy) { } double width() const { return maxx - minx; } double height() const { return maxy - miny; } }; // should start using core geometry class across mapnik, osrm, mapbox-gl-native class point_type_d { public: double x; double y; point_type_d(double _x, double _y) : x(_x), y(_y) { } }; class point_type_i { public: std::int64_t x; std::int64_t y; point_type_i(std::int64_t _x, std::int64_t _y) : x(_x), y(_y) { } }; using line_type = std::vector<point_type_i>; using line_typed = std::vector<point_type_d>; // from mapnik-vector-tile inline bool encode_linestring(line_type line, protozero::packed_field_uint32 & geometry, int32_t & start_x, int32_t & start_y) { std::size_t line_size = line.size(); //line_size -= detail_pbf::repeated_point_count(line); if (line_size < 2) { return false; } unsigned line_to_length = static_cast<unsigned>(line_size) - 1; auto pt = line.begin(); geometry.add_element(9); // move_to | (1 << 3) geometry.add_element(protozero::encode_zigzag32(pt->x - start_x)); geometry.add_element(protozero::encode_zigzag32(pt->y - start_y)); start_x = pt->x; start_y = pt->y; geometry.add_element(detail_pbf::encode_length(line_to_length)); for (++pt; pt != line.end(); ++pt) { int32_t dx = pt->x - start_x; int32_t dy = pt->y - start_y; /*if (dx == 0 && dy == 0) { continue; }*/ geometry.add_element(protozero::encode_zigzag32(dx)); geometry.add_element(protozero::encode_zigzag32(dy)); start_x = pt->x; start_y = pt->y; } return true; } template <class DataFacadeT> class TilePlugin final : public BasePlugin { public: explicit TilePlugin(DataFacadeT *facade) : facade(facade), descriptor_string("tile") {} const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &route_parameters, util::json::Object &json_result) override final { const unsigned tile_extent = 4096; double min_lon, min_lat, max_lon, max_lat; xyz2wsg84(route_parameters.x, route_parameters.y, route_parameters.z, min_lon, min_lat, max_lon, max_lat); FixedPointCoordinate southwest = { static_cast<int32_t>(min_lat * COORDINATE_PRECISION), static_cast<int32_t>(min_lon * COORDINATE_PRECISION) }; FixedPointCoordinate northeast = { static_cast<int32_t>(max_lat * COORDINATE_PRECISION), static_cast<int32_t>(max_lon * COORDINATE_PRECISION) }; auto edges = facade->GetEdgesInBox(southwest, northeast); xyz(route_parameters.x, route_parameters.y, route_parameters.z, min_lon, min_lat, max_lon, max_lat); bbox tile_bbox(min_lon, min_lat, max_lon, max_lat); std::string buffer; protozero::pbf_writer tile_writer(buffer); { protozero::pbf_writer layer_writer(tile_writer,3); // TODO: don't write a layer if there are no features layer_writer.add_uint32(15,2); // version layer_writer.add_string(1,"speeds"); // name layer_writer.add_uint32(5,4096); // extent std::vector<double> speeds; std::vector<bool> is_smalls; { unsigned id = 1; for (const auto & edge : edges) { const auto a = facade->GetCoordinateOfNode(edge.u); const auto b = facade->GetCoordinateOfNode(edge.v); double length = osrm::util::coordinate_calculation::haversineDistance( a.lon, a.lat, b.lon, b.lat ); if (edge.forward_weight != 0 && edge.forward_edge_based_node_id != SPECIAL_NODEID) { std::int32_t start_x = 0; std::int32_t start_y = 0; line_typed geo_line; geo_line.emplace_back(a.lon / COORDINATE_PRECISION, a.lat / COORDINATE_PRECISION); geo_line.emplace_back(b.lon / COORDINATE_PRECISION, b.lat / COORDINATE_PRECISION); double speed = round(length / edge.forward_weight * 10 ) * 3.6; speeds.push_back(speed); is_smalls.push_back(edge.component.is_tiny); line_type tile_line; for (auto const & pt : geo_line) { double px_merc = pt.x; double py_merc = pt.y; lonlat2merc(px_merc,py_merc); // convert to integer tile coordinat std::int64_t px = std::round((px_merc - tile_bbox.minx) * tile_extent/16 / tile_bbox.width()); std::int64_t py = std::round((tile_bbox.maxy - py_merc) * tile_extent/16 / tile_bbox.height()); tile_line.emplace_back(px*tile_extent/256,py*tile_extent/256); } protozero::pbf_writer feature_writer(layer_writer,2); feature_writer.add_enum(3,2); // geometry type feature_writer.add_uint64(1,id++); // id { protozero::packed_field_uint32 field(feature_writer, 2); field.add_element(0); // "speed" tag key offset field.add_element((speeds.size()-1)*2); // "speed" tag value offset field.add_element(1); // "is_small" tag key offset field.add_element((is_smalls.size()-1)*2+1); // "is_small" tag value offset } { protozero::packed_field_uint32 geometry(feature_writer,4); encode_linestring(tile_line,geometry,start_x,start_y); } } if (edge.reverse_weight != 0 && edge.reverse_edge_based_node_id != SPECIAL_NODEID) { std::int32_t start_x = 0; std::int32_t start_y = 0; line_typed geo_line; geo_line.emplace_back(b.lon / COORDINATE_PRECISION, b.lat / COORDINATE_PRECISION); geo_line.emplace_back(a.lon / COORDINATE_PRECISION, a.lat / COORDINATE_PRECISION); double speed = round(length / edge.reverse_weight * 10 ) * 3.6; speeds.push_back(speed); is_smalls.push_back(edge.component.is_tiny); line_type tile_line; for (auto const & pt : geo_line) { double px_merc = pt.x; double py_merc = pt.y; lonlat2merc(px_merc,py_merc); // convert to integer tile coordinat std::int64_t px = std::round((px_merc - tile_bbox.minx) * tile_extent/16 / tile_bbox.width()); std::int64_t py = std::round((tile_bbox.maxy - py_merc) * tile_extent/16 / tile_bbox.height()); tile_line.emplace_back(px*tile_extent/256,py*tile_extent/256); } protozero::pbf_writer feature_writer(layer_writer,2); feature_writer.add_enum(3,2); // geometry type feature_writer.add_uint64(1,id++); // id { protozero::packed_field_uint32 field(feature_writer, 2); field.add_element(0); // "speed" tag key offset field.add_element((speeds.size()-1)*2); // "speed" tag value offset field.add_element(1); // "is_small" tag key offset field.add_element((is_smalls.size()-1)*2+1); // "is_small" tag value offset } { protozero::packed_field_uint32 geometry(feature_writer,4); encode_linestring(tile_line,geometry,start_x,start_y); } } } } layer_writer.add_string(3,"speed"); layer_writer.add_string(3,"is_small"); for (size_t i=0; i<speeds.size(); i++) { { protozero::pbf_writer values_writer(layer_writer,4); values_writer.add_double(3, speeds[i]); } { protozero::pbf_writer values_writer(layer_writer,4); values_writer.add_bool(7, is_smalls[i]); } } } json_result.values["pbf"] = osrm::util::json::Buffer(buffer); return Status::Ok; } private: DataFacadeT *facade; std::string descriptor_string; }; } } } #endif /* TILEPLUGIN_HPP */ <commit_msg>Don't round until necessary, this keeps coordinates in much better positions.<commit_after>#ifndef TILEPLUGIN_HPP #define TILEPLUGIN_HPP #include "engine/plugins/plugin_base.hpp" #include "osrm/json_container.hpp" #include "util/tile_bbox.hpp" #include <protozero/varint.hpp> #include <protozero/pbf_writer.hpp> #include <string> #include <cmath> /* * This plugin generates Mapbox Vector tiles that show the internal * routing geometry and speed values on all road segments. * You can use this along with a vector-tile viewer, like Mapbox GL, * to display maps that show the exact road network that * OSRM is routing. This is very useful for debugging routing * errors */ namespace osrm { namespace engine { namespace plugins { // from mapnik/well_known_srs.hpp static const double EARTH_RADIUS = 6378137.0; static const double EARTH_DIAMETER = EARTH_RADIUS * 2.0; static const double EARTH_CIRCUMFERENCE = EARTH_DIAMETER * M_PI; static const double MAXEXTENT = EARTH_CIRCUMFERENCE / 2.0; static const double M_PI_by2 = M_PI / 2.0; static const double D2R = M_PI / 180.0; static const double R2D = 180.0 / M_PI; static const double M_PIby360 = M_PI / 360.0; static const double MAXEXTENTby180 = MAXEXTENT / 180.0; static const double MAX_LATITUDE = R2D * (2.0 * std::atan(std::exp(180.0 * D2R)) - M_PI_by2); // from mapnik-vector-tile namespace detail_pbf { inline unsigned encode_length(unsigned len) { return (len << 3u) | 2u; } } inline void lonlat2merc(double & x, double & y) { if (x > 180) x = 180; else if (x < -180) x = -180; if (y > MAX_LATITUDE) y = MAX_LATITUDE; else if (y < -MAX_LATITUDE) y = -MAX_LATITUDE; x = x * MAXEXTENTby180; y = std::log(std::tan((90 + y) * M_PIby360)) * R2D; y = y * MAXEXTENTby180; } const static double tile_size_ = 256.0; void from_pixels(double shift, double & x, double & y) { double b = shift/2.0; x = (x - b)/(shift/360.0); double g = (y - b)/-(shift/(2 * M_PI)); y = R2D * (2.0 * std::atan(std::exp(g)) - M_PI_by2); } void xyz(int x, int y, int z, double & minx, double & miny, double & maxx, double & maxy) { minx = x * tile_size_; miny = (y + 1.0) * tile_size_; maxx = (x + 1.0) * tile_size_; maxy = y * tile_size_; double shift = std::pow(2.0,z) * tile_size_; from_pixels(shift,minx,miny); from_pixels(shift,maxx,maxy); lonlat2merc(minx,miny); lonlat2merc(maxx,maxy); } void xyz2wsg84(int x, int y, int z, double & minx, double & miny, double & maxx, double & maxy) { minx = x * tile_size_; miny = (y + 1.0) * tile_size_; maxx = (x + 1.0) * tile_size_; maxy = y * tile_size_; double shift = std::pow(2.0,z) * tile_size_; from_pixels(shift,minx,miny); from_pixels(shift,maxx,maxy); } // emulates mapbox::box2d class bbox { public: double minx; double miny; double maxx; double maxy; bbox(double _minx,double _miny,double _maxx,double _maxy) : minx(_minx), miny(_miny), maxx(_maxx), maxy(_maxy) { } double width() const { return maxx - minx; } double height() const { return maxy - miny; } }; // should start using core geometry class across mapnik, osrm, mapbox-gl-native class point_type_d { public: double x; double y; point_type_d(double _x, double _y) : x(_x), y(_y) { } }; class point_type_i { public: std::int64_t x; std::int64_t y; point_type_i(std::int64_t _x, std::int64_t _y) : x(_x), y(_y) { } }; using line_type = std::vector<point_type_i>; using line_typed = std::vector<point_type_d>; // from mapnik-vector-tile inline bool encode_linestring(line_type line, protozero::packed_field_uint32 & geometry, int32_t & start_x, int32_t & start_y) { std::size_t line_size = line.size(); //line_size -= detail_pbf::repeated_point_count(line); if (line_size < 2) { return false; } unsigned line_to_length = static_cast<unsigned>(line_size) - 1; auto pt = line.begin(); geometry.add_element(9); // move_to | (1 << 3) geometry.add_element(protozero::encode_zigzag32(pt->x - start_x)); geometry.add_element(protozero::encode_zigzag32(pt->y - start_y)); start_x = pt->x; start_y = pt->y; geometry.add_element(detail_pbf::encode_length(line_to_length)); for (++pt; pt != line.end(); ++pt) { int32_t dx = pt->x - start_x; int32_t dy = pt->y - start_y; /*if (dx == 0 && dy == 0) { continue; }*/ geometry.add_element(protozero::encode_zigzag32(dx)); geometry.add_element(protozero::encode_zigzag32(dy)); start_x = pt->x; start_y = pt->y; } return true; } template <class DataFacadeT> class TilePlugin final : public BasePlugin { public: explicit TilePlugin(DataFacadeT *facade) : facade(facade), descriptor_string("tile") {} const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &route_parameters, util::json::Object &json_result) override final { const double tile_extent = 4096.0; double min_lon, min_lat, max_lon, max_lat; xyz2wsg84(route_parameters.x, route_parameters.y, route_parameters.z, min_lon, min_lat, max_lon, max_lat); FixedPointCoordinate southwest = { static_cast<int32_t>(min_lat * COORDINATE_PRECISION), static_cast<int32_t>(min_lon * COORDINATE_PRECISION) }; FixedPointCoordinate northeast = { static_cast<int32_t>(max_lat * COORDINATE_PRECISION), static_cast<int32_t>(max_lon * COORDINATE_PRECISION) }; auto edges = facade->GetEdgesInBox(southwest, northeast); xyz(route_parameters.x, route_parameters.y, route_parameters.z, min_lon, min_lat, max_lon, max_lat); bbox tile_bbox(min_lon, min_lat, max_lon, max_lat); std::string buffer; protozero::pbf_writer tile_writer(buffer); { protozero::pbf_writer layer_writer(tile_writer,3); // TODO: don't write a layer if there are no features layer_writer.add_uint32(15,2); // version layer_writer.add_string(1,"speeds"); // name layer_writer.add_uint32(5,4096); // extent std::vector<double> speeds; std::vector<bool> is_smalls; { unsigned id = 1; for (const auto & edge : edges) { const auto a = facade->GetCoordinateOfNode(edge.u); const auto b = facade->GetCoordinateOfNode(edge.v); double length = osrm::util::coordinate_calculation::haversineDistance( a.lon, a.lat, b.lon, b.lat ); if (edge.forward_weight != 0 && edge.forward_edge_based_node_id != SPECIAL_NODEID) { std::int32_t start_x = 0; std::int32_t start_y = 0; line_typed geo_line; geo_line.emplace_back(a.lon / COORDINATE_PRECISION, a.lat / COORDINATE_PRECISION); geo_line.emplace_back(b.lon / COORDINATE_PRECISION, b.lat / COORDINATE_PRECISION); double speed = round(length / edge.forward_weight * 10 ) * 3.6; speeds.push_back(speed); is_smalls.push_back(edge.component.is_tiny); line_type tile_line; for (auto const & pt : geo_line) { double px_merc = pt.x; double py_merc = pt.y; lonlat2merc(px_merc,py_merc); // convert to integer tile coordinat const auto px = std::round(((px_merc - tile_bbox.minx) * tile_extent/16.0 / static_cast<double>(tile_bbox.width()))*tile_extent/256.0); const auto py = std::round(((tile_bbox.maxy - py_merc) * tile_extent/16.0 / static_cast<double>(tile_bbox.height()))*tile_extent/256.0); tile_line.emplace_back(px,py); } protozero::pbf_writer feature_writer(layer_writer,2); feature_writer.add_enum(3,2); // geometry type feature_writer.add_uint64(1,id++); // id { protozero::packed_field_uint32 field(feature_writer, 2); field.add_element(0); // "speed" tag key offset field.add_element((speeds.size()-1)*2); // "speed" tag value offset field.add_element(1); // "is_small" tag key offset field.add_element((is_smalls.size()-1)*2+1); // "is_small" tag value offset } { protozero::packed_field_uint32 geometry(feature_writer,4); encode_linestring(tile_line,geometry,start_x,start_y); } } if (edge.reverse_weight != 0 && edge.reverse_edge_based_node_id != SPECIAL_NODEID) { std::int32_t start_x = 0; std::int32_t start_y = 0; line_typed geo_line; geo_line.emplace_back(b.lon / COORDINATE_PRECISION, b.lat / COORDINATE_PRECISION); geo_line.emplace_back(a.lon / COORDINATE_PRECISION, a.lat / COORDINATE_PRECISION); double speed = round(length / edge.reverse_weight * 10 ) * 3.6; speeds.push_back(speed); is_smalls.push_back(edge.component.is_tiny); line_type tile_line; for (auto const & pt : geo_line) { double px_merc = pt.x; double py_merc = pt.y; lonlat2merc(px_merc,py_merc); // convert to integer tile coordinat const auto px = std::round(((px_merc - tile_bbox.minx) * tile_extent/16.0 / static_cast<double>(tile_bbox.width()))*tile_extent/256.0); const auto py = std::round(((tile_bbox.maxy - py_merc) * tile_extent/16.0 / static_cast<double>(tile_bbox.height()))*tile_extent/256.0); tile_line.emplace_back(px,py); } protozero::pbf_writer feature_writer(layer_writer,2); feature_writer.add_enum(3,2); // geometry type feature_writer.add_uint64(1,id++); // id { protozero::packed_field_uint32 field(feature_writer, 2); field.add_element(0); // "speed" tag key offset field.add_element((speeds.size()-1)*2); // "speed" tag value offset field.add_element(1); // "is_small" tag key offset field.add_element((is_smalls.size()-1)*2+1); // "is_small" tag value offset } { protozero::packed_field_uint32 geometry(feature_writer,4); encode_linestring(tile_line,geometry,start_x,start_y); } } } } layer_writer.add_string(3,"speed"); layer_writer.add_string(3,"is_small"); for (size_t i=0; i<speeds.size(); i++) { { protozero::pbf_writer values_writer(layer_writer,4); values_writer.add_double(3, speeds[i]); } { protozero::pbf_writer values_writer(layer_writer,4); values_writer.add_bool(7, is_smalls[i]); } } } json_result.values["pbf"] = osrm::util::json::Buffer(buffer); return Status::Ok; } private: DataFacadeT *facade; std::string descriptor_string; }; } } } #endif /* TILEPLUGIN_HPP */ <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "ut_mtheme.h" #include "mtheme_p.h" #include <MApplication> #include <MGConfItem> #include <MLabel> #include <MScalableImage> #include <MTheme> #include <QEventLoop> #include <QtTest> #include <QString> #include <QProcess> #include <QSignalSpy> namespace { const char *KnownIconId = "meegotouch-combobox-indicator"; const char *UnknownIconId = "xxx-unknown-icon-id"; }; void Ut_MTheme::initTestCase() { static int argc = 1; static char *appName = (char*) "./Ut_MTheme"; m_app = new MApplication(argc, &appName); while (MTheme::hasPendingRequests()) { usleep(10000); QCoreApplication::processEvents(); } m_theme = MTheme::instance(); } void Ut_MTheme::cleanupTestCase() { delete m_app; m_app = 0; } void Ut_MTheme::testStyle() { const MStyle *labelStyle1 = m_theme->style("MLabelStyle"); QVERIFY(labelStyle1 != 0); const MStyle *labelStyle2 = m_theme->style("MLabelStyle", QString(), QString(), QString(), M::Landscape); QVERIFY(labelStyle2 != 0); // Check overload behavior of MTheme::style() QCOMPARE(labelStyle1, labelStyle2); const MStyle *labelStyle3 = m_theme->style("MLabelStyle", "MyButton", "active", QString(), M::Landscape); QVERIFY(labelStyle3 != 0); // Loading of invalid styles is not supported, qFatal() is triggered in this case // const MStyle *invalidStyle = m_theme->style("InvalidStyle", "MyButton", "active", QString(), M::Landscape); // QVERIFY(invalidStyle == 0); m_theme->releaseStyle(labelStyle1); m_theme->releaseStyle(labelStyle2); m_theme->releaseStyle(labelStyle3); } void Ut_MTheme::testThemeChangeCompleted() { QSignalSpy spy(m_theme, SIGNAL(themeChangeCompleted())); MGConfItem themeNameItem("/meegotouch/theme/name"); const QString currentThemeName = themeNameItem.value().toString(); if (currentThemeName == QLatin1String("base")) { themeNameItem.set("blanco"); } else { themeNameItem.set("base"); } // Wait until the signal themeChangeCompleted() has been received QEventLoop eventLoop; connect(m_theme, SIGNAL(themeChangeCompleted()), &eventLoop, SLOT(quit())); QTimer::singleShot(30000, &eventLoop, SLOT(quit())); // fallback if themeChangeCompleted() is not send eventLoop.exec(); QCOMPARE(spy.count(), 1); // Reset theme again themeNameItem.set(currentThemeName); eventLoop.exec(); QCOMPARE(spy.count(), 2); } void Ut_MTheme::testPixmap() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); const QPixmap *pixmap = m_theme->pixmap(KnownIconId); QVERIFY(pixmap != 0); if (MTheme::hasPendingRequests()) { QVERIFY(pixmap->size().isEmpty()); QCOMPARE(spy.count(), 0); } else { QVERIFY(!pixmap->size().isEmpty()); QCOMPARE(spy.count(), 1); } QVERIFY(isIconCached(KnownIconId, QSize())); QCOMPARE(cachedIconCount(), 1); waitForPendingThemeRequests(); // Release icon m_theme->releasePixmap(pixmap); QVERIFY(!isIconCached(KnownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testPixmapWithSize() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); const QPixmap *fixedSizePixmap = m_theme->pixmap(KnownIconId, QSize(100, 150)); QVERIFY(fixedSizePixmap != 0); QCOMPARE(fixedSizePixmap->size(), QSize(100, 150)); QCOMPARE(spy.count(), MTheme::hasPendingRequests() ? 0 : 1); QVERIFY(isIconCached(KnownIconId, fixedSizePixmap->size())); QCOMPARE(cachedIconCount(), 1); waitForPendingThemeRequests(); // Release icon m_theme->releasePixmap(fixedSizePixmap); QVERIFY(!isIconCached(KnownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testUnknownPixmap() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); const QPixmap *unknownPixmap = m_theme->pixmap(UnknownIconId); QVERIFY(unknownPixmap != 0); if (MTheme::hasPendingRequests()) { QVERIFY(unknownPixmap->size().isEmpty()); QCOMPARE(spy.count(), 0); } else { QVERIFY(!unknownPixmap->size().isEmpty()); QCOMPARE(spy.count(), 1); } QVERIFY(isIconCached(UnknownIconId, QSize())); QCOMPARE(cachedIconCount(), 1); waitForPendingThemeRequests(); // Release icon m_theme->releasePixmap(unknownPixmap); QVERIFY(!isIconCached(UnknownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testPixmapCopy() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); QPixmap *pixmap = m_theme->pixmapCopy(KnownIconId); QVERIFY(pixmap != 0); QVERIFY(!pixmap->size().isEmpty()); QCOMPARE(spy.count(), 1); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testPixmapCopyWithSize() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); QPixmap *fixedSizePixmap = m_theme->pixmapCopy(KnownIconId, QSize(100, 150)); QVERIFY(fixedSizePixmap != 0); QCOMPARE(fixedSizePixmap->size(), QSize(100, 150)); QCOMPARE(spy.count(), 1); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testUnknownPixmapCopy() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); QPixmap *unknownPixmap = m_theme->pixmapCopy(UnknownIconId); QVERIFY(unknownPixmap != 0); QCOMPARE(unknownPixmap->size(), QSize(50, 50)); QCOMPARE(spy.count(), 1); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testPixmapCaching() { QCOMPARE(cachedIconCount(), 0); const QPixmap *pixmap = m_theme->pixmap(KnownIconId); QVERIFY(isIconCached(KnownIconId, QSize())); QCOMPARE(cachedIconCount(), 1); const QPixmap *fixedSizePixmap = m_theme->pixmap(KnownIconId, QSize(100, 150)); QVERIFY(isIconCached(KnownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 2); const QPixmap *unknownPixmap = m_theme->pixmap(UnknownIconId); QVERIFY(isIconCached(UnknownIconId, QSize())); QCOMPARE(cachedIconCount(), 3); m_theme->releasePixmap(pixmap); QVERIFY(!isIconCached(KnownIconId, QSize())); QCOMPARE(cachedIconCount(), 2); m_theme->releasePixmap(fixedSizePixmap); QVERIFY(!isIconCached(KnownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 1); m_theme->releasePixmap(unknownPixmap); QVERIFY(!isIconCached(UnknownIconId, QSize())); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testApplicationPixmapDirs() { const QPixmap *unknownPixmap = m_theme->pixmap(UnknownIconId); const QPixmap *custom; m_theme->addPixmapDirectory(qApp->applicationDirPath()); custom = m_theme->pixmap("ut_mtheme"); QVERIFY(custom != 0); QVERIFY(unknownPixmap->toImage() != custom->toImage()); m_theme->releasePixmap(custom); m_theme->clearPixmapDirectories(); custom = m_theme->pixmap("ut_mtheme"); m_theme->releasePixmap(custom); QVERIFY(custom != 0); QCOMPARE(unknownPixmap->toImage(), custom->toImage()); m_theme->releasePixmap(unknownPixmap); } void Ut_MTheme::testScalableImage() { const MScalableImage *image = m_theme->scalableImage(KnownIconId, 1, 2, 3, 4); QVERIFY(image != 0); int left = -1; int right = -1; int top = -1; int bottom = -1; image->borders(&left, &right, &top, &bottom); QCOMPARE(left, 1); QCOMPARE(right, 2); QCOMPARE(top, 3); QCOMPARE(bottom, 4); const MScalableImage *unknownImage = m_theme->scalableImage(UnknownIconId, 1, 2, 3, 4); QVERIFY(unknownImage != 0); left = right = top = bottom = -1; unknownImage->borders(&left, &right, &top, &bottom); QCOMPARE(left, 1); QCOMPARE(right, 2); QCOMPARE(top, 3); QCOMPARE(bottom, 4); m_theme->releaseScalableImage(image); m_theme->releaseScalableImage(unknownImage); } void Ut_MTheme::testView() { MLabel label(0, 0); MWidgetView *view = m_theme->view(&label); QVERIFY(view != 0); } bool Ut_MTheme::isIconCached(const QString &id, const QSize &size) const { const QSize usedSize = size.isEmpty() ? QSize(0, 0) : size; MThemePrivate *d_ptr = m_theme->d_ptr; QHash<QString, CachedPixmap> pixmapIdentifiers = d_ptr->pixmapIdentifiers; QHashIterator<QString, CachedPixmap> it(pixmapIdentifiers); while (it.hasNext()) { it.next(); if (it.value().imageId == id) { const QString sizeString = QLatin1Char('_') + QString::number(usedSize.width()) + QLatin1Char('_') + QString::number(usedSize.height()); if (it.key().endsWith(sizeString)) { return true; } } } return false; } int Ut_MTheme::cachedIconCount() const { MThemePrivate *d_ptr = m_theme->d_ptr; return d_ptr->pixmapIdentifiers.count(); } void Ut_MTheme::waitForPendingThemeRequests() { if (MTheme::hasPendingRequests()) { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); QEventLoop eventLoop; connect(m_theme, SIGNAL(pixmapRequestsFinished()), &eventLoop, SLOT(quit())); QTimer::singleShot(10000, &eventLoop, SLOT(quit())); // fallback if pixmapRequestsFinished() is not send eventLoop.exec(); QCOMPARE(spy.count(), 1); } } QTEST_APPLESS_MAIN(Ut_MTheme) <commit_msg>Changes: QSKIP ut_mtheme test which causes a crash in themedaemon.<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "ut_mtheme.h" #include "mtheme_p.h" #include <MApplication> #include <MGConfItem> #include <MLabel> #include <MScalableImage> #include <MTheme> #include <QEventLoop> #include <QtTest> #include <QString> #include <QProcess> #include <QSignalSpy> namespace { const char *KnownIconId = "meegotouch-combobox-indicator"; const char *UnknownIconId = "xxx-unknown-icon-id"; }; void Ut_MTheme::initTestCase() { static int argc = 1; static char *appName = (char*) "./Ut_MTheme"; m_app = new MApplication(argc, &appName); while (MTheme::hasPendingRequests()) { usleep(10000); QCoreApplication::processEvents(); } m_theme = MTheme::instance(); } void Ut_MTheme::cleanupTestCase() { delete m_app; m_app = 0; } void Ut_MTheme::testStyle() { const MStyle *labelStyle1 = m_theme->style("MLabelStyle"); QVERIFY(labelStyle1 != 0); const MStyle *labelStyle2 = m_theme->style("MLabelStyle", QString(), QString(), QString(), M::Landscape); QVERIFY(labelStyle2 != 0); // Check overload behavior of MTheme::style() QCOMPARE(labelStyle1, labelStyle2); const MStyle *labelStyle3 = m_theme->style("MLabelStyle", "MyButton", "active", QString(), M::Landscape); QVERIFY(labelStyle3 != 0); // Loading of invalid styles is not supported, qFatal() is triggered in this case // const MStyle *invalidStyle = m_theme->style("InvalidStyle", "MyButton", "active", QString(), M::Landscape); // QVERIFY(invalidStyle == 0); m_theme->releaseStyle(labelStyle1); m_theme->releaseStyle(labelStyle2); m_theme->releaseStyle(labelStyle3); } void Ut_MTheme::testThemeChangeCompleted() { QSignalSpy spy(m_theme, SIGNAL(themeChangeCompleted())); MGConfItem themeNameItem("/meegotouch/theme/name"); const QString currentThemeName = themeNameItem.value().toString(); if (currentThemeName == QLatin1String("base")) { themeNameItem.set("blanco"); } else { themeNameItem.set("base"); } // Wait until the signal themeChangeCompleted() has been received QEventLoop eventLoop; connect(m_theme, SIGNAL(themeChangeCompleted()), &eventLoop, SLOT(quit())); QTimer::singleShot(30000, &eventLoop, SLOT(quit())); // fallback if themeChangeCompleted() is not send eventLoop.exec(); QCOMPARE(spy.count(), 1); // Reset theme again themeNameItem.set(currentThemeName); eventLoop.exec(); QCOMPARE(spy.count(), 2); } void Ut_MTheme::testPixmap() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); const QPixmap *pixmap = m_theme->pixmap(KnownIconId); QVERIFY(pixmap != 0); if (MTheme::hasPendingRequests()) { QVERIFY(pixmap->size().isEmpty()); QCOMPARE(spy.count(), 0); } else { QVERIFY(!pixmap->size().isEmpty()); QCOMPARE(spy.count(), 1); } QVERIFY(isIconCached(KnownIconId, QSize())); QCOMPARE(cachedIconCount(), 1); waitForPendingThemeRequests(); // Release icon m_theme->releasePixmap(pixmap); QVERIFY(!isIconCached(KnownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testPixmapWithSize() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); const QPixmap *fixedSizePixmap = m_theme->pixmap(KnownIconId, QSize(100, 150)); QVERIFY(fixedSizePixmap != 0); QCOMPARE(fixedSizePixmap->size(), QSize(100, 150)); QCOMPARE(spy.count(), MTheme::hasPendingRequests() ? 0 : 1); QVERIFY(isIconCached(KnownIconId, fixedSizePixmap->size())); QCOMPARE(cachedIconCount(), 1); waitForPendingThemeRequests(); // Release icon m_theme->releasePixmap(fixedSizePixmap); QVERIFY(!isIconCached(KnownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testUnknownPixmap() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); const QPixmap *unknownPixmap = m_theme->pixmap(UnknownIconId); QVERIFY(unknownPixmap != 0); if (MTheme::hasPendingRequests()) { QVERIFY(unknownPixmap->size().isEmpty()); QCOMPARE(spy.count(), 0); } else { QVERIFY(!unknownPixmap->size().isEmpty()); QCOMPARE(spy.count(), 1); } QVERIFY(isIconCached(UnknownIconId, QSize())); QCOMPARE(cachedIconCount(), 1); waitForPendingThemeRequests(); // Release icon m_theme->releasePixmap(unknownPixmap); QVERIFY(!isIconCached(UnknownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testPixmapCopy() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); QPixmap *pixmap = m_theme->pixmapCopy(KnownIconId); QVERIFY(pixmap != 0); QVERIFY(!pixmap->size().isEmpty()); QCOMPARE(spy.count(), 1); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testPixmapCopyWithSize() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); QPixmap *fixedSizePixmap = m_theme->pixmapCopy(KnownIconId, QSize(100, 150)); QVERIFY(fixedSizePixmap != 0); QCOMPARE(fixedSizePixmap->size(), QSize(100, 150)); QCOMPARE(spy.count(), 1); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testUnknownPixmapCopy() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); QPixmap *unknownPixmap = m_theme->pixmapCopy(UnknownIconId); QVERIFY(unknownPixmap != 0); QCOMPARE(unknownPixmap->size(), QSize(50, 50)); QCOMPARE(spy.count(), 1); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testPixmapCaching() { QCOMPARE(cachedIconCount(), 0); const QPixmap *pixmap = m_theme->pixmap(KnownIconId); QVERIFY(isIconCached(KnownIconId, QSize())); QCOMPARE(cachedIconCount(), 1); const QPixmap *fixedSizePixmap = m_theme->pixmap(KnownIconId, QSize(100, 150)); QVERIFY(isIconCached(KnownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 2); const QPixmap *unknownPixmap = m_theme->pixmap(UnknownIconId); QVERIFY(isIconCached(UnknownIconId, QSize())); QCOMPARE(cachedIconCount(), 3); m_theme->releasePixmap(pixmap); QVERIFY(!isIconCached(KnownIconId, QSize())); QCOMPARE(cachedIconCount(), 2); m_theme->releasePixmap(fixedSizePixmap); QVERIFY(!isIconCached(KnownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 1); m_theme->releasePixmap(unknownPixmap); QVERIFY(!isIconCached(UnknownIconId, QSize())); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testApplicationPixmapDirs() { QSKIP("Skipping due to crashes themedaemon...", SkipAll); const QPixmap *unknownPixmap = m_theme->pixmap(UnknownIconId); const QPixmap *custom; m_theme->addPixmapDirectory(qApp->applicationDirPath()); custom = m_theme->pixmap("ut_mtheme"); QVERIFY(custom != 0); QVERIFY(unknownPixmap->toImage() != custom->toImage()); m_theme->releasePixmap(custom); m_theme->clearPixmapDirectories(); custom = m_theme->pixmap("ut_mtheme"); m_theme->releasePixmap(custom); QVERIFY(custom != 0); QCOMPARE(unknownPixmap->toImage(), custom->toImage()); m_theme->releasePixmap(unknownPixmap); } void Ut_MTheme::testScalableImage() { const MScalableImage *image = m_theme->scalableImage(KnownIconId, 1, 2, 3, 4); QVERIFY(image != 0); int left = -1; int right = -1; int top = -1; int bottom = -1; image->borders(&left, &right, &top, &bottom); QCOMPARE(left, 1); QCOMPARE(right, 2); QCOMPARE(top, 3); QCOMPARE(bottom, 4); const MScalableImage *unknownImage = m_theme->scalableImage(UnknownIconId, 1, 2, 3, 4); QVERIFY(unknownImage != 0); left = right = top = bottom = -1; unknownImage->borders(&left, &right, &top, &bottom); QCOMPARE(left, 1); QCOMPARE(right, 2); QCOMPARE(top, 3); QCOMPARE(bottom, 4); m_theme->releaseScalableImage(image); m_theme->releaseScalableImage(unknownImage); } void Ut_MTheme::testView() { MLabel label(0, 0); MWidgetView *view = m_theme->view(&label); QVERIFY(view != 0); } bool Ut_MTheme::isIconCached(const QString &id, const QSize &size) const { const QSize usedSize = size.isEmpty() ? QSize(0, 0) : size; MThemePrivate *d_ptr = m_theme->d_ptr; QHash<QString, CachedPixmap> pixmapIdentifiers = d_ptr->pixmapIdentifiers; QHashIterator<QString, CachedPixmap> it(pixmapIdentifiers); while (it.hasNext()) { it.next(); if (it.value().imageId == id) { const QString sizeString = QLatin1Char('_') + QString::number(usedSize.width()) + QLatin1Char('_') + QString::number(usedSize.height()); if (it.key().endsWith(sizeString)) { return true; } } } return false; } int Ut_MTheme::cachedIconCount() const { MThemePrivate *d_ptr = m_theme->d_ptr; return d_ptr->pixmapIdentifiers.count(); } void Ut_MTheme::waitForPendingThemeRequests() { if (MTheme::hasPendingRequests()) { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); QEventLoop eventLoop; connect(m_theme, SIGNAL(pixmapRequestsFinished()), &eventLoop, SLOT(quit())); QTimer::singleShot(10000, &eventLoop, SLOT(quit())); // fallback if pixmapRequestsFinished() is not send eventLoop.exec(); QCOMPARE(spy.count(), 1); } } QTEST_APPLESS_MAIN(Ut_MTheme) <|endoftext|>
<commit_before>#include "fixie/state.hpp" #include "fixie/fixie_gl_es.h" #include "fixie/exceptions.hpp" #include "fixie/debug.hpp" namespace fixie { state::state(const caps& caps) : _clear_color(0.0f, 0.0f, 0.0f, 0.0f) , _clear_depth(1.0f) , _clear_stencil(0) , _depth_range(0.0f, 1.0f) , _depth_func(GL_LESS) , _viewport(0, 0, 1, 1) , _scissor_test(GL_FALSE) , _scissor(0, 0, 1, 1) , _front_material(get_default_material()) , _back_material(get_default_material()) , _lights(caps.max_lights()) , _clip_planes(caps.max_clip_planes()) , _active_texture_unit(0) , _matrix_mode(GL_MODELVIEW) , _texture_matrix_stacks(caps.max_texture_units()) , _next_texture_id(1) , _bound_textures(caps.max_texture_units()) , _next_buffer_id(1) , _active_client_texture(0) , _texcoord_attributes(caps.max_texture_units()) , _shade_model(GL_SMOOTH) , _error(GL_NO_ERROR) { for (size_t i = 0; i < _lights.size(); i++) { _lights[i] = get_default_light(i); } } color& state::clear_color() { return _clear_color; } const color& state::clear_color() const { return _clear_color; } GLclampf& state::clear_depth() { return _clear_depth; } const GLclampf& state::clear_depth() const { return _clear_depth; } GLint& state::clear_stencil() { return _clear_stencil; } const GLint& state::clear_stencil() const { return _clear_stencil; } const GLboolean& state::depth_test() const { return _depth_test; } GLboolean& state::depth_test() { return _depth_test; } range& state::depth_range() { return _depth_range; } const range& state::depth_range() const { return _depth_range; } GLenum& state::depth_func() { return _depth_func; } const GLenum& state::depth_func() const { return _depth_func; } rectangle& state::viewport() { return _viewport; } const rectangle& state::viewport() const { return _viewport; } GLboolean& state::scissor_test() { return _scissor_test; } const GLboolean& state::scissor_test() const { return _scissor_test; } rectangle& state::scissor() { return _scissor; } const rectangle& state::scissor() const { return _scissor; } material& state::front_material() { return _front_material; } const material& state::front_material() const { return _front_material; } material& state::back_material() { return _back_material; } const material& state::back_material() const { return _back_material; } light& state::lights(size_t idx) { return _lights[idx]; } const light& state::lights(size_t idx) const { return _lights[idx]; } fixie::light_model& state::light_model() { return _light_model; } const fixie::light_model& state::light_model() const { return _light_model; } vector4& state::clip_plane(size_t idx) { return _clip_planes[idx]; } const vector4& state::clip_plane(size_t idx) const { return _clip_planes[idx]; } GLenum& state::matrix_mode() { return _matrix_mode; } const GLenum& state::matrix_mode() const { return _matrix_mode; } matrix_stack& state::texture_matrix_stack(size_t idx) { return _texture_matrix_stacks[idx]; } const matrix_stack& state::texture_matrix_stack(size_t idx) const { return _texture_matrix_stacks[idx]; } matrix_stack& state::model_view_matrix_stack() { return _model_view_matrix_stack; } const matrix_stack& state::model_view_matrix_stack() const { return _model_view_matrix_stack; } matrix_stack& state::projection_matrix_stack() { return _projection_matrix_stack; } const matrix_stack& state::projection_matrix_stack() const { return _projection_matrix_stack; } GLuint state::insert_texture(std::shared_ptr<fixie::texture> texture) { GLuint id = _next_texture_id++; _textures[id] = texture; return id; } void state::delete_texture(GLuint id) { auto iter = _textures.find(id); if (iter != end(_textures)) { _textures.erase(iter); for (auto bind = begin(_bound_textures); bind != end(_bound_textures); ++bind) { if (iter->second == *bind) { *bind = nullptr; } } } } std::shared_ptr<fixie::texture> state::texture(GLuint id) { auto iter = _textures.find(id); return (iter != end(_textures)) ? iter->second : nullptr; } std::shared_ptr<const fixie::texture> state::texture(GLuint id) const { auto iter = _textures.find(id); return (iter != end(_textures)) ? iter->second : nullptr; } size_t& state::active_texture_unit() { return _active_texture_unit; } const size_t& state::active_texture_unit() const { return _active_texture_unit; } std::shared_ptr<fixie::texture>& state::bound_texture(size_t unit) { return _bound_textures[unit]; } std::shared_ptr<const fixie::texture> state::bound_texture(size_t unit) const { return _bound_textures[unit]; } GLuint state::insert_buffer(std::shared_ptr<fixie::buffer> buffer) { GLuint id = _next_buffer_id++; _buffers[id] = buffer; return id; } void state::delete_buffer(GLuint id) { auto iter = _buffers.find(id); if (iter != end(_buffers)) { _buffers.erase(iter); if (_bound_array_buffer == iter->second) { _bound_array_buffer = nullptr; } if (_bound_element_array_buffer == iter->second) { _bound_element_array_buffer = nullptr; } } } std::shared_ptr<fixie::buffer> state::buffer(GLuint id) { auto iter = _buffers.find(id); return (iter != end(_buffers)) ? iter->second : nullptr; } std::shared_ptr<const fixie::buffer> state::buffer(GLuint id) const { auto iter = _buffers.find(id); return (iter != end(_buffers)) ? iter->second : nullptr; } void state::bind_array_buffer(std::shared_ptr<fixie::buffer> buf) { _bound_array_buffer = buf; if (buf) { buf->bind(GL_ARRAY_BUFFER); if (_bound_element_array_buffer == buf) { _bound_element_array_buffer = nullptr; } } } std::shared_ptr<const fixie::buffer> state::bound_array_buffer() const { return _bound_array_buffer; } std::shared_ptr<fixie::buffer> state::bound_array_buffer() { return _bound_array_buffer; } void state::bind_element_array_buffer(std::shared_ptr<fixie::buffer> buf) { _bound_element_array_buffer = buf; if (buf) { buf->bind(GL_ELEMENT_ARRAY_BUFFER); if (_bound_array_buffer == buf) { _bound_array_buffer = nullptr; } } } std::shared_ptr<const fixie::buffer> state::bound_element_array_buffer() const { return _bound_element_array_buffer; } std::shared_ptr<fixie::buffer> state::bound_element_array_buffer() { return _bound_element_array_buffer; } fixie::vertex_attribute& state::vertex_attribute() { return _vertex_attribute; } const fixie::vertex_attribute& state::vertex_attribute() const { return _vertex_attribute; } fixie::vertex_attribute& state::normal_attribute() { return _normal_attribute; } const fixie::vertex_attribute& state::normal_attribute() const { return _normal_attribute; } fixie::vertex_attribute& state::color_attribute() { return _color_attribute; } const fixie::vertex_attribute& state::color_attribute() const { return _color_attribute; } size_t& state::active_client_texture() { return _active_client_texture; } const size_t& state::active_client_texture() const { return _active_client_texture; } fixie::vertex_attribute& state::texcoord_attribute(size_t unit) { return _texcoord_attributes[unit]; } const fixie::vertex_attribute& state::texcoord_attribute(size_t unit) const { return _texcoord_attributes[unit]; } GLenum& state::shade_model() { return _shade_model; } const GLenum& state::shade_model() const { return _shade_model; } GLenum& state::error() { return _error; } const GLenum& state::error() const { return _error; } } <commit_msg>Erase the iterator after using it to determine if the buffer/texture is bound instead of before.<commit_after>#include "fixie/state.hpp" #include "fixie/fixie_gl_es.h" #include "fixie/exceptions.hpp" #include "fixie/debug.hpp" namespace fixie { state::state(const caps& caps) : _clear_color(0.0f, 0.0f, 0.0f, 0.0f) , _clear_depth(1.0f) , _clear_stencil(0) , _depth_range(0.0f, 1.0f) , _depth_func(GL_LESS) , _viewport(0, 0, 1, 1) , _scissor_test(GL_FALSE) , _scissor(0, 0, 1, 1) , _front_material(get_default_material()) , _back_material(get_default_material()) , _lights(caps.max_lights()) , _clip_planes(caps.max_clip_planes()) , _active_texture_unit(0) , _matrix_mode(GL_MODELVIEW) , _texture_matrix_stacks(caps.max_texture_units()) , _next_texture_id(1) , _bound_textures(caps.max_texture_units()) , _next_buffer_id(1) , _active_client_texture(0) , _texcoord_attributes(caps.max_texture_units()) , _shade_model(GL_SMOOTH) , _error(GL_NO_ERROR) { for (size_t i = 0; i < _lights.size(); i++) { _lights[i] = get_default_light(i); } } color& state::clear_color() { return _clear_color; } const color& state::clear_color() const { return _clear_color; } GLclampf& state::clear_depth() { return _clear_depth; } const GLclampf& state::clear_depth() const { return _clear_depth; } GLint& state::clear_stencil() { return _clear_stencil; } const GLint& state::clear_stencil() const { return _clear_stencil; } const GLboolean& state::depth_test() const { return _depth_test; } GLboolean& state::depth_test() { return _depth_test; } range& state::depth_range() { return _depth_range; } const range& state::depth_range() const { return _depth_range; } GLenum& state::depth_func() { return _depth_func; } const GLenum& state::depth_func() const { return _depth_func; } rectangle& state::viewport() { return _viewport; } const rectangle& state::viewport() const { return _viewport; } GLboolean& state::scissor_test() { return _scissor_test; } const GLboolean& state::scissor_test() const { return _scissor_test; } rectangle& state::scissor() { return _scissor; } const rectangle& state::scissor() const { return _scissor; } material& state::front_material() { return _front_material; } const material& state::front_material() const { return _front_material; } material& state::back_material() { return _back_material; } const material& state::back_material() const { return _back_material; } light& state::lights(size_t idx) { return _lights[idx]; } const light& state::lights(size_t idx) const { return _lights[idx]; } fixie::light_model& state::light_model() { return _light_model; } const fixie::light_model& state::light_model() const { return _light_model; } vector4& state::clip_plane(size_t idx) { return _clip_planes[idx]; } const vector4& state::clip_plane(size_t idx) const { return _clip_planes[idx]; } GLenum& state::matrix_mode() { return _matrix_mode; } const GLenum& state::matrix_mode() const { return _matrix_mode; } matrix_stack& state::texture_matrix_stack(size_t idx) { return _texture_matrix_stacks[idx]; } const matrix_stack& state::texture_matrix_stack(size_t idx) const { return _texture_matrix_stacks[idx]; } matrix_stack& state::model_view_matrix_stack() { return _model_view_matrix_stack; } const matrix_stack& state::model_view_matrix_stack() const { return _model_view_matrix_stack; } matrix_stack& state::projection_matrix_stack() { return _projection_matrix_stack; } const matrix_stack& state::projection_matrix_stack() const { return _projection_matrix_stack; } GLuint state::insert_texture(std::shared_ptr<fixie::texture> texture) { GLuint id = _next_texture_id++; _textures[id] = texture; return id; } void state::delete_texture(GLuint id) { auto iter = _textures.find(id); if (iter != end(_textures)) { for (auto bind = begin(_bound_textures); bind != end(_bound_textures); ++bind) { if (iter->second == *bind) { *bind = nullptr; } } _textures.erase(iter); } } std::shared_ptr<fixie::texture> state::texture(GLuint id) { auto iter = _textures.find(id); return (iter != end(_textures)) ? iter->second : nullptr; } std::shared_ptr<const fixie::texture> state::texture(GLuint id) const { auto iter = _textures.find(id); return (iter != end(_textures)) ? iter->second : nullptr; } size_t& state::active_texture_unit() { return _active_texture_unit; } const size_t& state::active_texture_unit() const { return _active_texture_unit; } std::shared_ptr<fixie::texture>& state::bound_texture(size_t unit) { return _bound_textures[unit]; } std::shared_ptr<const fixie::texture> state::bound_texture(size_t unit) const { return _bound_textures[unit]; } GLuint state::insert_buffer(std::shared_ptr<fixie::buffer> buffer) { GLuint id = _next_buffer_id++; _buffers[id] = buffer; return id; } void state::delete_buffer(GLuint id) { auto iter = _buffers.find(id); if (iter != end(_buffers)) { if (_bound_array_buffer == iter->second) { _bound_array_buffer = nullptr; } if (_bound_element_array_buffer == iter->second) { _bound_element_array_buffer = nullptr; } _buffers.erase(iter); } } std::shared_ptr<fixie::buffer> state::buffer(GLuint id) { auto iter = _buffers.find(id); return (iter != end(_buffers)) ? iter->second : nullptr; } std::shared_ptr<const fixie::buffer> state::buffer(GLuint id) const { auto iter = _buffers.find(id); return (iter != end(_buffers)) ? iter->second : nullptr; } void state::bind_array_buffer(std::shared_ptr<fixie::buffer> buf) { _bound_array_buffer = buf; if (buf) { buf->bind(GL_ARRAY_BUFFER); if (_bound_element_array_buffer == buf) { _bound_element_array_buffer = nullptr; } } } std::shared_ptr<const fixie::buffer> state::bound_array_buffer() const { return _bound_array_buffer; } std::shared_ptr<fixie::buffer> state::bound_array_buffer() { return _bound_array_buffer; } void state::bind_element_array_buffer(std::shared_ptr<fixie::buffer> buf) { _bound_element_array_buffer = buf; if (buf) { buf->bind(GL_ELEMENT_ARRAY_BUFFER); if (_bound_array_buffer == buf) { _bound_array_buffer = nullptr; } } } std::shared_ptr<const fixie::buffer> state::bound_element_array_buffer() const { return _bound_element_array_buffer; } std::shared_ptr<fixie::buffer> state::bound_element_array_buffer() { return _bound_element_array_buffer; } fixie::vertex_attribute& state::vertex_attribute() { return _vertex_attribute; } const fixie::vertex_attribute& state::vertex_attribute() const { return _vertex_attribute; } fixie::vertex_attribute& state::normal_attribute() { return _normal_attribute; } const fixie::vertex_attribute& state::normal_attribute() const { return _normal_attribute; } fixie::vertex_attribute& state::color_attribute() { return _color_attribute; } const fixie::vertex_attribute& state::color_attribute() const { return _color_attribute; } size_t& state::active_client_texture() { return _active_client_texture; } const size_t& state::active_client_texture() const { return _active_client_texture; } fixie::vertex_attribute& state::texcoord_attribute(size_t unit) { return _texcoord_attributes[unit]; } const fixie::vertex_attribute& state::texcoord_attribute(size_t unit) const { return _texcoord_attributes[unit]; } GLenum& state::shade_model() { return _shade_model; } const GLenum& state::shade_model() const { return _shade_model; } GLenum& state::error() { return _error; } const GLenum& state::error() const { return _error; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: terminate.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 12:07:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #ifdef SOLARIS #include <sys/time.h> #include <sys/types.h> #endif #include <signal.h> #ifdef WNT #define UNDER_WINDOWS_DEBUGGING // Nice feature, to debug under windows, install msdev locally and use DebugBreak() to stop a new process at a point you want. #ifdef UNDER_WINDOWS_DEBUGGING #include <tools/presys.h> #include <windows.h> #include <MAPIWin.h> #include <tools/postsys.h> #define VCL_NEED_BASETSD #endif /* UNDER_WINDOWS_DEBUGGING */ #endif /* WNT */ #include <iostream> #include <string> #include "getopt.hxx" #ifdef UNX #include <unistd.h> /* usleep */ #include <sys/types.h> #include <signal.h> #endif using namespace std; // ----------------------------------------------------------------------------- class ProcessHandler { std::string m_sProcessIDFilename; int m_nPID; int getPID(); int readPIDFromFile(); void sendSignal(int _nPID); void write(int); public: ProcessHandler(); void setName(std::string const& _sFilename); ~ProcessHandler(); void waitForPIDFile(int); void waitForTimeout(int); }; void my_sleep(int sec) { #ifdef WNT Sleep(sec * 1000); #else usleep(sec * 1000000); // 10 ms #endif } // ------------------------------- ProcessHelper ------------------------------- ProcessHandler::ProcessHandler():m_nPID(0) {} void ProcessHandler::setName(std::string const& _sPIDFilename) { m_sProcessIDFilename = _sPIDFilename; } int ProcessHandler::getPID() { return m_nPID; } int ProcessHandler::readPIDFromFile() { // get own PID int nPID = 0; if (m_sProcessIDFilename.size() > 0) { FILE* in; in = fopen(m_sProcessIDFilename.c_str(), "r"); if (!in) { // fprintf(stderr, "warning: (testshl.cxx) can't read own pid.\n"); return 0; // exit(0); } // if file exist, wait short, maybe the other tool writes it down. fscanf(in, "%d", &nPID); fclose(in); } else { fprintf(stderr, "error: (terminate.cxx) PID Filename empty, must set.\n"); exit(0); } return nPID; } ProcessHandler::~ProcessHandler() { } #ifdef WNT #define TA_FAILED 0 #define TA_SUCCESS_CLEAN 1 #define TA_SUCCESS_KILL 2 #define TA_SUCCESS_16 3 // Declare Callback Enum Functions. bool CALLBACK TerminateAppEnum( HWND hwnd, LPARAM lParam ); /*---------------------------------------------------------------- DWORD WINAPI TerminateApp( DWORD dwPID, DWORD dwTimeout ) Purpose: Shut down a 32-Bit Process (or 16-bit process under Windows 95) Parameters: dwPID Process ID of the process to shut down. dwTimeout Wait time in milliseconds before shutting down the process. Return Value: TA_FAILED - If the shutdown failed. TA_SUCCESS_CLEAN - If the process was shutdown using WM_CLOSE. TA_SUCCESS_KILL - if the process was shut down with TerminateProcess(). NOTE: See header for these defines. ----------------------------------------------------------------*/ DWORD WINAPI TerminateApp( DWORD dwPID, DWORD dwTimeout ) { HANDLE hProc; DWORD dwRet; // If we can't open the process with PROCESS_TERMINATE rights, // then we give up immediately. hProc = OpenProcess(SYNCHRONIZE|PROCESS_TERMINATE, false, dwPID); if(hProc == NULL) { return TA_FAILED; } // TerminateAppEnum() posts WM_CLOSE to all windows whose PID // matches your process's. EnumWindows((WNDENUMPROC)TerminateAppEnum, (LPARAM) dwPID); // Wait on the handle. If it signals, great. If it times out, // then you kill it. if (WaitForSingleObject(hProc, dwTimeout) != WAIT_OBJECT_0) dwRet= (TerminateProcess(hProc,0) ? TA_SUCCESS_KILL : TA_FAILED); else dwRet = TA_SUCCESS_CLEAN; CloseHandle(hProc); return dwRet; } bool CALLBACK TerminateAppEnum( HWND hwnd, LPARAM lParam ) { DWORD dwID; GetWindowThreadProcessId(hwnd, &dwID); if(dwID == (DWORD)lParam) { PostMessage(hwnd, WM_CLOSE, 0, 0); } return true; } #endif void ProcessHandler::sendSignal(int _nPID) { if (_nPID != 0) { #ifdef WNT TerminateApp(_nPID, 100); #else kill(_nPID, SIGKILL); #endif } } // ----------------------------------------------------------------------------- void ProcessHandler::waitForPIDFile(int _nTimeout) { int nWaitforTimeout = _nTimeout; while (getPID() == 0 && nWaitforTimeout > 0) { int nPID = readPIDFromFile(); if (nPID != 0) { m_nPID = nPID; break; } my_sleep(1); fprintf(stderr, "wait for pid file\n"); nWaitforTimeout--; } if (nWaitforTimeout <= 0) { fprintf(stderr, "No PID found, time runs out\n"); exit(1); } } // ----------------------------------------------------------------------------- void ProcessHandler::waitForTimeout(int _nTimeout) { int nTimeout = _nTimeout; while (nTimeout > 0) { my_sleep(1); fprintf(stderr, "%d \r", nTimeout); int nNewPID = readPIDFromFile(); if ( nNewPID != getPID() ) { fprintf(stderr, "PID has changed.\n"); if ( nNewPID != 0) { fprintf(stderr, "new PID is not 0, maybe forgotten to delete old PID file, restart timeout.\n"); m_nPID = nNewPID; nTimeout = _nTimeout; } else { break; } } nTimeout --; } if (nTimeout <= 0) { fprintf(stderr, "PID: %d\n", getPID()); sendSignal(getPID()); write(0); } } void ProcessHandler::write(int _nPID) { // get own PID if (m_sProcessIDFilename.size() > 0) { FILE* out; out = fopen(m_sProcessIDFilename.c_str(), "w"); if (!out) { fprintf(stderr, "warning: (testshl.cxx) can't write own pid.\n"); return; // exit(0); } fprintf(out, "%d", _nPID); fclose(out); } else { fprintf(stderr, "warning: (testshl.cxx) PID Filename empty, must set.\n"); } } // ----------------------------------- Main ----------------------------------- #if (defined UNX) || (defined OS2) int main( int argc, char* argv[] ) #else int _cdecl main( int argc, char* argv[] ) #endif { static char* optionSet[] = { "-version, shows current program version and exit.", "-pid=s, write current process id to file", "-time=s, timeout [default is 10 sec]", "-h:s, display help or help on option", "-help:s, see -h", NULL }; ProcessHandler aCurrentProcess; GetOpt opt( argv, optionSet ); if ( opt.hasOpt("-pid") ) { aCurrentProcess.setName(opt.getOpt("-pid").getStr()); } int nTimeout = 10; if ( opt.hasOpt("-time")) { // nTimeout = opt.getOpt("-time").toInt32(); if (nTimeout == 0) { nTimeout = 10; } } if ( opt.hasOpt("-version") ) { fprintf(stderr, "testshl2_timeout $Revision: 1.3 $\n"); exit(0); } // someone indicates that he needs help if ( opt.hasOpt( "-h" ) || opt.hasOpt( "-help" ) ) { opt.showUsage(); exit(0); } // wait until pid file exist ============================== aCurrentProcess.waitForPIDFile(10); printf("Found PID file, wait for timeout %d sec.\n", nTimeout); // timeout ================================================== aCurrentProcess.waitForTimeout(nTimeout); return 0; } <commit_msg>INTEGRATION: CWS warnings01 (1.2.50); FILE MERGED 2006/03/01 16:54:53 sb 1.2.50.3: #i53898# Made code warning-free. 2005/09/22 22:38:18 sb 1.2.50.2: RESYNC: (1.2-1.3); FILE MERGED 2005/09/14 10:21:51 sb 1.2.50.1: #i53898# Made code warning-free.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: terminate.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2006-06-20 02:28:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #ifdef SOLARIS #include <sys/time.h> #include <sys/types.h> #endif #include <signal.h> #ifdef WNT #define UNDER_WINDOWS_DEBUGGING // Nice feature, to debug under windows, install msdev locally and use DebugBreak() to stop a new process at a point you want. #ifdef UNDER_WINDOWS_DEBUGGING #if defined _MSC_VER #pragma warning(push, 1) #endif #include <windows.h> #if defined _MSC_VER #pragma warning(pop) #endif #include <MAPIWin.h> #define VCL_NEED_BASETSD #endif /* UNDER_WINDOWS_DEBUGGING */ #endif /* WNT */ #include <iostream> #include <string> #include "getopt.hxx" #ifdef UNX #include <unistd.h> /* usleep */ #include <sys/types.h> #include <signal.h> #endif using namespace std; // ----------------------------------------------------------------------------- class ProcessHandler { std::string m_sProcessIDFilename; int m_nPID; int getPID(); int readPIDFromFile(); void sendSignal(int _nPID); void write(int); public: ProcessHandler(); void setName(std::string const& _sFilename); ~ProcessHandler(); void waitForPIDFile(int); void waitForTimeout(int); }; void my_sleep(int sec) { #ifdef WNT Sleep(sec * 1000); #else usleep(sec * 1000000); // 10 ms #endif } // ------------------------------- ProcessHelper ------------------------------- ProcessHandler::ProcessHandler():m_nPID(0) {} void ProcessHandler::setName(std::string const& _sPIDFilename) { m_sProcessIDFilename = _sPIDFilename; } int ProcessHandler::getPID() { return m_nPID; } int ProcessHandler::readPIDFromFile() { // get own PID int nPID = 0; if (m_sProcessIDFilename.size() > 0) { FILE* in; in = fopen(m_sProcessIDFilename.c_str(), "r"); if (!in) { // fprintf(stderr, "warning: (testshl.cxx) can't read own pid.\n"); return 0; // exit(0); } // if file exist, wait short, maybe the other tool writes it down. fscanf(in, "%d", &nPID); fclose(in); } else { fprintf(stderr, "error: (terminate.cxx) PID Filename empty, must set.\n"); exit(0); } return nPID; } ProcessHandler::~ProcessHandler() { } #ifdef WNT #define TA_FAILED 0 #define TA_SUCCESS_CLEAN 1 #define TA_SUCCESS_KILL 2 #define TA_SUCCESS_16 3 // Declare Callback Enum Functions. bool CALLBACK TerminateAppEnum( HWND hwnd, LPARAM lParam ); /*---------------------------------------------------------------- DWORD WINAPI TerminateApp( DWORD dwPID, DWORD dwTimeout ) Purpose: Shut down a 32-Bit Process (or 16-bit process under Windows 95) Parameters: dwPID Process ID of the process to shut down. dwTimeout Wait time in milliseconds before shutting down the process. Return Value: TA_FAILED - If the shutdown failed. TA_SUCCESS_CLEAN - If the process was shutdown using WM_CLOSE. TA_SUCCESS_KILL - if the process was shut down with TerminateProcess(). NOTE: See header for these defines. ----------------------------------------------------------------*/ DWORD WINAPI TerminateApp( DWORD dwPID, DWORD dwTimeout ) { HANDLE hProc; DWORD dwRet; // If we can't open the process with PROCESS_TERMINATE rights, // then we give up immediately. hProc = OpenProcess(SYNCHRONIZE|PROCESS_TERMINATE, false, dwPID); if(hProc == NULL) { return TA_FAILED; } // TerminateAppEnum() posts WM_CLOSE to all windows whose PID // matches your process's. EnumWindows((WNDENUMPROC)TerminateAppEnum, (LPARAM) dwPID); // Wait on the handle. If it signals, great. If it times out, // then you kill it. if (WaitForSingleObject(hProc, dwTimeout) != WAIT_OBJECT_0) dwRet= (TerminateProcess(hProc,0) ? TA_SUCCESS_KILL : TA_FAILED); else dwRet = TA_SUCCESS_CLEAN; CloseHandle(hProc); return dwRet; } bool CALLBACK TerminateAppEnum( HWND hwnd, LPARAM lParam ) { DWORD dwID; GetWindowThreadProcessId(hwnd, &dwID); if(dwID == (DWORD)lParam) { PostMessage(hwnd, WM_CLOSE, 0, 0); } return true; } #endif void ProcessHandler::sendSignal(int _nPID) { if (_nPID != 0) { #ifdef WNT TerminateApp(_nPID, 100); #else kill(_nPID, SIGKILL); #endif } } // ----------------------------------------------------------------------------- void ProcessHandler::waitForPIDFile(int _nTimeout) { int nWaitforTimeout = _nTimeout; while (getPID() == 0 && nWaitforTimeout > 0) { int nPID = readPIDFromFile(); if (nPID != 0) { m_nPID = nPID; break; } my_sleep(1); fprintf(stderr, "wait for pid file\n"); nWaitforTimeout--; } if (nWaitforTimeout <= 0) { fprintf(stderr, "No PID found, time runs out\n"); exit(1); } } // ----------------------------------------------------------------------------- void ProcessHandler::waitForTimeout(int _nTimeout) { int nTimeout = _nTimeout; while (nTimeout > 0) { my_sleep(1); fprintf(stderr, "%d \r", nTimeout); int nNewPID = readPIDFromFile(); if ( nNewPID != getPID() ) { fprintf(stderr, "PID has changed.\n"); if ( nNewPID != 0) { fprintf(stderr, "new PID is not 0, maybe forgotten to delete old PID file, restart timeout.\n"); m_nPID = nNewPID; nTimeout = _nTimeout; } else { break; } } nTimeout --; } if (nTimeout <= 0) { fprintf(stderr, "PID: %d\n", getPID()); sendSignal(getPID()); write(0); } } void ProcessHandler::write(int _nPID) { // get own PID if (m_sProcessIDFilename.size() > 0) { FILE* out; out = fopen(m_sProcessIDFilename.c_str(), "w"); if (!out) { fprintf(stderr, "warning: (testshl.cxx) can't write own pid.\n"); return; // exit(0); } fprintf(out, "%d", _nPID); fclose(out); } else { fprintf(stderr, "warning: (testshl.cxx) PID Filename empty, must set.\n"); } } // ----------------------------------- Main ----------------------------------- #if (defined UNX) || (defined OS2) int main( int, char* argv[] ) #else int _cdecl main( int, char* argv[] ) #endif { static char const * optionSet[] = { "-version, shows current program version and exit.", "-pid=s, write current process id to file", "-time=s, timeout [default is 10 sec]", "-h:s, display help or help on option", "-help:s, see -h", NULL }; ProcessHandler aCurrentProcess; GetOpt opt( argv, optionSet ); if ( opt.hasOpt("-pid") ) { aCurrentProcess.setName(opt.getOpt("-pid").getStr()); } int nTimeout = 10; if ( opt.hasOpt("-time")) { // nTimeout = opt.getOpt("-time").toInt32(); if (nTimeout == 0) { nTimeout = 10; } } if ( opt.hasOpt("-version") ) { fprintf(stderr, "testshl2_timeout $Revision: 1.4 $\n"); exit(0); } // someone indicates that he needs help if ( opt.hasOpt( "-h" ) || opt.hasOpt( "-help" ) ) { opt.showUsage(); exit(0); } // wait until pid file exist ============================== aCurrentProcess.waitForPIDFile(10); printf("Found PID file, wait for timeout %d sec.\n", nTimeout); // timeout ================================================== aCurrentProcess.waitForTimeout(nTimeout); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2013, Stephan Aßmus <[email protected]>. * All rights reserved. Distributed under the terms of the MIT License. */ #include "TextDocumentTest.h" #include <math.h> #include <stdio.h> #include <LayoutBuilder.h> #include <ScrollView.h> #include <Window.h> #include <private/shared/ToolBar.h> #include "MarkupParser.h" #include "TextDocumentView.h" using namespace BPrivate; TextDocumentTest::TextDocumentTest() : BApplication("application/x-vnd.Haiku-TextDocumentTest") { } TextDocumentTest::~TextDocumentTest() { } void TextDocumentTest::ReadyToRun() { BRect frame(50.0, 50.0, 749.0, 549.0); BWindow* window = new BWindow(frame, "Text document test", B_TITLED_WINDOW, B_QUIT_ON_WINDOW_CLOSE | B_AUTO_UPDATE_SIZE_LIMITS); TextDocumentView* documentView = new TextDocumentView("text document view"); BScrollView* scrollView = new BScrollView("text scroll view", documentView, false, true, B_NO_BORDER); BToolBar* toolBar= new BToolBar(); BLayoutBuilder::Group<>(window, B_VERTICAL) .Add(toolBar) .Add(scrollView) .SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNLIMITED)) ; CharacterStyle regularStyle; float fontSize = regularStyle.Font().Size(); ParagraphStyle paragraphStyle; paragraphStyle.SetJustify(true); paragraphStyle.SetSpacingTop(ceilf(fontSize * 0.6f)); paragraphStyle.SetLineSpacing(ceilf(fontSize * 0.2f)); CharacterStyle boldStyle(regularStyle); boldStyle.SetBold(true); CharacterStyle italicStyle(regularStyle); italicStyle.SetItalic(true); CharacterStyle italicAndBoldStyle(boldStyle); italicAndBoldStyle.SetItalic(true); CharacterStyle bigStyle(regularStyle); bigStyle.SetFontSize(24); bigStyle.SetBold(true); bigStyle.SetForegroundColor(255, 50, 50); TextDocumentRef document(new TextDocument(), true); Paragraph paragraph(paragraphStyle); paragraph.Append(TextSpan("This is a", regularStyle)); paragraph.Append(TextSpan(" test ", bigStyle)); paragraph.Append(TextSpan("to see if ", regularStyle)); paragraph.Append(TextSpan("different", boldStyle)); paragraph.Append(TextSpan(" character styles already work.", regularStyle)); document->Append(paragraph); paragraphStyle.SetSpacingTop(8.0f); paragraphStyle.SetAlignment(ALIGN_CENTER); paragraphStyle.SetJustify(false); paragraph = Paragraph(paragraphStyle); paragraph.Append(TextSpan("Different alignment styles ", regularStyle)); paragraph.Append(TextSpan("are", boldStyle)); paragraph.Append(TextSpan(" supported as of now!", regularStyle)); document->Append(paragraph); paragraphStyle.SetAlignment(ALIGN_RIGHT); paragraphStyle.SetJustify(true); paragraph = Paragraph(paragraphStyle); paragraph.Append(TextSpan("I am on the ", regularStyle)); paragraph.Append(TextSpan("Right", boldStyle)); paragraph.Append(TextSpan("Side", italicStyle)); document->Append(paragraph); // Test a bullet list paragraphStyle.SetSpacingTop(8.0f); paragraphStyle.SetAlignment(ALIGN_LEFT); paragraphStyle.SetJustify(true); paragraphStyle.SetBullet(Bullet("•", 12.0f)); paragraphStyle.SetLineInset(10.0f); paragraph = Paragraph(paragraphStyle); paragraph.Append(TextSpan("Even bullet lists are supported.", regularStyle)); document->Append(paragraph); paragraph = Paragraph(paragraphStyle); paragraph.Append(TextSpan("The wrapping in ", regularStyle)); paragraph.Append(TextSpan("this", italicStyle)); paragraph.Append(TextSpan(" bullet item should look visually " "pleasing. And ", regularStyle)); paragraph.Append(TextSpan("why", italicAndBoldStyle)); paragraph.Append(TextSpan(" should it not?", regularStyle)); document->Append(paragraph); /* MarkupParser parser(regularStyle, paragraphStyle); TextDocumentRef document = parser.CreateDocumentFromMarkup( "== Text document test ==\n" "This is a test to see if '''different''' " "character styles already work.\n" "Different alignment styles '''are''' supported as of now!\n" " * Even bullet lists are supported.\n" " * The wrapping in ''this'' bullet item should look visually " "pleasing. And ''why'' should it not?\n" );*/ documentView->SetTextDocument(document); documentView->SetTextEditor(TextEditorRef(new TextEditor(), true)); documentView->MakeFocus(); window->Show(); } int main(int argc, char* argv[]) { TextDocumentTest().Run(); return 0; } <commit_msg>added satus bar - wich also make the layout work<commit_after>/* * Copyright 2013, Stephan Aßmus <[email protected]>. * All rights reserved. Distributed under the terms of the MIT License. */ #include "TextDocumentTest.h" #include <math.h> #include <stdio.h> #include <Button.h> #include <LayoutBuilder.h> #include <ScrollView.h> #include <StringView.h> #include <Window.h> #include <private/shared/ToolBar.h> #include "MarkupParser.h" #include "TextDocumentView.h" using namespace BPrivate; TextDocumentTest::TextDocumentTest() : BApplication("application/x-vnd.Haiku-TextDocumentTest") { } TextDocumentTest::~TextDocumentTest() { } void TextDocumentTest::ReadyToRun() { BRect frame(50.0, 50.0, 749.0, 549.0); BWindow* window = new BWindow(frame, "Text document test", B_TITLED_WINDOW, B_QUIT_ON_WINDOW_CLOSE | B_AUTO_UPDATE_SIZE_LIMITS); TextDocumentView* documentView = new TextDocumentView("text document view"); BScrollView* scrollView = new BScrollView("text scroll view", documentView, false, true, B_NO_BORDER); BToolBar* toolBar= new BToolBar(); toolBar->AddView(new BButton("Bold")); BToolBar* statusBar= new BToolBar(); statusBar->AddView(new BStringView("firstStatus","Here will be the Status View")); BLayoutBuilder::Group<>(window, B_VERTICAL,0) .Add(toolBar) .Add(scrollView) .SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNLIMITED)) .Add(statusBar) ; CharacterStyle regularStyle; float fontSize = regularStyle.Font().Size(); ParagraphStyle paragraphStyle; paragraphStyle.SetJustify(true); paragraphStyle.SetSpacingTop(ceilf(fontSize * 0.6f)); paragraphStyle.SetLineSpacing(ceilf(fontSize * 0.2f)); CharacterStyle boldStyle(regularStyle); boldStyle.SetBold(true); CharacterStyle italicStyle(regularStyle); italicStyle.SetItalic(true); CharacterStyle italicAndBoldStyle(boldStyle); italicAndBoldStyle.SetItalic(true); CharacterStyle bigStyle(regularStyle); bigStyle.SetFontSize(24); bigStyle.SetBold(true); bigStyle.SetForegroundColor(255, 50, 50); TextDocumentRef document(new TextDocument(), true); Paragraph paragraph(paragraphStyle); paragraph.Append(TextSpan("This is a", regularStyle)); paragraph.Append(TextSpan(" test ", bigStyle)); paragraph.Append(TextSpan("to see if ", regularStyle)); paragraph.Append(TextSpan("different", boldStyle)); paragraph.Append(TextSpan(" character styles already work.", regularStyle)); document->Append(paragraph); paragraphStyle.SetSpacingTop(8.0f); paragraphStyle.SetAlignment(ALIGN_CENTER); paragraphStyle.SetJustify(false); paragraph = Paragraph(paragraphStyle); paragraph.Append(TextSpan("Different alignment styles ", regularStyle)); paragraph.Append(TextSpan("are", boldStyle)); paragraph.Append(TextSpan(" supported as of now!", regularStyle)); document->Append(paragraph); paragraphStyle.SetAlignment(ALIGN_RIGHT); paragraphStyle.SetJustify(true); paragraph = Paragraph(paragraphStyle); paragraph.Append(TextSpan("I am on the ", regularStyle)); paragraph.Append(TextSpan("Right", boldStyle)); paragraph.Append(TextSpan("Side", italicStyle)); document->Append(paragraph); // Test a bullet list paragraphStyle.SetSpacingTop(8.0f); paragraphStyle.SetAlignment(ALIGN_LEFT); paragraphStyle.SetJustify(true); paragraphStyle.SetBullet(Bullet("•", 12.0f)); paragraphStyle.SetLineInset(10.0f); paragraph = Paragraph(paragraphStyle); paragraph.Append(TextSpan("Even bullet lists are supported.", regularStyle)); document->Append(paragraph); paragraph = Paragraph(paragraphStyle); paragraph.Append(TextSpan("The wrapping in ", regularStyle)); paragraph.Append(TextSpan("this", italicStyle)); paragraph.Append(TextSpan(" bullet item should look visually " "pleasing. And ", regularStyle)); paragraph.Append(TextSpan("why", italicAndBoldStyle)); paragraph.Append(TextSpan(" should it not?", regularStyle)); document->Append(paragraph); /* MarkupParser parser(regularStyle, paragraphStyle); TextDocumentRef document = parser.CreateDocumentFromMarkup( "== Text document test ==\n" "This is a test to see if '''different''' " "character styles already work.\n" "Different alignment styles '''are''' supported as of now!\n" " * Even bullet lists are supported.\n" " * The wrapping in ''this'' bullet item should look visually " "pleasing. And ''why'' should it not?\n" );*/ documentView->SetTextDocument(document); documentView->SetTextEditor(TextEditorRef(new TextEditor(), true)); documentView->MakeFocus(); window->Show(); } int main(int argc, char* argv[]) { TextDocumentTest().Run(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. // Support out-of-source builds: if MFEM_CONFIG_FILE is defined, include it. // // Otherwise, use the local file: _config.hpp. #ifndef MFEM_CONFIG_HPP #define MFEM_CONFIG_HPP #ifdef MFEM_CONFIG_FILE #include MFEM_CONFIG_FILE #else #include "_config.hpp" #endif // Common configuration macros #if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)) || defined(__clang__) #define MFEM_HAVE_GCC_PRAGMA_DIAGNOSTIC #endif // Windows specific options #ifdef _WIN32 // Macro needed to get defines like M_PI from <cmath>. (Visual Studio C++ only?) #define _USE_MATH_DEFINES #endif // Check dependencies: #define MFEM_USE_MPI // Options that require MPI #ifndef MFEM_USE_MPI #ifdef MFEM_USE_SUPERLU #error Building with SuperLU_DIST (MFEM_USE_SUPERLU=YES) requires MPI (MFEM_USE_MPI=YES) #endif #ifdef MFEM_USE_STRUMPACK #error Building with STRUMPACK (MFEM_USE_STRUMPACK=YES) requires MPI (MFEM_USE_MPI=YES) #endif #ifdef MFEM_USE_PETSC #error Building with PETSc (MFEM_USE_PETSC=YES) requires MPI (MFEM_USE_MPI=YES) #endif #ifdef MFEM_USE_PUMI #error Building with PUMI (MFEM_USE_PUMI=YES) requires MPI (MFEM_USE_MPI=YES) #endif #endif // MFEM_USE_MPI not defined #endif // MFEM_CONFIG_HPP <commit_msg>Revert config<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. // Support out-of-source builds: if MFEM_CONFIG_FILE is defined, include it. // // Otherwise, use the local file: _config.hpp. #ifndef MFEM_CONFIG_HPP #define MFEM_CONFIG_HPP #ifdef MFEM_CONFIG_FILE #include MFEM_CONFIG_FILE #else #include "_config.hpp" #endif // Common configuration macros #if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)) || defined(__clang__) #define MFEM_HAVE_GCC_PRAGMA_DIAGNOSTIC #endif // Windows specific options #ifdef _WIN32 // Macro needed to get defines like M_PI from <cmath>. (Visual Studio C++ only?) #define _USE_MATH_DEFINES #endif // Check dependencies: // Options that require MPI #ifndef MFEM_USE_MPI #ifdef MFEM_USE_SUPERLU #error Building with SuperLU_DIST (MFEM_USE_SUPERLU=YES) requires MPI (MFEM_USE_MPI=YES) #endif #ifdef MFEM_USE_STRUMPACK #error Building with STRUMPACK (MFEM_USE_STRUMPACK=YES) requires MPI (MFEM_USE_MPI=YES) #endif #ifdef MFEM_USE_PETSC #error Building with PETSc (MFEM_USE_PETSC=YES) requires MPI (MFEM_USE_MPI=YES) #endif #ifdef MFEM_USE_PUMI #error Building with PUMI (MFEM_USE_PUMI=YES) requires MPI (MFEM_USE_MPI=YES) #endif #endif // MFEM_USE_MPI not defined #endif // MFEM_CONFIG_HPP <|endoftext|>
<commit_before>//===-- asan_malloc_linux.cc ----------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of AddressSanitizer, an address sanity checker. // // Linux-specific malloc interception. // We simply define functions like malloc, free, realloc, etc. // They will replace the corresponding libc functions automagically. //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_platform.h" #if SANITIZER_FREEBSD || SANITIZER_LINUX #include "sanitizer_common/sanitizer_tls_get_addr.h" #include "asan_allocator.h" #include "asan_interceptors.h" #include "asan_internal.h" #include "asan_stack.h" // ---------------------- Replacement functions ---------------- {{{1 using namespace __asan; // NOLINT INTERCEPTOR(void, free, void *ptr) { GET_STACK_TRACE_FREE; asan_free(ptr, &stack, FROM_MALLOC); } INTERCEPTOR(void, cfree, void *ptr) { GET_STACK_TRACE_FREE; asan_free(ptr, &stack, FROM_MALLOC); } INTERCEPTOR(void*, malloc, uptr size) { GET_STACK_TRACE_MALLOC; return asan_malloc(size, &stack); } INTERCEPTOR(void*, calloc, uptr nmemb, uptr size) { if (UNLIKELY(!asan_inited)) { // Hack: dlsym calls calloc before REAL(calloc) is retrieved from dlsym. const uptr kCallocPoolSize = 1024; static uptr calloc_memory_for_dlsym[kCallocPoolSize]; static uptr allocated; uptr size_in_words = ((nmemb * size) + kWordSize - 1) / kWordSize; void *mem = (void*)&calloc_memory_for_dlsym[allocated]; allocated += size_in_words; CHECK(allocated < kCallocPoolSize); return mem; } GET_STACK_TRACE_MALLOC; return asan_calloc(nmemb, size, &stack); } INTERCEPTOR(void*, realloc, void *ptr, uptr size) { GET_STACK_TRACE_MALLOC; return asan_realloc(ptr, size, &stack); } INTERCEPTOR(void*, memalign, uptr boundary, uptr size) { GET_STACK_TRACE_MALLOC; return asan_memalign(boundary, size, &stack, FROM_MALLOC); } INTERCEPTOR(void*, aligned_alloc, uptr boundary, uptr size) { GET_STACK_TRACE_MALLOC; return asan_memalign(boundary, size, &stack, FROM_MALLOC); } INTERCEPTOR(void*, __libc_memalign, uptr boundary, uptr size) { GET_STACK_TRACE_MALLOC; void *res = asan_memalign(boundary, size, &stack, FROM_MALLOC); DTLS_on_libc_memalign(res, size * boundary); return res; } INTERCEPTOR(uptr, malloc_usable_size, void *ptr) { GET_CURRENT_PC_BP_SP; (void)sp; return asan_malloc_usable_size(ptr, pc, bp); } // We avoid including malloc.h for portability reasons. // man mallinfo says the fields are "long", but the implementation uses int. // It doesn't matter much -- we just need to make sure that the libc's mallinfo // is not called. struct fake_mallinfo { int x[10]; }; INTERCEPTOR(struct fake_mallinfo, mallinfo, void) { struct fake_mallinfo res; REAL(memset)(&res, 0, sizeof(res)); return res; } INTERCEPTOR(int, mallopt, int cmd, int value) { return -1; } INTERCEPTOR(int, posix_memalign, void **memptr, uptr alignment, uptr size) { GET_STACK_TRACE_MALLOC; // Printf("posix_memalign: %zx %zu\n", alignment, size); return asan_posix_memalign(memptr, alignment, size, &stack); } INTERCEPTOR(void*, valloc, uptr size) { GET_STACK_TRACE_MALLOC; return asan_valloc(size, &stack); } INTERCEPTOR(void*, pvalloc, uptr size) { GET_STACK_TRACE_MALLOC; return asan_pvalloc(size, &stack); } INTERCEPTOR(void, malloc_stats, void) { __asan_print_accumulated_stats(); } #if SANITIZER_ANDROID // Format of __libc_malloc_dispatch has changed in Android L. // While we are moving towards a solution that does not depend on bionic // internals, here is something to support both K* and L releases. struct MallocDebugK { void *(*malloc)(uptr bytes); void (*free)(void *mem); void *(*calloc)(uptr n_elements, uptr elem_size); void *(*realloc)(void *oldMem, uptr bytes); void *(*memalign)(uptr alignment, uptr bytes); uptr (*malloc_usable_size)(void *mem); }; struct MallocDebugL { void *(*calloc)(uptr n_elements, uptr elem_size); void (*free)(void *mem); fake_mallinfo (*mallinfo)(void); void *(*malloc)(uptr bytes); uptr (*malloc_usable_size)(void *mem); void *(*memalign)(uptr alignment, uptr bytes); int (*posix_memalign)(void **memptr, uptr alignment, uptr size); void* (*pvalloc)(uptr size); void *(*realloc)(void *oldMem, uptr bytes); void* (*valloc)(uptr size); }; ALIGNED(32) const MallocDebugK asan_malloc_dispatch_k = { WRAP(malloc), WRAP(free), WRAP(calloc), WRAP(realloc), WRAP(memalign), WRAP(malloc_usable_size)}; ALIGNED(32) const MallocDebugL asan_malloc_dispatch_l = { WRAP(calloc), WRAP(free), WRAP(mallinfo), WRAP(malloc), WRAP(malloc_usable_size), WRAP(memalign), WRAP(posix_memalign), WRAP(pvalloc), WRAP(realloc), WRAP(valloc)}; namespace __asan { void ReplaceSystemMalloc() { void **__libc_malloc_dispatch_p = (void **)AsanDlSymNext("__libc_malloc_dispatch"); if (__libc_malloc_dispatch_p) { // Decide on K vs L dispatch format by the presence of // __libc_malloc_default_dispatch export in libc. void *default_dispatch_p = AsanDlSymNext("__libc_malloc_default_dispatch"); Printf("default dispatch: %p\n", default_dispatch_p); if (default_dispatch_p) *__libc_malloc_dispatch_p = (void *)&asan_malloc_dispatch_k; else *__libc_malloc_dispatch_p = (void *)&asan_malloc_dispatch_l; } } } // namespace __asan #else // SANITIZER_ANDROID namespace __asan { void ReplaceSystemMalloc() { } } // namespace __asan #endif // SANITIZER_ANDROID #endif // SANITIZER_FREEBSD || SANITIZER_LINUX <commit_msg>[asan] Remove leftover debug printf.<commit_after>//===-- asan_malloc_linux.cc ----------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of AddressSanitizer, an address sanity checker. // // Linux-specific malloc interception. // We simply define functions like malloc, free, realloc, etc. // They will replace the corresponding libc functions automagically. //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_platform.h" #if SANITIZER_FREEBSD || SANITIZER_LINUX #include "sanitizer_common/sanitizer_tls_get_addr.h" #include "asan_allocator.h" #include "asan_interceptors.h" #include "asan_internal.h" #include "asan_stack.h" // ---------------------- Replacement functions ---------------- {{{1 using namespace __asan; // NOLINT INTERCEPTOR(void, free, void *ptr) { GET_STACK_TRACE_FREE; asan_free(ptr, &stack, FROM_MALLOC); } INTERCEPTOR(void, cfree, void *ptr) { GET_STACK_TRACE_FREE; asan_free(ptr, &stack, FROM_MALLOC); } INTERCEPTOR(void*, malloc, uptr size) { GET_STACK_TRACE_MALLOC; return asan_malloc(size, &stack); } INTERCEPTOR(void*, calloc, uptr nmemb, uptr size) { if (UNLIKELY(!asan_inited)) { // Hack: dlsym calls calloc before REAL(calloc) is retrieved from dlsym. const uptr kCallocPoolSize = 1024; static uptr calloc_memory_for_dlsym[kCallocPoolSize]; static uptr allocated; uptr size_in_words = ((nmemb * size) + kWordSize - 1) / kWordSize; void *mem = (void*)&calloc_memory_for_dlsym[allocated]; allocated += size_in_words; CHECK(allocated < kCallocPoolSize); return mem; } GET_STACK_TRACE_MALLOC; return asan_calloc(nmemb, size, &stack); } INTERCEPTOR(void*, realloc, void *ptr, uptr size) { GET_STACK_TRACE_MALLOC; return asan_realloc(ptr, size, &stack); } INTERCEPTOR(void*, memalign, uptr boundary, uptr size) { GET_STACK_TRACE_MALLOC; return asan_memalign(boundary, size, &stack, FROM_MALLOC); } INTERCEPTOR(void*, aligned_alloc, uptr boundary, uptr size) { GET_STACK_TRACE_MALLOC; return asan_memalign(boundary, size, &stack, FROM_MALLOC); } INTERCEPTOR(void*, __libc_memalign, uptr boundary, uptr size) { GET_STACK_TRACE_MALLOC; void *res = asan_memalign(boundary, size, &stack, FROM_MALLOC); DTLS_on_libc_memalign(res, size * boundary); return res; } INTERCEPTOR(uptr, malloc_usable_size, void *ptr) { GET_CURRENT_PC_BP_SP; (void)sp; return asan_malloc_usable_size(ptr, pc, bp); } // We avoid including malloc.h for portability reasons. // man mallinfo says the fields are "long", but the implementation uses int. // It doesn't matter much -- we just need to make sure that the libc's mallinfo // is not called. struct fake_mallinfo { int x[10]; }; INTERCEPTOR(struct fake_mallinfo, mallinfo, void) { struct fake_mallinfo res; REAL(memset)(&res, 0, sizeof(res)); return res; } INTERCEPTOR(int, mallopt, int cmd, int value) { return -1; } INTERCEPTOR(int, posix_memalign, void **memptr, uptr alignment, uptr size) { GET_STACK_TRACE_MALLOC; // Printf("posix_memalign: %zx %zu\n", alignment, size); return asan_posix_memalign(memptr, alignment, size, &stack); } INTERCEPTOR(void*, valloc, uptr size) { GET_STACK_TRACE_MALLOC; return asan_valloc(size, &stack); } INTERCEPTOR(void*, pvalloc, uptr size) { GET_STACK_TRACE_MALLOC; return asan_pvalloc(size, &stack); } INTERCEPTOR(void, malloc_stats, void) { __asan_print_accumulated_stats(); } #if SANITIZER_ANDROID // Format of __libc_malloc_dispatch has changed in Android L. // While we are moving towards a solution that does not depend on bionic // internals, here is something to support both K* and L releases. struct MallocDebugK { void *(*malloc)(uptr bytes); void (*free)(void *mem); void *(*calloc)(uptr n_elements, uptr elem_size); void *(*realloc)(void *oldMem, uptr bytes); void *(*memalign)(uptr alignment, uptr bytes); uptr (*malloc_usable_size)(void *mem); }; struct MallocDebugL { void *(*calloc)(uptr n_elements, uptr elem_size); void (*free)(void *mem); fake_mallinfo (*mallinfo)(void); void *(*malloc)(uptr bytes); uptr (*malloc_usable_size)(void *mem); void *(*memalign)(uptr alignment, uptr bytes); int (*posix_memalign)(void **memptr, uptr alignment, uptr size); void* (*pvalloc)(uptr size); void *(*realloc)(void *oldMem, uptr bytes); void* (*valloc)(uptr size); }; ALIGNED(32) const MallocDebugK asan_malloc_dispatch_k = { WRAP(malloc), WRAP(free), WRAP(calloc), WRAP(realloc), WRAP(memalign), WRAP(malloc_usable_size)}; ALIGNED(32) const MallocDebugL asan_malloc_dispatch_l = { WRAP(calloc), WRAP(free), WRAP(mallinfo), WRAP(malloc), WRAP(malloc_usable_size), WRAP(memalign), WRAP(posix_memalign), WRAP(pvalloc), WRAP(realloc), WRAP(valloc)}; namespace __asan { void ReplaceSystemMalloc() { void **__libc_malloc_dispatch_p = (void **)AsanDlSymNext("__libc_malloc_dispatch"); if (__libc_malloc_dispatch_p) { // Decide on K vs L dispatch format by the presence of // __libc_malloc_default_dispatch export in libc. void *default_dispatch_p = AsanDlSymNext("__libc_malloc_default_dispatch"); if (default_dispatch_p) *__libc_malloc_dispatch_p = (void *)&asan_malloc_dispatch_k; else *__libc_malloc_dispatch_p = (void *)&asan_malloc_dispatch_l; } } } // namespace __asan #else // SANITIZER_ANDROID namespace __asan { void ReplaceSystemMalloc() { } } // namespace __asan #endif // SANITIZER_ANDROID #endif // SANITIZER_FREEBSD || SANITIZER_LINUX <|endoftext|>
<commit_before>// Copyright (c) 2010 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 "remoting/host/session_manager.h" #include <algorithm> #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/stl_util-inl.h" #include "media/base/data_buffer.h" #include "remoting/base/protocol_decoder.h" #include "remoting/host/client_connection.h" #include "remoting/host/encoder.h" namespace remoting { // By default we capture 20 times a second. This number is obtained by // experiment to provide good latency. static const double kDefaultCaptureRate = 20.0; // Interval that we perform rate regulation. static const base::TimeDelta kRateControlInterval = base::TimeDelta::FromSeconds(1); // We divide the pending update stream number by this value to determine the // rate divider. static const int kSlowDownFactor = 10; // A list of dividers used to divide the max rate to determine the current // capture rate. static const int kRateDividers[] = {1, 2, 4, 8, 16}; SessionManager::SessionManager( MessageLoop* capture_loop, MessageLoop* encode_loop, MessageLoop* network_loop, Capturer* capturer, Encoder* encoder) : capture_loop_(capture_loop), encode_loop_(encode_loop), network_loop_(network_loop), capturer_(capturer), encoder_(encoder), rate_(kDefaultCaptureRate), started_(false), recordings_(0), max_rate_(kDefaultCaptureRate), rate_control_started_(false) { DCHECK(capture_loop_); DCHECK(encode_loop_); DCHECK(network_loop_); } SessionManager::~SessionManager() { clients_.clear(); } void SessionManager::Start() { capture_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoStart)); } void SessionManager::DoStart() { DCHECK_EQ(capture_loop_, MessageLoop::current()); if (started_) { NOTREACHED() << "Record session already started"; return; } started_ = true; DoCapture(); // Starts the rate regulation. network_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoStartRateControl)); } void SessionManager::DoStartRateControl() { DCHECK_EQ(network_loop_, MessageLoop::current()); if (rate_control_started_) { NOTREACHED() << "Rate regulation already started"; return; } rate_control_started_ = true; ScheduleNextRateControl(); } void SessionManager::Pause() { capture_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoPause)); } void SessionManager::DoPause() { DCHECK_EQ(capture_loop_, MessageLoop::current()); if (!started_) { NOTREACHED() << "Record session not started"; return; } started_ = false; // Pause the rate regulation. network_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoPauseRateControl)); } void SessionManager::DoPauseRateControl() { DCHECK_EQ(network_loop_, MessageLoop::current()); if (!rate_control_started_) { NOTREACHED() << "Rate regulation not started"; return; } rate_control_started_ = false; } void SessionManager::SetMaxRate(double rate) { capture_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoSetMaxRate, rate)); } void SessionManager::AddClient(scoped_refptr<ClientConnection> client) { // Gets the init information for the client. capture_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoGetInitInfo, client)); } void SessionManager::RemoveClient(scoped_refptr<ClientConnection> client) { network_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoRemoveClient, client)); } void SessionManager::DoCapture() { DCHECK_EQ(capture_loop_, MessageLoop::current()); // Make sure we have at most two oustanding recordings. We can simply return // if we can't make a capture now, the next capture will be started by the // end of an encode operation. if (recordings_ >= 2 || !started_) return; base::Time now = base::Time::Now(); base::TimeDelta interval = base::TimeDelta::FromMilliseconds( static_cast<int>(base::Time::kMillisecondsPerSecond / rate_)); base::TimeDelta elapsed = now - last_capture_time_; // If this method is called sonner than the required interval we return // immediately if (elapsed < interval) return; // At this point we are going to perform one capture so save the current time. last_capture_time_ = now; ++recordings_; // Before we actually do a capture, schedule the next one. ScheduleNextCapture(); // And finally perform one capture. DCHECK(capturer_.get()); capturer_->CaptureDirtyRects( NewRunnableMethod(this, &SessionManager::CaptureDoneTask)); } void SessionManager::DoFinishEncode() { DCHECK_EQ(capture_loop_, MessageLoop::current()); // Decrement the number of recording in process since we have completed // one cycle. --recordings_; // Try to do a capture again. Note that the following method may do nothing // if it is too early to perform a capture. if (rate_ > 0) DoCapture(); } void SessionManager::DoEncode(const CaptureData *capture_data) { // Take ownership of capture_data. scoped_ptr<const CaptureData> capture_data_owner(capture_data); DCHECK_EQ(encode_loop_, MessageLoop::current()); DCHECK(encoder_.get()); // TODO(hclam): Enable |force_refresh| if a new client was // added. encoder_->SetSize(capture_data->width_, capture_data->height_); encoder_->SetPixelFormat(capture_data->pixel_format_); encoder_->Encode( capture_data->dirty_rects_, capture_data->data_, capture_data->data_strides_, false, NewCallback(this, &SessionManager::EncodeDataAvailableTask)); } void SessionManager::DoSendUpdate(const UpdateStreamPacketHeader* header, const scoped_refptr<media::DataBuffer> data, Encoder::EncodingState state) { // Take ownership of header. scoped_ptr<const UpdateStreamPacketHeader> header_owner(header); DCHECK_EQ(network_loop_, MessageLoop::current()); for (size_t i = 0; i < clients_.size(); ++i) { if (state & Encoder::EncodingStarting) { clients_[i]->SendBeginUpdateStreamMessage(); } clients_[i]->SendUpdateStreamPacketMessage(header, data); if (state & Encoder::EncodingEnded) { clients_[i]->SendEndUpdateStreamMessage(); } } delete header; } void SessionManager::DoSendInit(scoped_refptr<ClientConnection> client, int width, int height) { DCHECK_EQ(network_loop_, MessageLoop::current()); // Sends the client init information. client->SendInitClientMessage(width, height); } void SessionManager::DoGetInitInfo(scoped_refptr<ClientConnection> client) { DCHECK_EQ(capture_loop_, MessageLoop::current()); // Sends the init message to the cleint. network_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoSendInit, client, capturer_->GetWidth(), capturer_->GetHeight())); // And then add the client to the list so it can receive update stream. // It is important we do so in such order or the client will receive // update stream before init message. network_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoAddClient, client)); } void SessionManager::DoSetRate(double rate) { DCHECK_EQ(capture_loop_, MessageLoop::current()); if (rate == rate_) return; // Change the current capture rate. rate_ = rate; // If we have already started then schedule the next capture with the new // rate. if (started_) ScheduleNextCapture(); } void SessionManager::DoSetMaxRate(double max_rate) { DCHECK_EQ(capture_loop_, MessageLoop::current()); // TODO(hclam): Should also check for small epsilon. if (max_rate != 0) { max_rate_ = max_rate; DoSetRate(max_rate); } else { NOTREACHED() << "Rate is too small."; } } void SessionManager::DoAddClient(scoped_refptr<ClientConnection> client) { DCHECK_EQ(network_loop_, MessageLoop::current()); // TODO(hclam): Force a full frame for next encode. clients_.push_back(client); } void SessionManager::DoRemoveClient(scoped_refptr<ClientConnection> client) { DCHECK_EQ(network_loop_, MessageLoop::current()); // TODO(hclam): Is it correct to do to a scoped_refptr? ClientConnectionList::iterator it = std::find(clients_.begin(), clients_.end(), client); if (it != clients_.end()) clients_.erase(it); } void SessionManager::DoRateControl() { DCHECK_EQ(network_loop_, MessageLoop::current()); // If we have been paused then shutdown the rate regulation loop. if (!rate_control_started_) return; int max_pending_update_streams = 0; for (size_t i = 0; i < clients_.size(); ++i) { max_pending_update_streams = std::max(max_pending_update_streams, clients_[i]->GetPendingUpdateStreamMessages()); } // If |slow_down| equals zero, we have no slow down. size_t slow_down = max_pending_update_streams / kSlowDownFactor; // Set new_rate to -1 for checking later. double new_rate = -1; // If the slow down is too large. if (slow_down >= arraysize(kRateDividers)) { // Then we stop the capture completely. new_rate = 0; } else { // Slow down the capture rate using the divider. new_rate = max_rate_ / kRateDividers[slow_down]; } DCHECK_NE(new_rate, -1.0); // Then set the rate. capture_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoSetRate, new_rate)); ScheduleNextRateControl(); } void SessionManager::ScheduleNextCapture() { DCHECK_EQ(capture_loop_, MessageLoop::current()); if (rate_ == 0) return; base::TimeDelta interval = base::TimeDelta::FromMilliseconds( static_cast<int>(base::Time::kMillisecondsPerSecond / rate_)); capture_loop_->PostDelayedTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoCapture), interval.InMilliseconds()); } void SessionManager::ScheduleNextRateControl() { network_loop_->PostDelayedTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoRateControl), kRateControlInterval.InMilliseconds()); } void SessionManager::CaptureDoneTask() { DCHECK_EQ(capture_loop_, MessageLoop::current()); scoped_ptr<CaptureData> data(new CaptureData); // Save results of the capture. capturer_->GetData(data->data_); capturer_->GetDataStride(data->data_strides_); capturer_->GetDirtyRects(&data->dirty_rects_); data->pixel_format_ = capturer_->GetPixelFormat(); data->width_ = capturer_->GetWidth(); data->height_ = capturer_->GetHeight(); encode_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoEncode, data.release())); } void SessionManager::EncodeDataAvailableTask( const UpdateStreamPacketHeader *header, const scoped_refptr<media::DataBuffer>& data, Encoder::EncodingState state) { DCHECK_EQ(encode_loop_, MessageLoop::current()); // Before a new encode task starts, notify clients a new update // stream is coming. // Notify this will keep a reference to the DataBuffer in the // task. The ownership will eventually pass to the ClientConnections. network_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoSendUpdate, header, data, state)); if (state == Encoder::EncodingEnded) { capture_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoFinishEncode)); } } } // namespace remoting <commit_msg>Fix double deletion in SessionManager<commit_after>// Copyright (c) 2010 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 "remoting/host/session_manager.h" #include <algorithm> #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/stl_util-inl.h" #include "media/base/data_buffer.h" #include "remoting/base/protocol_decoder.h" #include "remoting/host/client_connection.h" #include "remoting/host/encoder.h" namespace remoting { // By default we capture 20 times a second. This number is obtained by // experiment to provide good latency. static const double kDefaultCaptureRate = 20.0; // Interval that we perform rate regulation. static const base::TimeDelta kRateControlInterval = base::TimeDelta::FromSeconds(1); // We divide the pending update stream number by this value to determine the // rate divider. static const int kSlowDownFactor = 10; // A list of dividers used to divide the max rate to determine the current // capture rate. static const int kRateDividers[] = {1, 2, 4, 8, 16}; SessionManager::SessionManager( MessageLoop* capture_loop, MessageLoop* encode_loop, MessageLoop* network_loop, Capturer* capturer, Encoder* encoder) : capture_loop_(capture_loop), encode_loop_(encode_loop), network_loop_(network_loop), capturer_(capturer), encoder_(encoder), rate_(kDefaultCaptureRate), started_(false), recordings_(0), max_rate_(kDefaultCaptureRate), rate_control_started_(false) { DCHECK(capture_loop_); DCHECK(encode_loop_); DCHECK(network_loop_); } SessionManager::~SessionManager() { clients_.clear(); } void SessionManager::Start() { capture_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoStart)); } void SessionManager::DoStart() { DCHECK_EQ(capture_loop_, MessageLoop::current()); if (started_) { NOTREACHED() << "Record session already started"; return; } started_ = true; DoCapture(); // Starts the rate regulation. network_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoStartRateControl)); } void SessionManager::DoStartRateControl() { DCHECK_EQ(network_loop_, MessageLoop::current()); if (rate_control_started_) { NOTREACHED() << "Rate regulation already started"; return; } rate_control_started_ = true; ScheduleNextRateControl(); } void SessionManager::Pause() { capture_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoPause)); } void SessionManager::DoPause() { DCHECK_EQ(capture_loop_, MessageLoop::current()); if (!started_) { NOTREACHED() << "Record session not started"; return; } started_ = false; // Pause the rate regulation. network_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoPauseRateControl)); } void SessionManager::DoPauseRateControl() { DCHECK_EQ(network_loop_, MessageLoop::current()); if (!rate_control_started_) { NOTREACHED() << "Rate regulation not started"; return; } rate_control_started_ = false; } void SessionManager::SetMaxRate(double rate) { capture_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoSetMaxRate, rate)); } void SessionManager::AddClient(scoped_refptr<ClientConnection> client) { // Gets the init information for the client. capture_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoGetInitInfo, client)); } void SessionManager::RemoveClient(scoped_refptr<ClientConnection> client) { network_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoRemoveClient, client)); } void SessionManager::DoCapture() { DCHECK_EQ(capture_loop_, MessageLoop::current()); // Make sure we have at most two oustanding recordings. We can simply return // if we can't make a capture now, the next capture will be started by the // end of an encode operation. if (recordings_ >= 2 || !started_) return; base::Time now = base::Time::Now(); base::TimeDelta interval = base::TimeDelta::FromMilliseconds( static_cast<int>(base::Time::kMillisecondsPerSecond / rate_)); base::TimeDelta elapsed = now - last_capture_time_; // If this method is called sonner than the required interval we return // immediately if (elapsed < interval) return; // At this point we are going to perform one capture so save the current time. last_capture_time_ = now; ++recordings_; // Before we actually do a capture, schedule the next one. ScheduleNextCapture(); // And finally perform one capture. DCHECK(capturer_.get()); capturer_->CaptureDirtyRects( NewRunnableMethod(this, &SessionManager::CaptureDoneTask)); } void SessionManager::DoFinishEncode() { DCHECK_EQ(capture_loop_, MessageLoop::current()); // Decrement the number of recording in process since we have completed // one cycle. --recordings_; // Try to do a capture again. Note that the following method may do nothing // if it is too early to perform a capture. if (rate_ > 0) DoCapture(); } void SessionManager::DoEncode(const CaptureData *capture_data) { // Take ownership of capture_data. scoped_ptr<const CaptureData> capture_data_owner(capture_data); DCHECK_EQ(encode_loop_, MessageLoop::current()); DCHECK(encoder_.get()); // TODO(hclam): Enable |force_refresh| if a new client was // added. encoder_->SetSize(capture_data->width_, capture_data->height_); encoder_->SetPixelFormat(capture_data->pixel_format_); encoder_->Encode( capture_data->dirty_rects_, capture_data->data_, capture_data->data_strides_, false, NewCallback(this, &SessionManager::EncodeDataAvailableTask)); } void SessionManager::DoSendUpdate(const UpdateStreamPacketHeader* header, const scoped_refptr<media::DataBuffer> data, Encoder::EncodingState state) { // Take ownership of header. scoped_ptr<const UpdateStreamPacketHeader> header_owner(header); DCHECK_EQ(network_loop_, MessageLoop::current()); for (size_t i = 0; i < clients_.size(); ++i) { if (state & Encoder::EncodingStarting) { clients_[i]->SendBeginUpdateStreamMessage(); } clients_[i]->SendUpdateStreamPacketMessage(header, data); if (state & Encoder::EncodingEnded) { clients_[i]->SendEndUpdateStreamMessage(); } } } void SessionManager::DoSendInit(scoped_refptr<ClientConnection> client, int width, int height) { DCHECK_EQ(network_loop_, MessageLoop::current()); // Sends the client init information. client->SendInitClientMessage(width, height); } void SessionManager::DoGetInitInfo(scoped_refptr<ClientConnection> client) { DCHECK_EQ(capture_loop_, MessageLoop::current()); // Sends the init message to the cleint. network_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoSendInit, client, capturer_->GetWidth(), capturer_->GetHeight())); // And then add the client to the list so it can receive update stream. // It is important we do so in such order or the client will receive // update stream before init message. network_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoAddClient, client)); } void SessionManager::DoSetRate(double rate) { DCHECK_EQ(capture_loop_, MessageLoop::current()); if (rate == rate_) return; // Change the current capture rate. rate_ = rate; // If we have already started then schedule the next capture with the new // rate. if (started_) ScheduleNextCapture(); } void SessionManager::DoSetMaxRate(double max_rate) { DCHECK_EQ(capture_loop_, MessageLoop::current()); // TODO(hclam): Should also check for small epsilon. if (max_rate != 0) { max_rate_ = max_rate; DoSetRate(max_rate); } else { NOTREACHED() << "Rate is too small."; } } void SessionManager::DoAddClient(scoped_refptr<ClientConnection> client) { DCHECK_EQ(network_loop_, MessageLoop::current()); // TODO(hclam): Force a full frame for next encode. clients_.push_back(client); } void SessionManager::DoRemoveClient(scoped_refptr<ClientConnection> client) { DCHECK_EQ(network_loop_, MessageLoop::current()); // TODO(hclam): Is it correct to do to a scoped_refptr? ClientConnectionList::iterator it = std::find(clients_.begin(), clients_.end(), client); if (it != clients_.end()) clients_.erase(it); } void SessionManager::DoRateControl() { DCHECK_EQ(network_loop_, MessageLoop::current()); // If we have been paused then shutdown the rate regulation loop. if (!rate_control_started_) return; int max_pending_update_streams = 0; for (size_t i = 0; i < clients_.size(); ++i) { max_pending_update_streams = std::max(max_pending_update_streams, clients_[i]->GetPendingUpdateStreamMessages()); } // If |slow_down| equals zero, we have no slow down. size_t slow_down = max_pending_update_streams / kSlowDownFactor; // Set new_rate to -1 for checking later. double new_rate = -1; // If the slow down is too large. if (slow_down >= arraysize(kRateDividers)) { // Then we stop the capture completely. new_rate = 0; } else { // Slow down the capture rate using the divider. new_rate = max_rate_ / kRateDividers[slow_down]; } DCHECK_NE(new_rate, -1.0); // Then set the rate. capture_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoSetRate, new_rate)); ScheduleNextRateControl(); } void SessionManager::ScheduleNextCapture() { DCHECK_EQ(capture_loop_, MessageLoop::current()); if (rate_ == 0) return; base::TimeDelta interval = base::TimeDelta::FromMilliseconds( static_cast<int>(base::Time::kMillisecondsPerSecond / rate_)); capture_loop_->PostDelayedTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoCapture), interval.InMilliseconds()); } void SessionManager::ScheduleNextRateControl() { network_loop_->PostDelayedTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoRateControl), kRateControlInterval.InMilliseconds()); } void SessionManager::CaptureDoneTask() { DCHECK_EQ(capture_loop_, MessageLoop::current()); scoped_ptr<CaptureData> data(new CaptureData); // Save results of the capture. capturer_->GetData(data->data_); capturer_->GetDataStride(data->data_strides_); capturer_->GetDirtyRects(&data->dirty_rects_); data->pixel_format_ = capturer_->GetPixelFormat(); data->width_ = capturer_->GetWidth(); data->height_ = capturer_->GetHeight(); encode_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoEncode, data.release())); } void SessionManager::EncodeDataAvailableTask( const UpdateStreamPacketHeader *header, const scoped_refptr<media::DataBuffer>& data, Encoder::EncodingState state) { DCHECK_EQ(encode_loop_, MessageLoop::current()); // Before a new encode task starts, notify clients a new update // stream is coming. // Notify this will keep a reference to the DataBuffer in the // task. The ownership will eventually pass to the ClientConnections. network_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoSendUpdate, header, data, state)); if (state == Encoder::EncodingEnded) { capture_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &SessionManager::DoFinishEncode)); } } } // namespace remoting <|endoftext|>
<commit_before>/******************************************************************************* * thrill/common/fast_string.hpp * * (Hopefully) fast static-length string implementation. * * Part of Project Thrill. * * Copyright (C) 2015 Alexander Noe <[email protected]> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef THRILL_COMMON_FAST_STRING_HEADER #define THRILL_COMMON_FAST_STRING_HEADER #include <cstdlib> #include <cstring> #include <thrill/common/logger.hpp> #include <thrill/data/serialization.hpp> namespace thrill { namespace common { class FastString { public: FastString() : size_(0) { }; FastString(const FastString& in_str) { // REVIEW(an): maybe use _new char []..._ / delete -> less casts void* begin = ::malloc(in_str.size_); // REVIEW(an): I am a big friend of std::copy instead of memcpy. std::memcpy(begin, in_str.start_, in_str.size_); start_ = reinterpret_cast<const char*>(begin); size_ = in_str.size_; has_data_ = true; }; // REVIEW(an): use ": field_()" _whenever_ possible! FastString(FastString&& other) { start_ = other.start_; size_ = other.size_; has_data_ = other.has_data_; other.has_data_ = false; }; ~FastString() { if (has_data_) std::free((void*)start_); }; static FastString Ref(const char* start, size_t size) { return FastString(start, size, false); } static FastString Take(const char* start, size_t size) { return FastString(start, size, true); } static FastString Copy(const char* start, size_t size) { void* mem = ::malloc(size); std::memcpy(mem, start, size); return FastString(reinterpret_cast<const char*>(mem), size, true); } static FastString Copy(const std::string& in_str) { return Copy(in_str.c_str(), in_str.size()); } // REVIEW(an): rename to Data(), just like std::string. const char* Start() const { return start_; } size_t Size() const { return size_; } FastString& operator = (const FastString& other) { if (has_data_) free((void*) start_); void* mem = ::malloc(other.size_); std::memcpy(mem, other.start_, other.size_); start_ = reinterpret_cast<const char*>(mem); size_ = other.size_; has_data_ = true; return *this; } FastString& operator = (FastString&& other) { if (has_data_) free((void*) start_); start_ = std::move(other.start_); size_ = other.Size(); has_data_ = true; other.has_data_ = false; return *this; } bool operator == (std::string other) const { // REVIEW(an): use std::equal()! return size_ == other.size() && std::strncmp(start_, other.c_str(), size_) == 0; } bool operator != (std::string other) const { return !(operator == (other)); } bool operator == (const FastString& other) const { return size_ == other.Size() && std::strncmp(start_, other.start_, size_) == 0; } bool operator != (const FastString& other) const { return !(operator == (other)); } friend std::ostream& operator << (std::ostream& os, const FastString& fs) { return os.write(fs.Start(), fs.Size()); } std::string ToString() const { return std::string(start_, size_); } protected: FastString(const char* start, size_t size, bool copy) : start_(start), size_(size), has_data_(copy) { }; // REVIEW(an): rename to data_. const char* start_; size_t size_; bool has_data_ = false; }; } // namespace common namespace data { template<typename Archive> struct Serialization<Archive, common::FastString> { static void Serialize(const common::FastString& fs, Archive& ar) { ar.PutVarint(fs.Size()).Append(fs.Start(), fs.Size()); } static common::FastString Deserialize(Archive& ar) { uint64_t size = ar.GetVarint(); void* outdata = ::malloc(size); ar.Read(outdata, size); return common::FastString::Take(reinterpret_cast<const char*>(outdata), size); } }; } //namespace data } // namespace thrill namespace std { //I am very sorry. template <> struct hash<thrill::common::FastString> { size_t operator ()(const thrill::common::FastString& fs) const { unsigned int hash = 0xDEADC0DE; for (size_t ctr = 0; ctr < fs.Size(); ctr++) { hash = ((hash << 5) + hash) + *(fs.Start() + ctr); /* hash * 33 + c */ } return hash; } }; } #endif // !THRILL_COMMON_FAST_STRING_HEADER /******************************************************************************/ <commit_msg>REVIEW CHANGES: use new & std::copy<commit_after>/******************************************************************************* * thrill/common/fast_string.hpp * * (Hopefully) fast static-length string implementation. * * Part of Project Thrill. * * Copyright (C) 2015 Alexander Noe <[email protected]> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef THRILL_COMMON_FAST_STRING_HEADER #define THRILL_COMMON_FAST_STRING_HEADER #include <cstdlib> #include <cstring> #include <thrill/common/logger.hpp> #include <thrill/data/serialization.hpp> namespace thrill { namespace common { class FastString { public: FastString() : size_(0) { }; FastString(const FastString& in_str) { // REVIEW(an): maybe use _new char []..._ / delete -> less casts char* begin = new char[in_str.size_]; // REVIEW(an): I am a big friend of std::copy instead of memcpy. std::copy(in_str.start_, in_str.start_ + in_str.size_, begin); start_ = begin; size_ = in_str.size_; has_data_ = true; }; // REVIEW(an): use ": field_()" _whenever_ possible! FastString(FastString&& other) : FastString(other.start_, other.size_, other.has_data_) { other.has_data_ = false; }; ~FastString() { if (has_data_) delete[](start_); }; static FastString Ref(const char* start, size_t size) { return FastString(start, size, false); } static FastString Take(const char* start, size_t size) { return FastString(start, size, true); } static FastString Copy(const char* start, size_t size) { char* mem = new char[size]; std::copy(start, start + size, mem); return FastString(mem, size, true); } static FastString Copy(const std::string& in_str) { return Copy(in_str.c_str(), in_str.size()); } // REVIEW(an): rename to Data(), just like std::string. const char* Start() const { return start_; } size_t Size() const { return size_; } FastString& operator = (const FastString& other) { if (has_data_) delete[] (start_); char* mem = new char[other.size_]; std::copy(other.start_, other.start_ + other.size_, mem); start_ = mem; size_ = other.size_; has_data_ = true; return *this; } FastString& operator = (FastString&& other) { if (has_data_) delete[] (start_); start_ = std::move(other.start_); size_ = other.Size(); has_data_ = other.has_data_; other.has_data_ = false; return *this; } bool operator == (std::string other) const { // REVIEW(an): use std::equal()! return size_ == other.size() && std::strncmp(start_, other.c_str(), size_) == 0; } bool operator != (std::string other) const { return !(operator == (other)); } bool operator == (const FastString& other) const { return size_ == other.Size() && std::strncmp(start_, other.start_, size_) == 0; } bool operator != (const FastString& other) const { return !(operator == (other)); } friend std::ostream& operator << (std::ostream& os, const FastString& fs) { return os.write(fs.Start(), fs.Size()); } std::string ToString() const { return std::string(start_, size_); } protected: FastString(const char* start, size_t size, bool copy) : start_(start), size_(size), has_data_(copy) { }; // REVIEW(an): rename to data_. const char* start_ = 0; size_t size_; bool has_data_ = false; }; } // namespace common namespace data { template<typename Archive> struct Serialization<Archive, common::FastString> { static void Serialize(const common::FastString& fs, Archive& ar) { ar.PutVarint(fs.Size()).Append(fs.Start(), fs.Size()); } static common::FastString Deserialize(Archive& ar) { uint64_t size = ar.GetVarint(); void* outdata = ::malloc(size); ar.Read(outdata, size); return common::FastString::Take(reinterpret_cast<const char*>(outdata), size); } }; } //namespace data } // namespace thrill namespace std { //I am very sorry. template <> struct hash<thrill::common::FastString> { size_t operator ()(const thrill::common::FastString& fs) const { unsigned int hash = 0xDEADC0DE; for (size_t ctr = 0; ctr < fs.Size(); ctr++) { hash = ((hash << 5) + hash) + *(fs.Start() + ctr); /* hash * 33 + c */ } return hash; } }; } #endif // !THRILL_COMMON_FAST_STRING_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>/******************************************************************************* * thrill/core/stage_builder.hpp * * Part of Project Thrill. * * Copyright (C) 2015 Sebastian Lamm <[email protected]> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef THRILL_CORE_STAGE_BUILDER_HEADER #define THRILL_CORE_STAGE_BUILDER_HEADER #include <thrill/api/collapse.hpp> #include <thrill/api/dia_base.hpp> #include <thrill/common/logger.hpp> #include <thrill/common/stat_logger.hpp> #include <thrill/common/stats_timer.hpp> #include <algorithm> #include <chrono> #include <ctime> #include <functional> #include <iomanip> #include <set> #include <stack> #include <string> #include <utility> #include <vector> namespace thrill { namespace core { using api::DIABase; class Stage { public: explicit Stage(DIABase* node) : node_(node) { } void Execute() { // time_t tt; // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); // STAT(node_->context()) // << "START (EXECUTING) stage" << node_->label() // << "time:" << std::put_time(std::localtime(&tt), "%T"); // timer.Start(); node_->Execute(); // timer.Stop(); // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); // STAT(node_->context()) // << "FINISH (EXECUTING) stage" << node_->label() // << "took (ms)" << timer.Milliseconds() // << "time:" << std::put_time(std::localtime(&tt), "%T"); // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); // STAT(node_->context()) // << "START (PUSHING) stage" << node_->label() // << "time:" << std::put_time(std::localtime(&tt), "%T"); // timer.Start(); node_->PushData(node_->consume_on_push_data()); // timer.Stop(); node_->set_state(api::DIAState::EXECUTED); // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); // STAT(node_->context()) // << "FINISH (PUSHING) stage" << node_->label() // << "took (ms)" << timer.Milliseconds() // << "time:" << std::put_time(std::localtime(&tt), "%T"); } void PushData() { // time_t tt; // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); // STAT(node_->context()) // << "START (PUSHING) stage" << node_->label() // << "time:" << std::put_time(std::localtime(&tt), "%T"); die_unless(!node_->consume_on_push_data()); // timer.Start(); node_->PushData(node_->consume_on_push_data()); node_->set_state(api::DIAState::EXECUTED); // timer.Stop(); // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); // STAT(node_->context()) // << "FINISH (PUSHING) stage" // << node_->label() // << "took (ms)" << timer.Milliseconds() // << "time: " << std::put_time(std::localtime(&tt), "%T"); } void Dispose() { // time_t tt; // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); // STAT(node_->context()) // << "START (DISPOSING) stage" << node_->label() // << "time:" << std::put_time(std::localtime(&tt), "%T"); // timer.Start(); node_->Dispose(); // timer.Stop(); node_->set_state(api::DIAState::DISPOSED); // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); // STAT(node_->context()) // << "FINISH (DISPOSING) stage" << node_->label() // << "took (ms)" << timer.Milliseconds() // << "time:" << std::put_time(std::localtime(&tt), "%T"); } DIABase * node() { return node_; } private: static const bool debug = false; common::StatsTimer<true> timer; DIABase* node_; }; class StageBuilder { public: template <typename T> using mm_set = std::set<T, std::less<T>, mem::Allocator<T> >; void FindStages(DIABase* action, mem::mm_vector<Stage>& stages_result) { LOG << "FINDING stages:"; mm_set<const DIABase*> stages_found( mem::Allocator<const DIABase*>(action->mem_manager())); // Do a reverse DFS and find all stages mem::mm_deque<DIABase*> dia_stack( mem::Allocator<DIABase*>(action->mem_manager())); dia_stack.push_back(action); stages_found.insert(action); stages_result.push_back(Stage(action)); while (!dia_stack.empty()) { DIABase* curr = dia_stack.front(); dia_stack.pop_front(); const auto parents = curr->parents(); for (size_t i = 0; i < parents.size(); ++i) { // Check if parent was already added auto p = parents[i].get(); if (p) { // If not add parent to stages found and result stages stages_found.insert(p); stages_result.push_back(Stage(p)); // If parent was not executed push it to the DFS if (p->state() != api::DIAState::EXECUTED || p->type() == api::DIANodeType::COLLAPSE) { dia_stack.push_back(p); } } } } // Reverse the execution order std::reverse(stages_result.begin(), stages_result.end()); } void RunScope(DIABase* action) { mem::mm_vector<Stage> result( mem::Allocator<Stage>(action->mem_manager())); FindStages(action, result); for (auto s : result) { if (s.node()->state() == api::DIAState::EXECUTED) s.PushData(); if (s.node()->state() == api::DIAState::NEW) s.Execute(); s.node()->UnregisterChilds(); } } static const bool debug = false; }; } // namespace core } // namespace thrill #endif // !THRILL_CORE_STAGE_BUILDER_HEADER /******************************************************************************/ <commit_msg>Reduce logging. Only keep finish events.<commit_after>/******************************************************************************* * thrill/core/stage_builder.hpp * * Part of Project Thrill. * * Copyright (C) 2015 Sebastian Lamm <[email protected]> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef THRILL_CORE_STAGE_BUILDER_HEADER #define THRILL_CORE_STAGE_BUILDER_HEADER #include <thrill/api/collapse.hpp> #include <thrill/api/dia_base.hpp> #include <thrill/common/logger.hpp> #include <thrill/common/stat_logger.hpp> #include <thrill/common/stats_timer.hpp> #include <algorithm> #include <chrono> #include <ctime> #include <functional> #include <iomanip> #include <set> #include <stack> #include <string> #include <utility> #include <vector> namespace thrill { namespace core { using api::DIABase; class Stage { public: explicit Stage(DIABase* node) : node_(node) { } void Execute() { // time_t tt; // timer.Start(); node_->Execute(); // timer.Stop(); // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); // STAT(node_->context()) // << "FINISH (EXECUTING) stage" << node_->label() // << "took (ms)" << timer.Milliseconds() // << "time:" << std::put_time(std::localtime(&tt), "%T"); // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); // timer.Start(); node_->PushData(node_->consume_on_push_data()); // timer.Stop(); node_->set_state(api::DIAState::EXECUTED); // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); // STAT(node_->context()) // << "FINISH (PUSHING) stage" << node_->label() // << "took (ms)" << timer.Milliseconds() // << "time:" << std::put_time(std::localtime(&tt), "%T"); } void PushData() { // time_t tt; die_unless(!node_->consume_on_push_data()); // timer.Start(); node_->PushData(node_->consume_on_push_data()); node_->set_state(api::DIAState::EXECUTED); // timer.Stop(); // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); // STAT(node_->context()) // << "FINISH (PUSHING) stage" // << node_->label() // << "took (ms)" << timer.Milliseconds() // << "time: " << std::put_time(std::localtime(&tt), "%T"); } void Dispose() { // time_t tt; // timer.Start(); node_->Dispose(); // timer.Stop(); node_->set_state(api::DIAState::DISPOSED); // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); // STAT(node_->context()) // << "FINISH (DISPOSING) stage" << node_->label() // << "took (ms)" << timer.Milliseconds() // << "time:" << std::put_time(std::localtime(&tt), "%T"); } DIABase * node() { return node_; } private: static const bool debug = false; common::StatsTimer<true> timer; DIABase* node_; }; class StageBuilder { public: template <typename T> using mm_set = std::set<T, std::less<T>, mem::Allocator<T> >; void FindStages(DIABase* action, mem::mm_vector<Stage>& stages_result) { LOG << "FINDING stages:"; mm_set<const DIABase*> stages_found( mem::Allocator<const DIABase*>(action->mem_manager())); // Do a reverse DFS and find all stages mem::mm_deque<DIABase*> dia_stack( mem::Allocator<DIABase*>(action->mem_manager())); dia_stack.push_back(action); stages_found.insert(action); stages_result.push_back(Stage(action)); while (!dia_stack.empty()) { DIABase* curr = dia_stack.front(); dia_stack.pop_front(); const auto parents = curr->parents(); for (size_t i = 0; i < parents.size(); ++i) { // Check if parent was already added auto p = parents[i].get(); if (p) { // If not add parent to stages found and result stages stages_found.insert(p); stages_result.push_back(Stage(p)); // If parent was not executed push it to the DFS if (p->state() != api::DIAState::EXECUTED || p->type() == api::DIANodeType::COLLAPSE) { dia_stack.push_back(p); } } } } // Reverse the execution order std::reverse(stages_result.begin(), stages_result.end()); } void RunScope(DIABase* action) { mem::mm_vector<Stage> result( mem::Allocator<Stage>(action->mem_manager())); FindStages(action, result); for (auto s : result) { if (s.node()->state() == api::DIAState::EXECUTED) s.PushData(); if (s.node()->state() == api::DIAState::NEW) s.Execute(); s.node()->UnregisterChilds(); } } static const bool debug = false; }; } // namespace core } // namespace thrill #endif // !THRILL_CORE_STAGE_BUILDER_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>// ================================================================================ // == This file is a part of TinkerBell UI Toolkit. (C) 2011-2013, Emil Segers == // == See tinkerbell.h for more information. == // ================================================================================ #include "tinkerbell.h" #include "tb_skin.h" #include "tb_widgets_reader.h" #include "tb_language.h" #include "tb_font_renderer.h" #include "tb_addon.h" #include <stdlib.h> #include <assert.h> #include <stdarg.h> #include <stdio.h> #include <ctype.h> namespace tinkerbell { static const char *empty = ""; inline void safe_delete(char *&str) { if(str != empty && str) free(str); str = const_cast<char*>(empty); } // ================================================================ TBRenderer *g_renderer = nullptr; TBSkin *g_tb_skin = nullptr; TBWidgetsReader *g_widgets_reader = nullptr; TBLanguage *g_tb_lng = nullptr; TBFontManager *g_font_manager = nullptr; bool init_tinkerbell(TBRenderer *renderer, const char *lng_file) { g_renderer = renderer; g_tb_lng = new TBLanguage; g_tb_lng->Load(lng_file); g_font_manager = new TBFontManager(); g_tb_skin = new TBSkin(); g_widgets_reader = TBWidgetsReader::Create(); return TBInitAddons(); } void shutdown_tinkerbell() { TBShutdownAddons(); delete g_widgets_reader; delete g_tb_skin; delete g_font_manager; delete g_tb_lng; } // == TBRect ====================================================== bool TBRect::Intersects(const TBRect &rect) const { if (IsEmpty() || rect.IsEmpty()) return false; if (x + w > rect.x && x < rect.x + rect.w && y + h > rect.y && y < rect.y + rect.h) return true; return false; } TBRect TBRect::Union(const TBRect &rect) const { assert(!IsInsideOut()); assert(!rect.IsInsideOut()); if (IsEmpty()) return rect; if (rect.IsEmpty()) return *this; int minx = MIN(x, rect.x); int miny = MIN(y, rect.y); int maxx = x + w > rect.x + rect.w ? x + w : rect.x + rect.w; int maxy = y + h > rect.y + rect.h ? y + h : rect.y + rect.h; return TBRect(minx, miny, maxx - minx, maxy - miny); } TBRect TBRect::Clip(const TBRect &clip_rect) const { assert(!clip_rect.IsInsideOut()); TBRect tmp; if (!Intersects(clip_rect)) return tmp; tmp.x = MAX(x, clip_rect.x); tmp.y = MAX(y, clip_rect.y); tmp.w = MIN(x + w, clip_rect.x + clip_rect.w) - tmp.x; tmp.h = MIN(y + h, clip_rect.y + clip_rect.h) - tmp.y; return tmp; } // =================================================================== const char *stristr(const char *arg1, const char *arg2) { const char *a, *b; for(;*arg1;*arg1++) { a = arg1; b = arg2; while(toupper(*a++) == toupper(*b++)) if(!*b) return arg1; } return nullptr; } // == TBStr ========================================================== TBStr::TBStr() : TBStrC(empty) { } TBStr::TBStr(const char* str) : TBStrC(str == empty ? empty : strdup(str)) { if (!s) s = const_cast<char*>(empty); } TBStr::TBStr(const TBStr &str) : TBStrC(str.s == empty ? empty : strdup(str.s)) { if (!s) s = const_cast<char*>(empty); } TBStr::TBStr(const char* str, int len) : TBStrC(empty) { Set(str, len); } TBStr::~TBStr() { safe_delete(s); } bool TBStr::Set(const char* str, int len) { safe_delete(s); if (len == TB_ALL_TO_TERMINATION) len = strlen(str); if (char *new_s = (char *) malloc(len + 1)) { s = new_s; memcpy(s, str, len); s[len] = 0; return true; } return false; } bool TBStr::SetFormatted(const char* format, ...) { safe_delete(s); if (!format) return true; va_list ap; int max_len = 64; char *new_s = nullptr; while (true) { if (char *tris_try_new_s = (char *) realloc(new_s, max_len)) { new_s = tris_try_new_s; va_start(ap, format); int ret = vsnprintf(new_s, max_len, format, ap); va_end(ap); if (ret > max_len) // Needed size is known (+2 for termination and avoid ambiguity) max_len = ret + 2; else if (ret == -1 || ret >= max_len - 1) // Handle some buggy vsnprintf implementations. max_len *= 2; else // Everything fit for sure { s = new_s; return true; } } else { // Out of memory free(new_s); break; } } return false; } void TBStr::Clear() { safe_delete(s); } void TBStr::Remove(int ofs, int len) { assert(ofs >= 0 && (ofs + len <= (int)strlen(s))); if (!len) return; char *dst = s + ofs; char *src = s + ofs + len; while (*src != 0) *(dst++) = *(src++); *dst = *src; } bool TBStr::Insert(int ofs, const char *ins, int ins_len) { int len1 = strlen(s); if (ins_len == TB_ALL_TO_TERMINATION) ins_len = strlen(ins); int newlen = len1 + ins_len; if (char *news = (char *) malloc(newlen + 1)) { memcpy(&news[0], s, ofs); memcpy(&news[ofs], ins, ins_len); memcpy(&news[ofs + ins_len], &s[ofs], len1 - ofs); news[newlen] = 0; safe_delete(s); s = news; return true; } return false; } // == TBID ================================================================================================== #ifdef _DEBUG // Hash table for checking if we get any collisions (same hash value for TBID's created // from different strings) static TBHashTableAutoDeleteOf<TBID> all_id_hash; static bool is_adding = false; void TBID::Set(uint32 newid) { id = newid; debug_string.Clear(); if (!is_adding) { if (TBID *other_id = all_id_hash.Get(id)) { assert(other_id->debug_string.IsEmpty()); } else { is_adding = true; all_id_hash.Add(id, new TBID(*this)); is_adding = false; } } } void TBID::Set(const TBID &newid) { id = newid; TB_IF_DEBUG(debug_string.Set(newid.debug_string)); if (!is_adding) { if (TBID *other_id = all_id_hash.Get(id)) { // If this happens, 2 different strings result in the same hash. // It might be a good idea to change one of them, but it might not matter. assert(other_id->debug_string.Equals(debug_string)); } else { is_adding = true; all_id_hash.Add(id, new TBID(*this)); is_adding = false; } } } void TBID::Set(const char *string) { id = TBGetHash(string); TB_IF_DEBUG(debug_string.Set(string)); if (!is_adding) { if (TBID *other_id = all_id_hash.Get(id)) { assert(other_id->debug_string.Equals(debug_string)); } else { is_adding = true; all_id_hash.Add(id, new TBID(*this)); is_adding = false; } } } #endif // _DEBUG // == TBColor =============================================================================================== void TBColor::SetFromString(const char *str, int len) { int r, g, b, a; if (len == 9 && sscanf(str, "#%2x%2x%2x%2x", &r, &g, &b, &a) == 4) // rrggbbaa Set(TBColor(r, g, b, a)); else if (len == 7 && sscanf(str, "#%2x%2x%2x", &r, &g, &b) == 3) // rrggbb Set(TBColor(r, g, b)); else if (len == 5 && sscanf(str, "#%1x%1x%1x%1x", &r, &g, &b, &a) == 4) // rgba Set(TBColor(r + (r << 4), g + (g << 4), b + (b << 4), a + (a << 4))); else if (len == 4 && sscanf(str, "#%1x%1x%1x", &r, &g, &b) == 3) // rgb Set(TBColor(r + (r << 4), g + (g << 4), b + (b << 4))); else Set(TBColor()); } // == TBDimensionConverter ================================================================================== void TBDimensionConverter::SetDPI(int src_dpi, int dst_dpi) { m_src_dpi = src_dpi; m_dst_dpi = dst_dpi; m_dst_dpi_str.Clear(); if (NeedConversion()) m_dst_dpi_str.SetFormatted("@%d", m_dst_dpi); } void TBDimensionConverter::GetDstDPIFilename(const char *filename, TBTempBuffer *tempbuf) const { int dot_pos = 0; for (dot_pos = strlen(filename) - 1; dot_pos > 0; dot_pos--) if (filename[dot_pos] == '.') break; tempbuf->ResetAppendPos(); tempbuf->Append(filename, dot_pos); tempbuf->AppendString(GetDstDPIStr()); tempbuf->AppendString(filename + dot_pos); } int TBDimensionConverter::DpToPx(int dp) const { if (dp <= TB_INVALID_DIMENSION || dp == 0 || !NeedConversion()) return dp; if (dp > 0) { dp = dp * m_dst_dpi / m_src_dpi; return MAX(dp, 1); } else { dp = dp * m_dst_dpi / m_src_dpi; return MIN(dp, -1); } } int TBDimensionConverter::GetPxFromString(const char *str, int def_value) const { if (!str || !isdigit(*str)) return def_value; int len = strlen(str); int val = atoi(str); // "dp" and unspecified unit is dp. if ((len > 0 && isdigit(str[len - 1])) || (len > 2 && strcmp(str + len - 2, "dp") == 0)) return DpToPx(val); else return val; } int TBDimensionConverter::GetPxFromValue(TBValue *value, int def_value) const { if (!value) return def_value; if (value->GetType() == TBValue::TYPE::TYPE_INT) return DpToPx(value->GetInt()); else if (value->GetType() == TBValue::TYPE::TYPE_FLOAT) // FIX: We might want float versions of all dimension functions. return DpToPx((int)value->GetFloat()); return GetPxFromString(value->GetString(), def_value); } }; // namespace tinkerbell <commit_msg>Compilefix for some compilers.<commit_after>// ================================================================================ // == This file is a part of TinkerBell UI Toolkit. (C) 2011-2013, Emil Segers == // == See tinkerbell.h for more information. == // ================================================================================ #include "tinkerbell.h" #include "tb_skin.h" #include "tb_widgets_reader.h" #include "tb_language.h" #include "tb_font_renderer.h" #include "tb_addon.h" #include <stdlib.h> #include <assert.h> #include <stdarg.h> #include <stdio.h> #include <ctype.h> namespace tinkerbell { static const char *empty = ""; inline void safe_delete(char *&str) { if(str != empty && str) free(str); str = const_cast<char*>(empty); } // ================================================================ TBRenderer *g_renderer = nullptr; TBSkin *g_tb_skin = nullptr; TBWidgetsReader *g_widgets_reader = nullptr; TBLanguage *g_tb_lng = nullptr; TBFontManager *g_font_manager = nullptr; bool init_tinkerbell(TBRenderer *renderer, const char *lng_file) { g_renderer = renderer; g_tb_lng = new TBLanguage; g_tb_lng->Load(lng_file); g_font_manager = new TBFontManager(); g_tb_skin = new TBSkin(); g_widgets_reader = TBWidgetsReader::Create(); return TBInitAddons(); } void shutdown_tinkerbell() { TBShutdownAddons(); delete g_widgets_reader; delete g_tb_skin; delete g_font_manager; delete g_tb_lng; } // == TBRect ====================================================== bool TBRect::Intersects(const TBRect &rect) const { if (IsEmpty() || rect.IsEmpty()) return false; if (x + w > rect.x && x < rect.x + rect.w && y + h > rect.y && y < rect.y + rect.h) return true; return false; } TBRect TBRect::Union(const TBRect &rect) const { assert(!IsInsideOut()); assert(!rect.IsInsideOut()); if (IsEmpty()) return rect; if (rect.IsEmpty()) return *this; int minx = MIN(x, rect.x); int miny = MIN(y, rect.y); int maxx = x + w > rect.x + rect.w ? x + w : rect.x + rect.w; int maxy = y + h > rect.y + rect.h ? y + h : rect.y + rect.h; return TBRect(minx, miny, maxx - minx, maxy - miny); } TBRect TBRect::Clip(const TBRect &clip_rect) const { assert(!clip_rect.IsInsideOut()); TBRect tmp; if (!Intersects(clip_rect)) return tmp; tmp.x = MAX(x, clip_rect.x); tmp.y = MAX(y, clip_rect.y); tmp.w = MIN(x + w, clip_rect.x + clip_rect.w) - tmp.x; tmp.h = MIN(y + h, clip_rect.y + clip_rect.h) - tmp.y; return tmp; } // =================================================================== const char *stristr(const char *arg1, const char *arg2) { const char *a, *b; for(;*arg1;*arg1++) { a = arg1; b = arg2; while(toupper(*a++) == toupper(*b++)) if(!*b) return arg1; } return nullptr; } // == TBStr ========================================================== TBStr::TBStr() : TBStrC(empty) { } TBStr::TBStr(const char* str) : TBStrC(str == empty ? empty : strdup(str)) { if (!s) s = const_cast<char*>(empty); } TBStr::TBStr(const TBStr &str) : TBStrC(str.s == empty ? empty : strdup(str.s)) { if (!s) s = const_cast<char*>(empty); } TBStr::TBStr(const char* str, int len) : TBStrC(empty) { Set(str, len); } TBStr::~TBStr() { safe_delete(s); } bool TBStr::Set(const char* str, int len) { safe_delete(s); if (len == TB_ALL_TO_TERMINATION) len = strlen(str); if (char *new_s = (char *) malloc(len + 1)) { s = new_s; memcpy(s, str, len); s[len] = 0; return true; } return false; } bool TBStr::SetFormatted(const char* format, ...) { safe_delete(s); if (!format) return true; va_list ap; int max_len = 64; char *new_s = nullptr; while (true) { if (char *tris_try_new_s = (char *) realloc(new_s, max_len)) { new_s = tris_try_new_s; va_start(ap, format); int ret = vsnprintf(new_s, max_len, format, ap); va_end(ap); if (ret > max_len) // Needed size is known (+2 for termination and avoid ambiguity) max_len = ret + 2; else if (ret == -1 || ret >= max_len - 1) // Handle some buggy vsnprintf implementations. max_len *= 2; else // Everything fit for sure { s = new_s; return true; } } else { // Out of memory free(new_s); break; } } return false; } void TBStr::Clear() { safe_delete(s); } void TBStr::Remove(int ofs, int len) { assert(ofs >= 0 && (ofs + len <= (int)strlen(s))); if (!len) return; char *dst = s + ofs; char *src = s + ofs + len; while (*src != 0) *(dst++) = *(src++); *dst = *src; } bool TBStr::Insert(int ofs, const char *ins, int ins_len) { int len1 = strlen(s); if (ins_len == TB_ALL_TO_TERMINATION) ins_len = strlen(ins); int newlen = len1 + ins_len; if (char *news = (char *) malloc(newlen + 1)) { memcpy(&news[0], s, ofs); memcpy(&news[ofs], ins, ins_len); memcpy(&news[ofs + ins_len], &s[ofs], len1 - ofs); news[newlen] = 0; safe_delete(s); s = news; return true; } return false; } // == TBID ================================================================================================== #ifdef _DEBUG // Hash table for checking if we get any collisions (same hash value for TBID's created // from different strings) static TBHashTableAutoDeleteOf<TBID> all_id_hash; static bool is_adding = false; void TBID::Set(uint32 newid) { id = newid; debug_string.Clear(); if (!is_adding) { if (TBID *other_id = all_id_hash.Get(id)) { assert(other_id->debug_string.IsEmpty()); } else { is_adding = true; all_id_hash.Add(id, new TBID(*this)); is_adding = false; } } } void TBID::Set(const TBID &newid) { id = newid; TB_IF_DEBUG(debug_string.Set(newid.debug_string)); if (!is_adding) { if (TBID *other_id = all_id_hash.Get(id)) { // If this happens, 2 different strings result in the same hash. // It might be a good idea to change one of them, but it might not matter. assert(other_id->debug_string.Equals(debug_string)); } else { is_adding = true; all_id_hash.Add(id, new TBID(*this)); is_adding = false; } } } void TBID::Set(const char *string) { id = TBGetHash(string); TB_IF_DEBUG(debug_string.Set(string)); if (!is_adding) { if (TBID *other_id = all_id_hash.Get(id)) { assert(other_id->debug_string.Equals(debug_string)); } else { is_adding = true; all_id_hash.Add(id, new TBID(*this)); is_adding = false; } } } #endif // _DEBUG // == TBColor =============================================================================================== void TBColor::SetFromString(const char *str, int len) { int r, g, b, a; if (len == 9 && sscanf(str, "#%2x%2x%2x%2x", &r, &g, &b, &a) == 4) // rrggbbaa Set(TBColor(r, g, b, a)); else if (len == 7 && sscanf(str, "#%2x%2x%2x", &r, &g, &b) == 3) // rrggbb Set(TBColor(r, g, b)); else if (len == 5 && sscanf(str, "#%1x%1x%1x%1x", &r, &g, &b, &a) == 4) // rgba Set(TBColor(r + (r << 4), g + (g << 4), b + (b << 4), a + (a << 4))); else if (len == 4 && sscanf(str, "#%1x%1x%1x", &r, &g, &b) == 3) // rgb Set(TBColor(r + (r << 4), g + (g << 4), b + (b << 4))); else Set(TBColor()); } // == TBDimensionConverter ================================================================================== void TBDimensionConverter::SetDPI(int src_dpi, int dst_dpi) { m_src_dpi = src_dpi; m_dst_dpi = dst_dpi; m_dst_dpi_str.Clear(); if (NeedConversion()) m_dst_dpi_str.SetFormatted("@%d", m_dst_dpi); } void TBDimensionConverter::GetDstDPIFilename(const char *filename, TBTempBuffer *tempbuf) const { int dot_pos = 0; for (dot_pos = strlen(filename) - 1; dot_pos > 0; dot_pos--) if (filename[dot_pos] == '.') break; tempbuf->ResetAppendPos(); tempbuf->Append(filename, dot_pos); tempbuf->AppendString(GetDstDPIStr()); tempbuf->AppendString(filename + dot_pos); } int TBDimensionConverter::DpToPx(int dp) const { if (dp <= TB_INVALID_DIMENSION || dp == 0 || !NeedConversion()) return dp; if (dp > 0) { dp = dp * m_dst_dpi / m_src_dpi; return MAX(dp, 1); } else { dp = dp * m_dst_dpi / m_src_dpi; return MIN(dp, -1); } } int TBDimensionConverter::GetPxFromString(const char *str, int def_value) const { if (!str || !isdigit(*str)) return def_value; int len = strlen(str); int val = atoi(str); // "dp" and unspecified unit is dp. if ((len > 0 && isdigit(str[len - 1])) || (len > 2 && strcmp(str + len - 2, "dp") == 0)) return DpToPx(val); else return val; } int TBDimensionConverter::GetPxFromValue(TBValue *value, int def_value) const { if (!value) return def_value; if (value->GetType() == TBValue::TYPE_INT) return DpToPx(value->GetInt()); else if (value->GetType() == TBValue::TYPE_FLOAT) // FIX: We might want float versions of all dimension functions. return DpToPx((int)value->GetFloat()); return GetPxFromString(value->GetString(), def_value); } }; // namespace tinkerbell <|endoftext|>
<commit_before>//**************************************************************************** // SurveySim //............................................................................. // written by Noah Kurinsky and Anna Sajina // The purpose of this program is to use MCMC to determine the luminosity function evolution and redshift distribution based on infrared survey data -- the details of the input observations as well as default model parameters are passed to this program via a series of fits files (model.fits, observations.fits, templates.fits) which are set using either idl (SurveySim.pro) or python (SurveySim.py). //**************************************************************************** #include "simulator.h" #include "functions.h" #include "mc_util.h" #include <stdio.h> using namespace std; int main(int argc,char** argv){ Configuration q(argc,argv); int logflag=q.oprint; LOG_DEBUG(printf("Fitting Code Compiled: %s\n\n",__DATE__)); RandomNumberGenerator rng; LOG_DEBUG(printf("Axis 1: %s\nAxis 2: %s\n",get_axis_type(q.axes[0]).c_str(),get_axis_type(q.axes[1]).c_str())); if(logflag >= 2) q.print(); //general variable declarations bool accept; bool saved=false; unsigned long i,m; unsigned long pi; double trial; //this array holds phi0,L0,alpha,beta,p, and q double lpars[LUMPARS]; double lmin[LUMPARS]; double lmax[LUMPARS]; double parfixed[LUMPARS]; //printf(q.LFparameters) q.LFparameters(lpars); q.LFparameters(lmin,q.min); q.LFparameters(lmax,q.max); double CE = q.colorEvolution[q.value]; double CEmin = q.colorEvolution[q.min]; double CEmax = q.colorEvolution[q.max]; double ZBC = q.colorZCut[q.value]; double ZBCmin = q.colorZCut[q.min]; double ZBCmax = q.colorZCut[q.max]; q.LFparameters(parfixed,q.fixed); string pnames[] = {"PHI0","L0","ALPHA","BETA","P","Q","P2","Q2","ZBP","ZBQ","FA0","T1","T2","ZBT","FCOMP","FCOLD"}; string countnames[]= {"dnds1","dnds2","dnds3"}; lumfunct lf(q.lfDist); lf.set_params(lpars); //initialize simulator simulator survey(q); survey.set_color_exp(CE,ZBC); //color evolution survey.set_fagn_pars(lpars); survey.set_lumfunct(&lf); products output; ResultChain final_counts(3,q.nsim); if(q.simflag){ //observations not provided LOG_CRITICAL(printf("Simulating a survey only \n")); //run number of simulations to get counts range LOG_CRITICAL(printf("Beginning Simulation Loop (%lu runs)\n",q.nsim)); for(unsigned long simi=1;simi<q.nsim;simi++){ output=survey.simulate(); final_counts.add_link(output.dnds,output.chisqr); if((simi % 20) == 0){ LOG_CRITICAL(printf("Current Iteration: %lu\n",simi)); } } LOG_DEBUG(printf("\nSaving Output\n")); saved = survey.save(q.outfile); LOG_DEBUG(printf("Saving Counts\n")); saved &= final_counts.save(q.outfile,countnames,"Simulated Counts"); } else{ MCChains mcchain(q.nchain,q.nparams,q.runs,q.conv_step); MCChains burnchain(q.nchain,q.nparams,q.runs,q.conv_step); mcchain.set_constraints(q.rmax,q.a_ci); burnchain.set_constraints(q.rmax,q.a_ci); //mcmc variables and arrays double chi_min=1.0E+4; double tchi_min=chi_min; vector<int>::const_iterator p; double *setvars[q.nparams]; ParameterSettings pset(q.nparams); unique_ptr<string[]> parnames (new string[q.nparams]); vector<double> results,means(q.nparams); ResultChain counts(3,q.nchain*q.runs); MetropSampler metrop(q.nchain,q.temp,q.learningRate,q.idealpct,q.annrng,q.oprint); if(q.nparams > 0){ //observations provided, not all parameters fixed double ptemp[q.nchain][q.nparams]; vector<double > means(q.nparams); double pcurrent[q.nchain][q.nparams]; LOG_DEBUG(printf("Initializing Chains\n")); for(pi=0, p = q.param_inds.begin(); p != q.param_inds.end(); ++p,++pi){ setvars[pi] = &(lpars[*p]); pcurrent[0][pi] = *(setvars[pi]); pset.set(pi,lmin[*p],lmax[*p],(lmax[*p] - lmin[*p])/q.sigmaSize,lpars[*p]); } if(q.vary_cexp){ setvars[q.cind] = &CE; pcurrent[0][q.cind] = *(setvars[pi]); pset.set(q.cind,CEmin,CEmax,(CEmax - CEmin)/q.sigmaSize,CE); pi++; } if(q.vary_zbc){ setvars[q.zbcind] = &ZBC; pcurrent[0][q.zbcind] = *(setvars[pi]); pset.set(q.zbcind,ZBCmin,ZBCmax,(ZBCmax - ZBCmin)/6.0,ZBC); } for(m=1;m<q.nchain;m++){ for(pi=0;pi<q.nparams;pi++) pcurrent[m][pi] = rng.flat(pset.min[pi],pset.max[pi]); } LOG_INFO(printf("\n ---------- Beginning MC Burn-in Phase ---------- \n")); i=0; for (i=0;i<q.burn_num;i++){ for (m=0;m<q.nchain;m++){ vector<double> results; for(pi=0;pi<q.nparams;pi++) means[pi] = pcurrent[m][pi]; rng.gaussian_mv(means,pset.covar,pset.min,pset.max,results); for(pi = 0;pi<q.nparams;pi++){ *(setvars[pi]) = ptemp[m][pi] = results[pi]; } LOG_DEBUG(printf("%lu %lu -",(i+1),(m+1))); for(pi=0;pi<LUMPARS;pi++) LOG_DEBUG(printf(" %5.2lf",lpars[pi])); LOG_DEBUG(printf(" %5.2lf : ",(q.vary_cexp ? ptemp[m][q.cind] : CE))); LOG_DEBUG(printf(" %5.2lf : ",(q.vary_zbc ? ptemp[m][q.zbcind] : ZBC))); lf.set_params(lpars); survey.set_color_exp(CE,ZBC); survey.set_fagn_pars(lpars); output=survey.simulate(); trial=output.chisqr; LOG_DEBUG(printf("Iteration Chi-Square: %lf",trial)); if(trial < chi_min){ LOG_DEBUG(printf(" -- Current Best Trial")); chi_min=trial; for(pi=0;pi<q.nparams;pi++) pset.best[pi]=ptemp[m][pi]; } LOG_DEBUG(printf("\n")); accept = metrop.accept(m,trial); if(accept) for(pi=0;pi<q.nparams;pi++) pcurrent[m][pi]=ptemp[m][pi]; burnchain.add_link(m,ptemp[m],trial,accept); } if(((i+1) % q.burn_step) == 0){ LOG_INFO(printf("\nAcceptance: %5.1lf%% (T=%8.2e)\n",metrop.acceptance_rate()*100.0,metrop.temperature())); LOG_INFO(printf("Covariance Matrix:\n")); for(int pi=0;pi<pset.covar.size();pi++){ LOG_INFO(printf("\t[")); for(int pj=0;pj<pset.covar[pi].size();pj++) LOG_INFO(printf("%6.2lf ",pset.covar[pi][pj])); LOG_INFO(printf("]\n")); } if(not metrop.anneal()) i = q.runs; burnchain.get_stdev(pset.sigma.data()); burnchain.get_covariance(pset.covar); } } for(m=0;m<q.nchain;m++) for(pi=0;pi<q.nparams;pi++) pcurrent[m][pi] = pset.best[pi]; metrop.reset(); LOG_INFO(printf("\n\n ---------------- Fitting Start ---------------- \n Total Run Number: %ld\n\n",q.runs)); for (i=0;i<q.runs;i++){ for (m=0;m<q.nchain;m++){ vector<double> results; for(pi = 0;pi<q.nparams;pi++) means[pi] = pcurrent[m][pi]; rng.gaussian_mv(means,pset.covar,pset.min,pset.max,results); for(pi = 0;pi<q.nparams;pi++){ *(setvars[pi]) = ptemp[m][pi] = results[pi]; } LOG_DEBUG(printf("%lu %lu -",(i+1),(m+1))); for(pi=0;pi<q.nparams;pi++) LOG_DEBUG(printf(" %lf",ptemp[m][pi])); LOG_DEBUG(printf(" : ")); lf.set_params(lpars); survey.set_color_exp(CE,ZBC); survey.set_fagn_pars(lpars); output=survey.simulate(); trial=output.chisqr; LOG_DEBUG(printf("Model Chi-Square: %lf",trial)); accept = metrop.accept(m,trial); mcchain.add_link(m,ptemp[m],trial,accept); counts.add_link(output.dnds,trial); if(accept){ LOG_DEBUG(printf(" -- Accepted\n")); for(pi=0;pi<q.nparams;pi++) pcurrent[m][pi]=ptemp[m][pi]; } else LOG_DEBUG(printf(" -- Rejected\n")); } if(((i+1) % q.conv_step) == 0){ LOG_INFO(printf("Checking Convergence\n")); if (i < q.burn_num) metrop.anneal(); mcchain.get_stdev(pset.sigma.data()); mcchain.get_covariance(pset.covar); if(mcchain.converged()){ LOG_INFO(printf("Chains Converged!\n")); i = q.runs;} else LOG_INFO(printf("Chains Have Not Converged\n")); } } mcchain.get_best_link(pset.best.data(),chi_min); LOG_INFO(printf("Best fit:\n")); for(pi=0;pi<q.param_inds.size();pi++){ lpars[q.param_inds[pi]] = pset.best[pi]; LOG_INFO(printf("%s : %lf +\\- %lf\n",pnames[q.param_inds[pi]].c_str(),pset.best[pi],pset.sigma[pi])); } lf.set_params(lpars); if(q.vary_cexp){ CE=pset.best[q.cind]; LOG_DEBUG(printf("CEXP : %lf +\\- %lf\n",pset.best[pi],pset.sigma[pi])); pi++; } if(q.vary_zbc){ ZBC=pset.best[q.zbcind]; LOG_DEBUG(printf("ZBC : %lf +\\- %lf\n",pset.best[pi],pset.sigma[pi])); } survey.set_color_exp(CE,ZBC); survey.set_fagn_pars(lpars); LOG_INFO(printf("\nCovariance Matrix:\n")); for(int pi=0;pi<pset.covar.size();pi++){ LOG_INFO(printf("\t[")); for(int pj=0;pj<pset.covar[pi].size();pj++) LOG_INFO(printf("%6.2lf ",pset.covar[pi][pj])); LOG_INFO(printf("]\n")); } LOG_INFO(printf("Final Acceptance Rate: %lf%%\n",metrop.mean_acceptance()*100)); } LOG_INFO(printf("\nRunning Best Fit...\n")); output=survey.simulate(); tchi_min = output.chisqr; LOG_INFO(printf("Saving Initial Survey\n")); saved = survey.save(q.outfile); for(pi = 0;pi<q.nparams;pi++) means[pi] = pset.best[pi]; for(unsigned long i=1;i<q.nsim;i++){ rng.gaussian_mv(means,pset.covar,pset.min,pset.max,results); for(pi = 0;pi<q.nparams;pi++){ *(setvars[pi]) = results[pi]; } lf.set_params(lpars); survey.set_color_exp(CE,ZBC); survey.set_fagn_pars(lpars); output=survey.simulate(); if(output.chisqr < tchi_min){ tchi_min = output.chisqr; LOG_INFO(printf("Saving new minimum (%lu/%lu)...",i,q.nsim)); saved = survey.save(q.outfile); } final_counts.add_link(output.dnds,output.chisqr); } LOG_INFO(printf("Saved Chi2: %lf (%lf)\n",tchi_min,chi_min)); for(pi=0, p= q.param_inds.begin(); p != q.param_inds.end();pi++,p++) parnames[pi] = pnames[*p]; if(q.vary_cexp) parnames[q.cind] = "CEXP"; if(q.vary_zbc) parnames[q.zbcind] = "ZBC"; LOG_DEBUG(printf("Saving Chains\n")); saved &= mcchain.save(q.outfile,parnames.get(),"MCMC Chain Record"); LOG_DEBUG(printf("Saving Counts\n")); saved &= counts.save(q.outfile,countnames,"Simulation Counts"); LOG_DEBUG(printf("Saving Final Counts\n")); saved &= final_counts.save(q.outfile,countnames,"Final Monte Carlo Counts"); } saved ? printf("Save Successful") : printf("Save Failed"); LOG_CRITICAL(printf("\nFitting Complete\n\n")); return saved ? 0 : 1; } <commit_msg>edited covar output<commit_after>//**************************************************************************** // SurveySim //............................................................................. // written by Noah Kurinsky and Anna Sajina // The purpose of this program is to use MCMC to determine the luminosity function evolution and redshift distribution based on infrared survey data -- the details of the input observations as well as default model parameters are passed to this program via a series of fits files (model.fits, observations.fits, templates.fits) which are set using either idl (SurveySim.pro) or python (SurveySim.py). //**************************************************************************** #include "simulator.h" #include "functions.h" #include "mc_util.h" #include <stdio.h> using namespace std; int main(int argc,char** argv){ Configuration q(argc,argv); int logflag=q.oprint; LOG_DEBUG(printf("Fitting Code Compiled: %s\n\n",__DATE__)); RandomNumberGenerator rng; LOG_DEBUG(printf("Axis 1: %s\nAxis 2: %s\n",get_axis_type(q.axes[0]).c_str(),get_axis_type(q.axes[1]).c_str())); if(logflag >= 2) q.print(); //general variable declarations bool accept; bool saved=false; unsigned long i,m; unsigned long pi; double trial; //this array holds phi0,L0,alpha,beta,p, and q double lpars[LUMPARS]; double lmin[LUMPARS]; double lmax[LUMPARS]; double parfixed[LUMPARS]; //printf(q.LFparameters) q.LFparameters(lpars); q.LFparameters(lmin,q.min); q.LFparameters(lmax,q.max); double CE = q.colorEvolution[q.value]; double CEmin = q.colorEvolution[q.min]; double CEmax = q.colorEvolution[q.max]; double ZBC = q.colorZCut[q.value]; double ZBCmin = q.colorZCut[q.min]; double ZBCmax = q.colorZCut[q.max]; q.LFparameters(parfixed,q.fixed); string pnames[] = {"PHI0","L0","ALPHA","BETA","P","Q","P2","Q2","ZBP","ZBQ","FA0","T1","T2","ZBT","FCOMP","FCOLD"}; string countnames[]= {"dnds1","dnds2","dnds3"}; lumfunct lf(q.lfDist); lf.set_params(lpars); //initialize simulator simulator survey(q); survey.set_color_exp(CE,ZBC); //color evolution survey.set_fagn_pars(lpars); survey.set_lumfunct(&lf); products output; ResultChain final_counts(3,q.nsim); if(q.simflag){ //observations not provided LOG_CRITICAL(printf("Simulating a survey only \n")); //run number of simulations to get counts range LOG_CRITICAL(printf("Beginning Simulation Loop (%lu runs)\n",q.nsim)); for(unsigned long simi=1;simi<q.nsim;simi++){ output=survey.simulate(); final_counts.add_link(output.dnds,output.chisqr); if((simi % 20) == 0){ LOG_CRITICAL(printf("Current Iteration: %lu\n",simi)); } } LOG_DEBUG(printf("\nSaving Output\n")); saved = survey.save(q.outfile); LOG_DEBUG(printf("Saving Counts\n")); saved &= final_counts.save(q.outfile,countnames,"Simulated Counts"); } else{ MCChains mcchain(q.nchain,q.nparams,q.runs,q.conv_step); MCChains burnchain(q.nchain,q.nparams,q.runs,q.conv_step); mcchain.set_constraints(q.rmax,q.a_ci); burnchain.set_constraints(q.rmax,q.a_ci); //mcmc variables and arrays double chi_min=1.0E+4; double tchi_min=chi_min; vector<int>::const_iterator p; double *setvars[q.nparams]; ParameterSettings pset(q.nparams); unique_ptr<string[]> parnames (new string[q.nparams]); vector<double> results,means(q.nparams); ResultChain counts(3,q.nchain*q.runs); MetropSampler metrop(q.nchain,q.temp,q.learningRate,q.idealpct,q.annrng,q.oprint); if(q.nparams > 0){ //observations provided, not all parameters fixed double ptemp[q.nchain][q.nparams]; vector<double > means(q.nparams); double pcurrent[q.nchain][q.nparams]; LOG_DEBUG(printf("Initializing Chains\n")); for(pi=0, p = q.param_inds.begin(); p != q.param_inds.end(); ++p,++pi){ setvars[pi] = &(lpars[*p]); pcurrent[0][pi] = *(setvars[pi]); pset.set(pi,lmin[*p],lmax[*p],(lmax[*p] - lmin[*p])/q.sigmaSize,lpars[*p]); } if(q.vary_cexp){ setvars[q.cind] = &CE; pcurrent[0][q.cind] = *(setvars[pi]); pset.set(q.cind,CEmin,CEmax,(CEmax - CEmin)/q.sigmaSize,CE); pi++; } if(q.vary_zbc){ setvars[q.zbcind] = &ZBC; pcurrent[0][q.zbcind] = *(setvars[pi]); pset.set(q.zbcind,ZBCmin,ZBCmax,(ZBCmax - ZBCmin)/6.0,ZBC); } for(m=1;m<q.nchain;m++){ for(pi=0;pi<q.nparams;pi++) pcurrent[m][pi] = rng.flat(pset.min[pi],pset.max[pi]); } LOG_INFO(printf("\n ---------- Beginning MC Burn-in Phase ---------- \n")); i=0; for (i=0;i<q.burn_num;i++){ for (m=0;m<q.nchain;m++){ vector<double> results; for(pi=0;pi<q.nparams;pi++) means[pi] = pcurrent[m][pi]; rng.gaussian_mv(means,pset.covar,pset.min,pset.max,results); for(pi = 0;pi<q.nparams;pi++){ *(setvars[pi]) = ptemp[m][pi] = results[pi]; } LOG_DEBUG(printf("%lu %lu -",(i+1),(m+1))); for(pi=0;pi<LUMPARS;pi++) LOG_DEBUG(printf(" %5.2lf",lpars[pi])); LOG_DEBUG(printf(" %5.2lf : ",(q.vary_cexp ? ptemp[m][q.cind] : CE))); LOG_DEBUG(printf(" %5.2lf : ",(q.vary_zbc ? ptemp[m][q.zbcind] : ZBC))); lf.set_params(lpars); survey.set_color_exp(CE,ZBC); survey.set_fagn_pars(lpars); output=survey.simulate(); trial=output.chisqr; LOG_DEBUG(printf("Iteration Chi-Square: %lf",trial)); if(trial < chi_min){ LOG_DEBUG(printf(" -- Current Best Trial")); chi_min=trial; for(pi=0;pi<q.nparams;pi++) pset.best[pi]=ptemp[m][pi]; } LOG_DEBUG(printf("\n")); accept = metrop.accept(m,trial); if(accept) for(pi=0;pi<q.nparams;pi++) pcurrent[m][pi]=ptemp[m][pi]; burnchain.add_link(m,ptemp[m],trial,accept); } if(((i+1) % q.burn_step) == 0){ LOG_INFO(printf("\nAcceptance: %5.1lf%% (T=%8.2e)\n",metrop.acceptance_rate()*100.0,metrop.temperature())); //for(int pi=0;pi<pset.covar.size();pi++){ // LOG_INFO(printf("\t[")); // for(int pj=0;pj<pset.covar[pi].size();pj++) // LOG_INFO(printf("%6.2lf ",pset.covar[pi][pj])); // LOG_INFO(printf("]\n")); //} if(not metrop.anneal()) i = q.runs; //burnchain.get_stdev(pset.sigma.data()); //burnchain.get_covariance(pset.covar); } } for(m=0;m<q.nchain;m++) for(pi=0;pi<q.nparams;pi++) pcurrent[m][pi] = pset.best[pi]; metrop.reset(); LOG_INFO(printf("\n\n ---------------- Fitting Start ---------------- \n Total Run Number: %ld\n\n",q.runs)); for (i=0;i<q.runs;i++){ for (m=0;m<q.nchain;m++){ vector<double> results; for(pi = 0;pi<q.nparams;pi++) means[pi] = pcurrent[m][pi]; rng.gaussian_mv(means,pset.covar,pset.min,pset.max,results); for(pi = 0;pi<q.nparams;pi++){ *(setvars[pi]) = ptemp[m][pi] = results[pi]; } LOG_DEBUG(printf("%lu %lu -",(i+1),(m+1))); for(pi=0;pi<q.nparams;pi++) LOG_DEBUG(printf(" %lf",ptemp[m][pi])); LOG_DEBUG(printf(" : ")); lf.set_params(lpars); survey.set_color_exp(CE,ZBC); survey.set_fagn_pars(lpars); output=survey.simulate(); trial=output.chisqr; LOG_DEBUG(printf("Model Chi-Square: %lf",trial)); accept = metrop.accept(m,trial); mcchain.add_link(m,ptemp[m],trial,accept); counts.add_link(output.dnds,trial); if(accept){ LOG_DEBUG(printf(" -- Accepted\n")); for(pi=0;pi<q.nparams;pi++) pcurrent[m][pi]=ptemp[m][pi]; } else LOG_DEBUG(printf(" -- Rejected\n")); } if(((i+1) % q.conv_step) == 0){ LOG_INFO(printf("Checking Convergence\n")); if (i < q.burn_num) metrop.anneal(); mcchain.get_stdev(pset.sigma.data()); mcchain.get_covariance(pset.covar); if(mcchain.converged()){ LOG_INFO(printf("Chains Converged!\n")); i = q.runs;} else LOG_INFO(printf("Chains Have Not Converged\n")); } } mcchain.get_best_link(pset.best.data(),chi_min); LOG_INFO(printf("Best fit:\n")); for(pi=0;pi<q.param_inds.size();pi++){ lpars[q.param_inds[pi]] = pset.best[pi]; LOG_INFO(printf("%s : %lf +\\- %lf\n",pnames[q.param_inds[pi]].c_str(),pset.best[pi],pset.sigma[pi])); } lf.set_params(lpars); if(q.vary_cexp){ CE=pset.best[q.cind]; LOG_DEBUG(printf("CEXP : %lf +\\- %lf\n",pset.best[pi],pset.sigma[pi])); pi++; } if(q.vary_zbc){ ZBC=pset.best[q.zbcind]; LOG_DEBUG(printf("ZBC : %lf +\\- %lf\n",pset.best[pi],pset.sigma[pi])); } survey.set_color_exp(CE,ZBC); survey.set_fagn_pars(lpars); LOG_INFO(printf("\nCovariance Matrix:\n")); for(int pi=0;pi<pset.covar.size();pi++){ LOG_INFO(printf("\t[")); for(int pj=0;pj<pset.covar[pi].size();pj++) LOG_INFO(printf("%6.2lf ",pset.covar[pi][pj])); LOG_INFO(printf("]\n")); } LOG_INFO(printf("Final Acceptance Rate: %lf%%\n",metrop.mean_acceptance()*100)); } LOG_INFO(printf("\nRunning Best Fit...\n")); output=survey.simulate(); tchi_min = output.chisqr; LOG_INFO(printf("Saving Initial Survey\n")); saved = survey.save(q.outfile); for(pi = 0;pi<q.nparams;pi++) means[pi] = pset.best[pi]; for(unsigned long i=1;i<q.nsim;i++){ rng.gaussian_mv(means,pset.covar,pset.min,pset.max,results); for(pi = 0;pi<q.nparams;pi++){ *(setvars[pi]) = results[pi]; } lf.set_params(lpars); survey.set_color_exp(CE,ZBC); survey.set_fagn_pars(lpars); output=survey.simulate(); if(output.chisqr < tchi_min){ tchi_min = output.chisqr; LOG_INFO(printf("Saving new minimum (%lu/%lu)...",i,q.nsim)); saved = survey.save(q.outfile); } final_counts.add_link(output.dnds,output.chisqr); } LOG_INFO(printf("Saved Chi2: %lf (%lf)\n",tchi_min,chi_min)); for(pi=0, p= q.param_inds.begin(); p != q.param_inds.end();pi++,p++) parnames[pi] = pnames[*p]; if(q.vary_cexp) parnames[q.cind] = "CEXP"; if(q.vary_zbc) parnames[q.zbcind] = "ZBC"; LOG_DEBUG(printf("Saving Chains\n")); saved &= mcchain.save(q.outfile,parnames.get(),"MCMC Chain Record"); LOG_DEBUG(printf("Saving Counts\n")); saved &= counts.save(q.outfile,countnames,"Simulation Counts"); LOG_DEBUG(printf("Saving Final Counts\n")); saved &= final_counts.save(q.outfile,countnames,"Final Monte Carlo Counts"); } saved ? printf("Save Successful") : printf("Save Failed"); LOG_CRITICAL(printf("\nFitting Complete\n\n")); return saved ? 0 : 1; } <|endoftext|>
<commit_before>#include <algorithm> #include <atomic> #include <iostream> #include <limits> #include <utility> #include <vector> #include <getopt.h> #include <signal.h> #include <unistd.h> #include <zcm/zcm-cpp.hpp> using namespace std; static atomic_int done {0}; static void sighandler(int signal) { done++; if (done == 3) exit(1); } struct Args { string infile = ""; string outfile = ""; bool init(int argc, char *argv[]) { struct option long_opts[] = { { "help", no_argument, 0, 'h' }, { "output", required_argument, 0, 'o' }, { 0, 0, 0, 0 } }; int c; while ((c = getopt_long(argc, argv, "ho:f", long_opts, 0)) >= 0) { switch (c) { case 'o': outfile = string(optarg); break; case 'h': default: usage(); return false; }; } if (optind != argc - 1) { cerr << "Please specify a logfile" << endl; usage(); return false; } infile = string(argv[optind]); if (outfile.empty()) { cerr << "Must specify output file" << endl; return false; } return true; } void usage() { cerr << "usage: zcm-log-repair [options] [FILE]" << endl << "" << endl << " Reads packets from an ZCM log file and re-writes that log file" << endl << " ensuring that all events are stored in recv_utime order." << endl << " This is generally only required if the original log was captured" << endl << " using multiple zcm shards and the user requires a strict ordering" << endl << " of events in the log." << endl << "" << endl << "Options:" << endl << "" << endl << " -o, --output=filename specify output file" << endl << " -h, --help Shows some help text and exits." << endl << endl; } }; struct LogRepair { Args args; zcm::LogFile* logIn = nullptr; zcm::LogFile* logOut = nullptr; zcm::LogFile* logVer = nullptr; const zcm::LogEvent* event; off_t length; off_t offset; vector<pair<int64_t, off_t>> timestamps; size_t progress; LogRepair() { } ~LogRepair() { if (logIn) { if (logIn->good()) logIn->close(); delete logIn; } if (logOut) { if (logOut->good()) logOut->close(); delete logOut; } if (logVer) { if (logVer->good()) logVer->close(); delete logVer; } } bool init(int argc, char *argv[]) { if (!args.init(argc, argv)) return false; logIn = new zcm::LogFile(args.infile, "r"); if (!logIn->good()) { cerr << "Error: Failed to open '" << args.infile << "'" << endl; return false; } logOut = new zcm::LogFile(args.outfile, "w"); if (!logOut->good()) { cerr << "Error: Failed to create output log" << endl; return false; } fseeko(logIn->getFilePtr(), 0, SEEK_END); length = ftello(logIn->getFilePtr()); fseeko(logIn->getFilePtr(), 0, SEEK_SET); timestamps.reserve(1e6); return true; } int run() { cout << "Reading log" << endl; progress = 0; cout << progress << "%" << flush; while (true) { if (done) return 1; offset = ftello(logIn->getFilePtr()); event = logIn->readNextEvent(); if (!event) break; timestamps.emplace_back(event->timestamp, offset); size_t p = (size_t)((100 * offset) / length); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } cout << endl << "Read " << timestamps.size() << " events" << endl; cout << "Repairing log data" << endl; sort(timestamps.begin(), timestamps.end()); cout << "Writing new log" << endl; progress = 0; cout << progress << "%" << flush; for (size_t i = 0; i < timestamps.size(); ++i) { if (done) return 1; size_t p = (100 * i) / timestamps.size(); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } logOut->writeEvent(logIn->readEventAtOffset(timestamps[i].second)); } cout << endl << "Flushing to disk" << endl; logOut->close(); cout << "Verifying output" << endl; logVer = new zcm::LogFile(args.outfile, "r"); if (!logVer->good()) { cerr << "Error: Failed to open output log for verification" << endl; return 1; } size_t i = 0; progress = 0; cout << progress << "%" << flush; while (true) { if (done) return 1; event = logIn->readNextEvent(); if (event->timestamp != timestamps[i++].first) { cerr << endl << "Error: output log timestamp mismatch" << endl; return 1; } size_t p = (100 * i) / timestamps.size(); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } return 0; } }; int main(int argc, char* argv[]) { LogRepair lr; if (!lr.init(argc, argv)) return 1; // Register signal handlers signal(SIGINT, sighandler); signal(SIGQUIT, sighandler); signal(SIGTERM, sighandler); int ret = lr.run(); if (ret == 0) { cout << endl << "Success" << endl; } else { cerr << endl << "Failure" << endl; } return ret; } <commit_msg>actually think this is working now<commit_after>#include <algorithm> #include <atomic> #include <iostream> #include <limits> #include <utility> #include <vector> #include <getopt.h> #include <signal.h> #include <unistd.h> #include <zcm/zcm-cpp.hpp> using namespace std; static atomic_int done {0}; static void sighandler(int signal) { done++; if (done == 3) exit(1); } struct Args { string infile = ""; string outfile = ""; bool verifyOnly = false; bool init(int argc, char *argv[]) { struct option long_opts[] = { { "help", no_argument, 0, 'h' }, { "output", required_argument, 0, 'o' }, { "verify-only", no_argument, 0, 'v' }, { 0, 0, 0, 0 } }; int c; while ((c = getopt_long(argc, argv, "ho:v", long_opts, 0)) >= 0) { switch (c) { case 'o': outfile = string(optarg); break; case 'v': verifyOnly = true; break; case 'h': default: usage(); return false; }; } if (optind != argc - 1) { cerr << "Please specify a logfile" << endl; usage(); return false; } infile = string(argv[optind]); if (outfile.empty()) { cerr << "Must specify output file" << endl; return false; } return true; } void usage() { cerr << "usage: zcm-log-repair [options] [FILE]" << endl << "" << endl << " Reads packets from an ZCM log file and re-writes that log file" << endl << " ensuring that all events are stored in recv_utime order." << endl << " This is generally only required if the original log was captured" << endl << " using multiple zcm shards and the user requires a strict ordering" << endl << " of events in the log." << endl << "" << endl << "Options:" << endl << "" << endl << " -o, --output=filename specify output file" << endl << " -v, --verify-only Skip writing output file, only verify that" << endl << " an already existing output file is the repaired" << endl << " version of the input." << endl << " -h, --help Shows some help text and exits." << endl << endl; } }; struct LogRepair { Args args; zcm::LogFile* logIn = nullptr; zcm::LogFile* logOut = nullptr; zcm::LogFile* logVer = nullptr; const zcm::LogEvent* event; off_t length; off_t offset; vector<pair<int64_t, off_t>> timestamps; size_t progress; LogRepair() { } ~LogRepair() { if (logIn) { if (logIn->good()) logIn->close(); delete logIn; } if (logOut) { if (logOut->good()) logOut->close(); delete logOut; } if (logVer) { if (logVer->good()) logVer->close(); delete logVer; } } bool init(int argc, char *argv[]) { if (!args.init(argc, argv)) return false; logIn = new zcm::LogFile(args.infile, "r"); if (!logIn->good()) { cerr << "Error: Failed to open '" << args.infile << "'" << endl; return false; } if (!args.verifyOnly) { logOut = new zcm::LogFile(args.outfile, "w"); if (!logOut->good()) { cerr << "Error: Failed to create output log" << endl; return false; } } fseeko(logIn->getFilePtr(), 0, SEEK_END); length = ftello(logIn->getFilePtr()); fseeko(logIn->getFilePtr(), 0, SEEK_SET); timestamps.reserve(1e6); return true; } int run() { cout << "Reading log" << endl; progress = 0; cout << progress << "%" << flush; while (true) { if (done) return 1; offset = ftello(logIn->getFilePtr()); event = logIn->readNextEvent(); if (!event) break; timestamps.emplace_back(event->timestamp, offset); size_t p = (size_t)((100 * offset) / length); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } cout << endl << "Read " << timestamps.size() << " events" << endl; cout << "Repairing log data" << endl; sort(timestamps.begin(), timestamps.end()); if (!args.verifyOnly) { cout << "Writing new log" << endl; progress = 0; cout << progress << "%" << flush; for (size_t i = 0; i < timestamps.size(); ++i) { if (done) return 1; logOut->writeEvent(logIn->readEventAtOffset(timestamps[i].second)); size_t p = (100 * i) / timestamps.size(); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } cout << endl << "Flushing to disk" << endl; logOut->close(); } cout << "Verifying output" << endl; logVer = new zcm::LogFile(args.outfile, "r"); if (!logVer->good()) { cerr << "Error: Failed to open output log for verification" << endl; return 1; } size_t i = 0; progress = 0; cout << progress << "%" << flush; while (true) { if (done) return 1; event = logVer->readNextEvent(); if (!event) break; if (event->timestamp != timestamps[i++].first) { cerr << endl << "Error: output log timestamp mismatch" << endl; cerr << "Expected " << timestamps[i].first << " got " << event->timestamp << " (idx " << i << ")" << endl; return 1; } size_t p = (100 * i) / timestamps.size(); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } if (i < timestamps.size()) { cerr << endl << "Error: output log was missing " << timestamps.size() - i << " events" << endl; } return 0; } }; int main(int argc, char* argv[]) { LogRepair lr; if (!lr.init(argc, argv)) return 1; // Register signal handlers signal(SIGINT, sighandler); signal(SIGQUIT, sighandler); signal(SIGTERM, sighandler); int ret = lr.run(); if (ret == 0) { cout << endl << "Success" << endl; } else { cerr << endl << "Failure" << endl; } return ret; } <|endoftext|>
<commit_before>/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil; -*- */ /* * Copyright (c) 2008 litl, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <config.h> #include <glib.h> #include <glib-object.h> #include <gjs/gjs-module.h> #include <util/glib.h> #include <util/crash.h> typedef struct _GjsUnitTestFixture GjsUnitTestFixture; struct _GjsUnitTestFixture { JSRuntime *runtime; JSContext *context; GjsContext *gjs_context; }; static void test_error_reporter(JSContext *context, const char *message, JSErrorReport *report) { g_printerr("error reported by test: %s\n", message); } static void _gjs_unit_test_fixture_begin (GjsUnitTestFixture *fixture) { fixture->gjs_context = gjs_context_new (); fixture->context = (JSContext *) gjs_context_get_native_context (fixture->gjs_context); fixture->runtime = JS_GetRuntime(fixture->context); JS_BeginRequest(fixture->context); JS_SetErrorReporter(fixture->context, test_error_reporter); } static void _gjs_unit_test_fixture_finish (GjsUnitTestFixture *fixture) { JS_EndRequest(fixture->context); g_object_unref(fixture->gjs_context); } static void gjstest_test_func_gjs_context_construct_destroy(void) { GjsContext *context; /* Construct twice just to possibly a case where global state from * the first leaks. */ context = gjs_context_new (); g_object_unref (context); context = gjs_context_new (); g_object_unref (context); } static void gjstest_test_func_gjs_context_construct_eval(void) { GjsContext *context; int estatus; GError *error = NULL; context = gjs_context_new (); if (!gjs_context_eval (context, "1+1", -1, "<input>", &estatus, &error)) g_error ("%s", error->message); g_object_unref (context); } static void gjstest_test_func_gjs_context_fixture(void) { GjsUnitTestFixture fixture; JSContext *context; JSObject *global; _gjs_unit_test_fixture_begin(&fixture); context = fixture.context; global = JS_GetGlobalObject(context); JSCompartment *oldCompartment = JS_EnterCompartment(context, global); JS_LeaveCompartment(context, oldCompartment); _gjs_unit_test_fixture_finish(&fixture); } #define N_ELEMS 15 static void gjstest_test_func_gjs_jsapi_util_array(void) { GjsUnitTestFixture fixture; JSContext *context; JSObject *global; GjsRootedArray *array; int i; jsval value; _gjs_unit_test_fixture_begin(&fixture); context = fixture.context; array = gjs_rooted_array_new(); global = JS_GetGlobalObject(context); JSCompartment *oldCompartment = JS_EnterCompartment(context, global); for (i = 0; i < N_ELEMS; i++) { value = STRING_TO_JSVAL(JS_NewStringCopyZ(context, "abcdefghijk")); gjs_rooted_array_append(context, array, value); } JS_GC(JS_GetRuntime(context)); for (i = 0; i < N_ELEMS; i++) { char *ascii; value = gjs_rooted_array_get(context, array, i); g_assert(JSVAL_IS_STRING(value)); gjs_string_to_utf8(context, value, &ascii); g_assert(strcmp(ascii, "abcdefghijk") == 0); g_free(ascii); } gjs_rooted_array_free(context, array, TRUE); JS_LeaveCompartment(context, oldCompartment); _gjs_unit_test_fixture_finish(&fixture); } #undef N_ELEMS static void gjstest_test_func_gjs_jsapi_util_string_js_string_utf8(void) { GjsUnitTestFixture fixture; JSContext *context; JSObject *global; const char *utf8_string = "\303\211\303\226 foobar \343\203\237"; char *utf8_result; jsval js_string; _gjs_unit_test_fixture_begin(&fixture); context = fixture.context; global = JS_GetGlobalObject(context); JSCompartment *oldCompartment = JS_EnterCompartment(context, global); g_assert(gjs_string_from_utf8(context, utf8_string, -1, &js_string) == JS_TRUE); g_assert(JSVAL_IS_STRING(js_string)); g_assert(gjs_string_to_utf8(context, js_string, &utf8_result) == JS_TRUE); JS_LeaveCompartment(context, oldCompartment); _gjs_unit_test_fixture_finish(&fixture); g_assert(g_str_equal(utf8_string, utf8_result)); g_free(utf8_result); } static void gjstest_test_func_gjs_stack_dump(void) { GjsContext *context; /* TODO this test could be better - maybe expose dumpstack as a JS API * so that we have a JS stack to dump? At least here we're getting some * coverage. */ context = gjs_context_new(); gjs_dumpstack(); g_object_unref(context); gjs_dumpstack(); } static void gjstest_test_func_gjs_jsapi_util_error_throw(void) { GjsUnitTestFixture fixture; JSContext *context; JSObject *global; jsval exc, value, previous; char *s = NULL; int strcmp_result; _gjs_unit_test_fixture_begin(&fixture); context = fixture.context; global = JS_GetGlobalObject(context); JSCompartment *oldCompartment = JS_EnterCompartment(context, global); /* Test that we can throw */ gjs_throw(context, "This is an exception %d", 42); g_assert(JS_IsExceptionPending(context)); exc = JSVAL_VOID; JS_GetPendingException(context, &exc); g_assert(!JSVAL_IS_VOID(exc)); value = JSVAL_VOID; JS_GetProperty(context, JSVAL_TO_OBJECT(exc), "message", &value); g_assert(JSVAL_IS_STRING(value)); gjs_string_to_utf8(context, value, &s); g_assert(s != NULL); strcmp_result = strcmp(s, "This is an exception 42"); free(s); if (strcmp_result != 0) g_error("Exception has wrong message '%s'", s); /* keep this around before we clear it */ previous = exc; JS_AddValueRoot(context, &previous); JS_ClearPendingException(context); g_assert(!JS_IsExceptionPending(context)); /* Check that we don't overwrite a pending exception */ JS_SetPendingException(context, previous); g_assert(JS_IsExceptionPending(context)); gjs_throw(context, "Second different exception %s", "foo"); g_assert(JS_IsExceptionPending(context)); exc = JSVAL_VOID; JS_GetPendingException(context, &exc); g_assert(!JSVAL_IS_VOID(exc)); g_assert(JSVAL_TO_OBJECT(exc) == JSVAL_TO_OBJECT(previous)); JS_RemoveValueRoot(context, &previous); JS_LeaveCompartment(context, oldCompartment); _gjs_unit_test_fixture_finish(&fixture); } static void gjstest_test_func_util_glib_strv_concat_null(void) { char **ret; ret = gjs_g_strv_concat(NULL, 0); g_assert(ret != NULL); g_assert(ret[0] == NULL); g_strfreev(ret); } static void gjstest_test_func_util_glib_strv_concat_pointers(void) { char *strv0[2] = {(char*)"foo", NULL}; char *strv1[1] = {NULL}; char **strv2 = NULL; char *strv3[2] = {(char*)"bar", NULL}; char **stuff[4]; char **ret; stuff[0] = strv0; stuff[1] = strv1; stuff[2] = strv2; stuff[3] = strv3; ret = gjs_g_strv_concat(stuff, 4); g_assert(ret != NULL); g_assert_cmpstr(ret[0], ==, strv0[0]); /* same string */ g_assert(ret[0] != strv0[0]); /* different pointer */ g_assert_cmpstr(ret[1], ==, strv3[0]); g_assert(ret[1] != strv3[0]); g_assert(ret[2] == NULL); g_strfreev(ret); } static void gjstest_test_strip_shebang_no_advance_for_no_shebang(void) { const char *script = "foo\nbar"; gssize script_len_original = strlen(script); gssize script_len = script_len_original; int line_number = 1; const char *stripped = gjs_strip_unix_shebang(script, &script_len, &line_number); g_assert_cmpstr(script, ==, stripped); g_assert(script_len == script_len_original); g_assert(line_number == 1); } static void gjstest_test_strip_shebang_advance_for_shebang(void) { const char *script = "#!foo\nbar"; gssize script_len_original = strlen(script); gssize script_len = script_len_original; int line_number = 1; const char *stripped = gjs_strip_unix_shebang(script, &script_len, &line_number); g_assert_cmpstr(stripped, ==, "bar"); g_assert(script_len == 3); g_assert(line_number == 2); } static void gjstest_test_strip_shebang_return_null_for_just_shebang(void) { const char *script = "#!foo"; gssize script_len_original = strlen(script); gssize script_len = script_len_original; int line_number = 1; const char *stripped = gjs_strip_unix_shebang(script, &script_len, &line_number); g_assert(stripped == NULL); g_assert(script_len == 0); g_assert(line_number == -1); } int main(int argc, char **argv) { gjs_crash_after_timeout(60*7); /* give the unit tests 7 minutes to complete */ g_test_init(&argc, &argv, NULL); g_test_add_func("/gjs/context/construct/destroy", gjstest_test_func_gjs_context_construct_destroy); g_test_add_func("/gjs/context/construct/eval", gjstest_test_func_gjs_context_construct_eval); g_test_add_func("/gjs/context/fixture", gjstest_test_func_gjs_context_fixture); g_test_add_func("/gjs/jsapi/util/array", gjstest_test_func_gjs_jsapi_util_array); g_test_add_func("/gjs/jsapi/util/error/throw", gjstest_test_func_gjs_jsapi_util_error_throw); g_test_add_func("/gjs/jsapi/util/string/js/string/utf8", gjstest_test_func_gjs_jsapi_util_string_js_string_utf8); g_test_add_func("/gjs/jsutil/strip_shebang/no_shebang", gjstest_test_strip_shebang_no_advance_for_no_shebang); g_test_add_func("/gjs/jsutil/strip_shebang/have_shebang", gjstest_test_strip_shebang_advance_for_shebang); g_test_add_func("/gjs/jsutil/strip_shebang/only_shebang", gjstest_test_strip_shebang_return_null_for_just_shebang); g_test_add_func("/gjs/stack/dump", gjstest_test_func_gjs_stack_dump); g_test_add_func("/util/glib/strv/concat/null", gjstest_test_func_util_glib_strv_concat_null); g_test_add_func("/util/glib/strv/concat/pointers", gjstest_test_func_util_glib_strv_concat_pointers); g_test_run(); return 0; } <commit_msg>gjs-tests: Remove runtime from fixture<commit_after>/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil; -*- */ /* * Copyright (c) 2008 litl, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <config.h> #include <glib.h> #include <glib-object.h> #include <gjs/gjs-module.h> #include <util/glib.h> #include <util/crash.h> typedef struct _GjsUnitTestFixture GjsUnitTestFixture; struct _GjsUnitTestFixture { JSContext *context; GjsContext *gjs_context; }; static void test_error_reporter(JSContext *context, const char *message, JSErrorReport *report) { g_printerr("error reported by test: %s\n", message); } static void _gjs_unit_test_fixture_begin (GjsUnitTestFixture *fixture) { fixture->gjs_context = gjs_context_new (); fixture->context = (JSContext *) gjs_context_get_native_context (fixture->gjs_context); JS_BeginRequest(fixture->context); JS_SetErrorReporter(fixture->context, test_error_reporter); } static void _gjs_unit_test_fixture_finish (GjsUnitTestFixture *fixture) { JS_EndRequest(fixture->context); g_object_unref(fixture->gjs_context); } static void gjstest_test_func_gjs_context_construct_destroy(void) { GjsContext *context; /* Construct twice just to possibly a case where global state from * the first leaks. */ context = gjs_context_new (); g_object_unref (context); context = gjs_context_new (); g_object_unref (context); } static void gjstest_test_func_gjs_context_construct_eval(void) { GjsContext *context; int estatus; GError *error = NULL; context = gjs_context_new (); if (!gjs_context_eval (context, "1+1", -1, "<input>", &estatus, &error)) g_error ("%s", error->message); g_object_unref (context); } static void gjstest_test_func_gjs_context_fixture(void) { GjsUnitTestFixture fixture; JSContext *context; JSObject *global; _gjs_unit_test_fixture_begin(&fixture); context = fixture.context; global = JS_GetGlobalObject(context); JSCompartment *oldCompartment = JS_EnterCompartment(context, global); JS_LeaveCompartment(context, oldCompartment); _gjs_unit_test_fixture_finish(&fixture); } #define N_ELEMS 15 static void gjstest_test_func_gjs_jsapi_util_array(void) { GjsUnitTestFixture fixture; JSContext *context; JSObject *global; GjsRootedArray *array; int i; jsval value; _gjs_unit_test_fixture_begin(&fixture); context = fixture.context; array = gjs_rooted_array_new(); global = JS_GetGlobalObject(context); JSCompartment *oldCompartment = JS_EnterCompartment(context, global); for (i = 0; i < N_ELEMS; i++) { value = STRING_TO_JSVAL(JS_NewStringCopyZ(context, "abcdefghijk")); gjs_rooted_array_append(context, array, value); } JS_GC(JS_GetRuntime(context)); for (i = 0; i < N_ELEMS; i++) { char *ascii; value = gjs_rooted_array_get(context, array, i); g_assert(JSVAL_IS_STRING(value)); gjs_string_to_utf8(context, value, &ascii); g_assert(strcmp(ascii, "abcdefghijk") == 0); g_free(ascii); } gjs_rooted_array_free(context, array, TRUE); JS_LeaveCompartment(context, oldCompartment); _gjs_unit_test_fixture_finish(&fixture); } #undef N_ELEMS static void gjstest_test_func_gjs_jsapi_util_string_js_string_utf8(void) { GjsUnitTestFixture fixture; JSContext *context; JSObject *global; const char *utf8_string = "\303\211\303\226 foobar \343\203\237"; char *utf8_result; jsval js_string; _gjs_unit_test_fixture_begin(&fixture); context = fixture.context; global = JS_GetGlobalObject(context); JSCompartment *oldCompartment = JS_EnterCompartment(context, global); g_assert(gjs_string_from_utf8(context, utf8_string, -1, &js_string) == JS_TRUE); g_assert(JSVAL_IS_STRING(js_string)); g_assert(gjs_string_to_utf8(context, js_string, &utf8_result) == JS_TRUE); JS_LeaveCompartment(context, oldCompartment); _gjs_unit_test_fixture_finish(&fixture); g_assert(g_str_equal(utf8_string, utf8_result)); g_free(utf8_result); } static void gjstest_test_func_gjs_stack_dump(void) { GjsContext *context; /* TODO this test could be better - maybe expose dumpstack as a JS API * so that we have a JS stack to dump? At least here we're getting some * coverage. */ context = gjs_context_new(); gjs_dumpstack(); g_object_unref(context); gjs_dumpstack(); } static void gjstest_test_func_gjs_jsapi_util_error_throw(void) { GjsUnitTestFixture fixture; JSContext *context; JSObject *global; jsval exc, value, previous; char *s = NULL; int strcmp_result; _gjs_unit_test_fixture_begin(&fixture); context = fixture.context; global = JS_GetGlobalObject(context); JSCompartment *oldCompartment = JS_EnterCompartment(context, global); /* Test that we can throw */ gjs_throw(context, "This is an exception %d", 42); g_assert(JS_IsExceptionPending(context)); exc = JSVAL_VOID; JS_GetPendingException(context, &exc); g_assert(!JSVAL_IS_VOID(exc)); value = JSVAL_VOID; JS_GetProperty(context, JSVAL_TO_OBJECT(exc), "message", &value); g_assert(JSVAL_IS_STRING(value)); gjs_string_to_utf8(context, value, &s); g_assert(s != NULL); strcmp_result = strcmp(s, "This is an exception 42"); free(s); if (strcmp_result != 0) g_error("Exception has wrong message '%s'", s); /* keep this around before we clear it */ previous = exc; JS_AddValueRoot(context, &previous); JS_ClearPendingException(context); g_assert(!JS_IsExceptionPending(context)); /* Check that we don't overwrite a pending exception */ JS_SetPendingException(context, previous); g_assert(JS_IsExceptionPending(context)); gjs_throw(context, "Second different exception %s", "foo"); g_assert(JS_IsExceptionPending(context)); exc = JSVAL_VOID; JS_GetPendingException(context, &exc); g_assert(!JSVAL_IS_VOID(exc)); g_assert(JSVAL_TO_OBJECT(exc) == JSVAL_TO_OBJECT(previous)); JS_RemoveValueRoot(context, &previous); JS_LeaveCompartment(context, oldCompartment); _gjs_unit_test_fixture_finish(&fixture); } static void gjstest_test_func_util_glib_strv_concat_null(void) { char **ret; ret = gjs_g_strv_concat(NULL, 0); g_assert(ret != NULL); g_assert(ret[0] == NULL); g_strfreev(ret); } static void gjstest_test_func_util_glib_strv_concat_pointers(void) { char *strv0[2] = {(char*)"foo", NULL}; char *strv1[1] = {NULL}; char **strv2 = NULL; char *strv3[2] = {(char*)"bar", NULL}; char **stuff[4]; char **ret; stuff[0] = strv0; stuff[1] = strv1; stuff[2] = strv2; stuff[3] = strv3; ret = gjs_g_strv_concat(stuff, 4); g_assert(ret != NULL); g_assert_cmpstr(ret[0], ==, strv0[0]); /* same string */ g_assert(ret[0] != strv0[0]); /* different pointer */ g_assert_cmpstr(ret[1], ==, strv3[0]); g_assert(ret[1] != strv3[0]); g_assert(ret[2] == NULL); g_strfreev(ret); } static void gjstest_test_strip_shebang_no_advance_for_no_shebang(void) { const char *script = "foo\nbar"; gssize script_len_original = strlen(script); gssize script_len = script_len_original; int line_number = 1; const char *stripped = gjs_strip_unix_shebang(script, &script_len, &line_number); g_assert_cmpstr(script, ==, stripped); g_assert(script_len == script_len_original); g_assert(line_number == 1); } static void gjstest_test_strip_shebang_advance_for_shebang(void) { const char *script = "#!foo\nbar"; gssize script_len_original = strlen(script); gssize script_len = script_len_original; int line_number = 1; const char *stripped = gjs_strip_unix_shebang(script, &script_len, &line_number); g_assert_cmpstr(stripped, ==, "bar"); g_assert(script_len == 3); g_assert(line_number == 2); } static void gjstest_test_strip_shebang_return_null_for_just_shebang(void) { const char *script = "#!foo"; gssize script_len_original = strlen(script); gssize script_len = script_len_original; int line_number = 1; const char *stripped = gjs_strip_unix_shebang(script, &script_len, &line_number); g_assert(stripped == NULL); g_assert(script_len == 0); g_assert(line_number == -1); } int main(int argc, char **argv) { gjs_crash_after_timeout(60*7); /* give the unit tests 7 minutes to complete */ g_test_init(&argc, &argv, NULL); g_test_add_func("/gjs/context/construct/destroy", gjstest_test_func_gjs_context_construct_destroy); g_test_add_func("/gjs/context/construct/eval", gjstest_test_func_gjs_context_construct_eval); g_test_add_func("/gjs/context/fixture", gjstest_test_func_gjs_context_fixture); g_test_add_func("/gjs/jsapi/util/array", gjstest_test_func_gjs_jsapi_util_array); g_test_add_func("/gjs/jsapi/util/error/throw", gjstest_test_func_gjs_jsapi_util_error_throw); g_test_add_func("/gjs/jsapi/util/string/js/string/utf8", gjstest_test_func_gjs_jsapi_util_string_js_string_utf8); g_test_add_func("/gjs/jsutil/strip_shebang/no_shebang", gjstest_test_strip_shebang_no_advance_for_no_shebang); g_test_add_func("/gjs/jsutil/strip_shebang/have_shebang", gjstest_test_strip_shebang_advance_for_shebang); g_test_add_func("/gjs/jsutil/strip_shebang/only_shebang", gjstest_test_strip_shebang_return_null_for_just_shebang); g_test_add_func("/gjs/stack/dump", gjstest_test_func_gjs_stack_dump); g_test_add_func("/util/glib/strv/concat/null", gjstest_test_func_util_glib_strv_concat_null); g_test_add_func("/util/glib/strv/concat/pointers", gjstest_test_func_util_glib_strv_concat_pointers); g_test_run(); return 0; } <|endoftext|>
<commit_before>#ifndef GCN_KEYLISTENER_HPP #define GCN_KEYLISTENER_HPP #include <string> #include "guichan/platform.hpp" namespace gcn { /** * A KeyListener listens for key events on a widget. When a * widget recives a key event, the corresponding function * in all its key listeners will be called. Only focused * widgets will generate key events. * * None of the functions in this class does anything at all, * it is up to you to overload them. * * @see Widget::addKeyListener */ class DECLSPEC KeyListener { public: /** * Destructor */ virtual ~KeyListener() { } /** * This function is called if a key is pressed when * the widget has keyboard focus. * * If a key is held down the widget will generate multiple * key presses. * * @param key the key pressed * @see Key */ virtual void keyPress(const Key& key) { } /** * This function is called if a key is released when * the widget has keyboard focus. * * @param key the key released * @see Key */ virtual void keyRelease(const Key& key) { } }; // end KeyListener } // end gcn #endif // end GCN_KEYLISTENER_HPP <commit_msg>Minor change<commit_after>#ifndef GCN_KEYLISTENER_HPP #define GCN_KEYLISTENER_HPP #include <string> #include "guichan/platform.hpp" #include "guichan/key.hpp" namespace gcn { /** * A KeyListener listens for key events on a widget. When a * widget recives a key event, the corresponding function * in all its key listeners will be called. Only focused * widgets will generate key events. * * None of the functions in this class does anything at all, * it is up to you to overload them. * * @see Widget::addKeyListener */ class DECLSPEC KeyListener { public: /** * Destructor */ virtual ~KeyListener() { } /** * This function is called if a key is pressed when * the widget has keyboard focus. * * If a key is held down the widget will generate multiple * key presses. * * @param key the key pressed * @see Key */ virtual void keyPress(const Key& key) { } /** * This function is called if a key is released when * the widget has keyboard focus. * * @param key the key released * @see Key */ virtual void keyRelease(const Key& key) { } }; // end KeyListener } // end gcn #endif // end GCN_KEYLISTENER_HPP <|endoftext|>
<commit_before>//===-- llvm-lto2: test harness for the resolution-based LTO interface ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program takes in a list of bitcode files, links them and performs // link-time optimization according to the provided symbol resolutions using the // resolution-based LTO interface, and outputs one or more object files. // // This program is intended to eventually replace llvm-lto which uses the legacy // LTO interface. // //===----------------------------------------------------------------------===// #include "llvm/LTO/LTO.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/TargetSelect.h" using namespace llvm; using namespace lto; using namespace object; static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore, cl::desc("<input bitcode files>")); static cl::opt<std::string> OutputFilename("o", cl::Required, cl::desc("Output filename"), cl::value_desc("filename")); static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files")); static cl::opt<bool> ThinLTODistributedIndexes("thinlto-distributed-indexes", cl::init(false), cl::desc("Write out individual index and " "import files for the " "distributed backend case")); static cl::opt<int> Threads("-thinlto-threads", cl::init(thread::hardware_concurrency())); static cl::list<std::string> SymbolResolutions( "r", cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n" "where \"resolution\" is a sequence (which may be empty) of the\n" "following characters:\n" " p - prevailing: the linker has chosen this definition of the\n" " symbol\n" " l - local: the definition of this symbol is unpreemptable at\n" " runtime and is known to be in this linkage unit\n" " x - externally visible: the definition of this symbol is\n" " visible outside of the LTO unit\n" "A resolution for each symbol must be specified."), cl::ZeroOrMore); static void check(Error E, std::string Msg) { if (!E) return; handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { errs() << "llvm-lto: " << Msg << ": " << EIB.message().c_str() << '\n'; }); exit(1); } template <typename T> static T check(Expected<T> E, std::string Msg) { if (E) return std::move(*E); check(E.takeError(), Msg); return T(); } static void check(std::error_code EC, std::string Msg) { check(errorCodeToError(EC), Msg); } template <typename T> static T check(ErrorOr<T> E, std::string Msg) { if (E) return std::move(*E); check(E.getError(), Msg); return T(); } namespace { // Define the LTOOutput handling class LTOOutput : public lto::NativeObjectOutput { StringRef Path; public: LTOOutput(StringRef Path) : Path(Path) {} std::unique_ptr<raw_pwrite_stream> getStream() override { std::error_code EC; auto S = llvm::make_unique<raw_fd_ostream>(Path, EC, sys::fs::F_None); check(EC, Path); return std::move(S); } }; } int main(int argc, char **argv) { InitializeAllTargets(); InitializeAllTargetMCs(); InitializeAllAsmPrinters(); InitializeAllAsmParsers(); cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness"); std::map<std::pair<std::string, std::string>, SymbolResolution> CommandLineResolutions; for (std::string R : SymbolResolutions) { StringRef Rest = R; StringRef FileName, SymbolName; std::tie(FileName, Rest) = Rest.split(','); if (Rest.empty()) { llvm::errs() << "invalid resolution: " << R << '\n'; return 1; } std::tie(SymbolName, Rest) = Rest.split(','); SymbolResolution Res; for (char C : Rest) { if (C == 'p') Res.Prevailing = true; else if (C == 'l') Res.FinalDefinitionInLinkageUnit = true; else if (C == 'x') Res.VisibleToRegularObj = true; else llvm::errs() << "invalid character " << C << " in resolution: " << R << '\n'; } CommandLineResolutions[{FileName, SymbolName}] = Res; } std::vector<std::unique_ptr<MemoryBuffer>> MBs; Config Conf; Conf.DiagHandler = [](const DiagnosticInfo &) { exit(1); }; if (SaveTemps) check(Conf.addSaveTemps(OutputFilename), "Config::addSaveTemps failed"); ThinBackend Backend; if (ThinLTODistributedIndexes) Backend = createWriteIndexesThinBackend("", "", true, ""); else Backend = createInProcessThinBackend(Threads); LTO Lto(std::move(Conf), std::move(Backend)); bool HasErrors = false; for (std::string F : InputFilenames) { std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F); std::unique_ptr<InputFile> Input = check(InputFile::create(MB->getMemBufferRef()), F); std::vector<SymbolResolution> Res; for (const InputFile::Symbol &Sym : Input->symbols()) { auto I = CommandLineResolutions.find({F, Sym.getName()}); if (I == CommandLineResolutions.end()) { llvm::errs() << argv[0] << ": missing symbol resolution for " << F << ',' << Sym.getName() << '\n'; HasErrors = true; } else { Res.push_back(I->second); CommandLineResolutions.erase(I); } } if (HasErrors) continue; MBs.push_back(std::move(MB)); check(Lto.add(std::move(Input), Res), F); } if (!CommandLineResolutions.empty()) { HasErrors = true; for (auto UnusedRes : CommandLineResolutions) llvm::errs() << argv[0] << ": unused symbol resolution for " << UnusedRes.first.first << ',' << UnusedRes.first.second << '\n'; } if (HasErrors) return 1; auto AddOutput = [&](size_t Task) { std::string Path = OutputFilename + "." + utostr(Task); return llvm::make_unique<LTOOutput>(Path); }; check(Lto.run(AddOutput), "LTO::run failed"); } <commit_msg>[LTO] Fix a use-after-free introduced in r278907 and caught by ASan.<commit_after>//===-- llvm-lto2: test harness for the resolution-based LTO interface ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program takes in a list of bitcode files, links them and performs // link-time optimization according to the provided symbol resolutions using the // resolution-based LTO interface, and outputs one or more object files. // // This program is intended to eventually replace llvm-lto which uses the legacy // LTO interface. // //===----------------------------------------------------------------------===// #include "llvm/LTO/LTO.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/TargetSelect.h" using namespace llvm; using namespace lto; using namespace object; static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore, cl::desc("<input bitcode files>")); static cl::opt<std::string> OutputFilename("o", cl::Required, cl::desc("Output filename"), cl::value_desc("filename")); static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files")); static cl::opt<bool> ThinLTODistributedIndexes("thinlto-distributed-indexes", cl::init(false), cl::desc("Write out individual index and " "import files for the " "distributed backend case")); static cl::opt<int> Threads("-thinlto-threads", cl::init(thread::hardware_concurrency())); static cl::list<std::string> SymbolResolutions( "r", cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n" "where \"resolution\" is a sequence (which may be empty) of the\n" "following characters:\n" " p - prevailing: the linker has chosen this definition of the\n" " symbol\n" " l - local: the definition of this symbol is unpreemptable at\n" " runtime and is known to be in this linkage unit\n" " x - externally visible: the definition of this symbol is\n" " visible outside of the LTO unit\n" "A resolution for each symbol must be specified."), cl::ZeroOrMore); static void check(Error E, std::string Msg) { if (!E) return; handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { errs() << "llvm-lto: " << Msg << ": " << EIB.message().c_str() << '\n'; }); exit(1); } template <typename T> static T check(Expected<T> E, std::string Msg) { if (E) return std::move(*E); check(E.takeError(), Msg); return T(); } static void check(std::error_code EC, std::string Msg) { check(errorCodeToError(EC), Msg); } template <typename T> static T check(ErrorOr<T> E, std::string Msg) { if (E) return std::move(*E); check(E.getError(), Msg); return T(); } namespace { // Define the LTOOutput handling class LTOOutput : public lto::NativeObjectOutput { std::string Path; public: LTOOutput(std::string Path) : Path(std::move(Path)) {} std::unique_ptr<raw_pwrite_stream> getStream() override { std::error_code EC; auto S = llvm::make_unique<raw_fd_ostream>(Path, EC, sys::fs::F_None); check(EC, Path); return std::move(S); } }; } int main(int argc, char **argv) { InitializeAllTargets(); InitializeAllTargetMCs(); InitializeAllAsmPrinters(); InitializeAllAsmParsers(); cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness"); std::map<std::pair<std::string, std::string>, SymbolResolution> CommandLineResolutions; for (std::string R : SymbolResolutions) { StringRef Rest = R; StringRef FileName, SymbolName; std::tie(FileName, Rest) = Rest.split(','); if (Rest.empty()) { llvm::errs() << "invalid resolution: " << R << '\n'; return 1; } std::tie(SymbolName, Rest) = Rest.split(','); SymbolResolution Res; for (char C : Rest) { if (C == 'p') Res.Prevailing = true; else if (C == 'l') Res.FinalDefinitionInLinkageUnit = true; else if (C == 'x') Res.VisibleToRegularObj = true; else llvm::errs() << "invalid character " << C << " in resolution: " << R << '\n'; } CommandLineResolutions[{FileName, SymbolName}] = Res; } std::vector<std::unique_ptr<MemoryBuffer>> MBs; Config Conf; Conf.DiagHandler = [](const DiagnosticInfo &) { exit(1); }; if (SaveTemps) check(Conf.addSaveTemps(OutputFilename), "Config::addSaveTemps failed"); ThinBackend Backend; if (ThinLTODistributedIndexes) Backend = createWriteIndexesThinBackend("", "", true, ""); else Backend = createInProcessThinBackend(Threads); LTO Lto(std::move(Conf), std::move(Backend)); bool HasErrors = false; for (std::string F : InputFilenames) { std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F); std::unique_ptr<InputFile> Input = check(InputFile::create(MB->getMemBufferRef()), F); std::vector<SymbolResolution> Res; for (const InputFile::Symbol &Sym : Input->symbols()) { auto I = CommandLineResolutions.find({F, Sym.getName()}); if (I == CommandLineResolutions.end()) { llvm::errs() << argv[0] << ": missing symbol resolution for " << F << ',' << Sym.getName() << '\n'; HasErrors = true; } else { Res.push_back(I->second); CommandLineResolutions.erase(I); } } if (HasErrors) continue; MBs.push_back(std::move(MB)); check(Lto.add(std::move(Input), Res), F); } if (!CommandLineResolutions.empty()) { HasErrors = true; for (auto UnusedRes : CommandLineResolutions) llvm::errs() << argv[0] << ": unused symbol resolution for " << UnusedRes.first.first << ',' << UnusedRes.first.second << '\n'; } if (HasErrors) return 1; auto AddOutput = [&](size_t Task) { std::string Path = OutputFilename + "." + utostr(Task); return llvm::make_unique<LTOOutput>(std::move(Path)); }; check(Lto.run(AddOutput), "LTO::run failed"); } <|endoftext|>
<commit_before>#include "Input.h" void ascii::Input::beginNewFrame() { mPressedKeys.clear(); mReleasedKeys.clear(); //take mouse input and update last mouse input mLastMouseX = mMouseX; mLastMouseY = mMouseY; mLastMouseState = mMouseState; mMouseState = SDL_GetMouseState(&mMouseX, &mMouseY); mScrollX = 0; mScrollY = 0; } void ascii::Input::keyDownEvent(const SDL_Event& event) { if (!event.key.repeat) { mPressedKeys[event.key.keysym.sym] = true; mHeldKeys[event.key.keysym.sym] = true; } } void ascii::Input::keyUpEvent(const SDL_Event& event) { mReleasedKeys[event.key.keysym.sym] = true; mHeldKeys[event.key.keysym.sym] = false; } void ascii::Input::scrollEvent(const SDL_Event& event) { mScrollX = event.wheel.x; mScrollY = event.wheel.y; } bool ascii::Input::wasKeyPressed(SDL_Keycode key) { return mPressedKeys[key]; } bool ascii::Input::wasKeyReleased(SDL_Keycode key) { return mReleasedKeys[key]; } bool ascii::Input::isKeyHeld(SDL_Keycode key) { return mHeldKeys[key]; } bool ascii::Input::anyKeyPressed() { return mPressedKeys.size() > 0; }<commit_msg>Fixed Input::anyKeyPressed() to stop false positives<commit_after>#include "Input.h" void ascii::Input::beginNewFrame() { mPressedKeys.clear(); mReleasedKeys.clear(); //take mouse input and update last mouse input mLastMouseX = mMouseX; mLastMouseY = mMouseY; mLastMouseState = mMouseState; mMouseState = SDL_GetMouseState(&mMouseX, &mMouseY); mScrollX = 0; mScrollY = 0; } void ascii::Input::keyDownEvent(const SDL_Event& event) { if (!event.key.repeat) { mPressedKeys[event.key.keysym.sym] = true; mHeldKeys[event.key.keysym.sym] = true; } } void ascii::Input::keyUpEvent(const SDL_Event& event) { mReleasedKeys[event.key.keysym.sym] = true; mHeldKeys[event.key.keysym.sym] = false; } void ascii::Input::scrollEvent(const SDL_Event& event) { mScrollX = event.wheel.x; mScrollY = event.wheel.y; } bool ascii::Input::wasKeyPressed(SDL_Keycode key) { return mPressedKeys[key]; } bool ascii::Input::wasKeyReleased(SDL_Keycode key) { return mReleasedKeys[key]; } bool ascii::Input::isKeyHeld(SDL_Keycode key) { return mHeldKeys[key]; } bool ascii::Input::anyKeyPressed() { for (auto it = mPressedKeys.begin(); it != mPressedKeys.end(); ++it) { if (it->second == true) { return true; } } return false; } <|endoftext|>
<commit_before>#include <iostream> #include <OpenMesh/Core/IO/MeshIO.hh> #include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh> #include <OpenMesh/Core/IO/reader/OBJReader.hh> #include <OpenMesh/Core/IO/writer/OBJWriter.hh> #include <OpenMesh/Tools/Decimater/DecimaterT.hh> #include <OpenMesh/Tools/Decimater/ModQuadricT.hh> #include <Eigen/Dense> #include <stdio.h> #include <RigidRegistration.hpp> #include <NonrigidRegistration.hpp> #include <InlierDetector.hpp> #include <CorrespondenceFilter.hpp> #include <SymmetricCorrespondenceFilter.hpp> #include <RigidTransformer.hpp> #include <ViscoElasticTransformer.hpp> #include "global.hpp" #include <helper_functions.hpp> using namespace std; typedef OpenMesh::DefaultTraits MyTraits; typedef OpenMesh::TriMesh_ArrayKernelT<MyTraits> TriMesh; typedef OpenMesh::Decimater::DecimaterT<TriMesh> DecimaterType; typedef OpenMesh::Decimater::ModQuadricT<TriMesh>::Handle HModQuadric; typedef Eigen::Matrix< int, Eigen::Dynamic, 3> FacesMat; //matrix Mx3 of type unsigned int typedef Eigen::VectorXf VecDynFloat; typedef Eigen::Matrix< float, Eigen::Dynamic, registration::NUM_FEATURES> FeatureMat; //matrix Mx6 of type float int main() { /* ############################################################################ ############################## INPUT ##################################### ############################################################################ */ //# IO variables // const string fuckedUpBunnyDir = "/home/jonatan/meshmonk/examples/data/bunny_slightly_rotated.obj"; const string fuckedUpBunnyDir = "/home/jonatan/projects/meshmonk/examples/data/fucked_up_bunny.obj"; const string bunnyDir = "/home/jonatan/projects/meshmonk/examples/data/bunny90.obj"; const string fuckedUpBunnyResultDir = "/home/jonatan/projects/meshmonk/examples/data/bunnyNonRigid.obj"; // const string fuckedUpBunnyDir = "/home/jonatan/projects/meshmonk/examples/data/kul_gezichten/Outliers/Alspac/4707_template.obj"; // const string bunnyDir = "/home/jonatan/projects/meshmonk/examples/data/kul_gezichten/Outliers/Alspac/4707_mevislab.obj"; // const string fuckedUpBunnyResultDir = "/home/jonatan/projects/meshmonk/examples/data/kul_gezichten/Outliers/Alspac/4707_Monk.obj"; //# Load meshes and convert to feature matrices TriMesh fuckedUpBunny; TriMesh bunny; FeatureMat floatingFeatures; FeatureMat targetFeatures; FacesMat floatingFaces; registration::import_data(fuckedUpBunnyDir, bunnyDir, floatingFeatures, targetFeatures, floatingFaces); // floatingFeatures = FeatureMat::Zero(8, NUM_FEATURES); // targetFeatures = FeatureMat::Zero(8, NUM_FEATURES); // floatingFeatures << 0.1f, 0.1f, 0.1f, 0.0f, 0.0f, 1.0f, // 0.1f, 1.1f, 0.1f, 0.0f, 0.0f, 1.0f, // 1.1f, 0.1f, 0.1f, 0.0f, 0.0f, 1.0f, // 1.1f, 1.1f, 0.1f, 0.0f, 0.0f, 1.0f, // 0.1f, 0.1f, 1.1f, 0.0f, 0.0f, 1.0f, // 0.1f, 1.1f, 1.1f, 0.0f, 0.0f, 1.0f, // 1.1f, 0.1f, 1.1f, 0.0f, 0.0f, 1.0f, // 1.1f, 1.1f, 1.1f, 0.0f, 0.0f, 1.0f; // targetFeatures << 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, // 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, // 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f; /* ############################################################################ ############################## TEST SHIZZLE ############################## ############################################################################ */ // std::cout << "test features: \n" << floatingFeatures.topRows(10) << std::endl; // std::cout << "test faces: \n" << floatingFaces.topRows(10) << std::endl; /* ############################################################################ ############################## DECIMATION ################################ ############################################################################ */ // //# block boundary vertices // fuckedUpBunny.request_vertex_status(); // //## Get an iterator over all halfedges // TriMesh::HalfedgeIter he_it, he_end=fuckedUpBunny.halfedges_end(); // //## If halfedge is boundary, lock the corresponding vertices // for (he_it = fuckedUpBunny.halfedges_begin(); he_it != he_end ; ++he_it) { // if (fuckedUpBunny.is_boundary(*he_it)) { // fuckedUpBunny.status(fuckedUpBunny.to_vertex_handle(*he_it)).set_locked(true); // fuckedUpBunny.status(fuckedUpBunny.from_vertex_handle(*he_it)).set_locked(true); // } // } // //# Make sure mesh has necessary normals etc // fuckedUpBunny.request_face_normals(); // fuckedUpBunny.update_face_normals(); // // //# Set up the decimator // DecimaterType decimater(fuckedUpBunny); // a decimater object, connected to a mesh // HModQuadric hModQuadric; // use a quadric module // decimater.add( hModQuadric ); // register module at the decimater // // std::cout << decimater.module( hModQuadric ).name() << std::endl; // decimater.module(hModQuadric).unset_max_err(); // // //# Initialize the decimater // bool rc = decimater.initialize(); // std::cout << "Decimater Initialization: " << decimater.is_initialized() << std::endl; // if (!rc){ // std::cerr << " initializing failed!" << std::endl; // std::cerr << " maybe no priority module or more than one were defined!" << std::endl; // return false; // } // // // std::cout << "Decimater Observer: \n" << decimater.observer() << std::endl; // // // // //# Run the decimater // rc = decimater.decimate_to(size_t(10)); // // //# Collect garbage // fuckedUpBunny.garbage_collection(); // // //# convert to our features // registration::convert_mesh_to_matrices(fuckedUpBunny, floatingFeatures, floatingFaces); /* ############################################################################ ############################## RIGID ICP ################################# ############################################################################ */ //# Info & Initialization //## Data and matrices size_t numFloatingVertices = floatingFeatures.rows(); size_t numTargetVertices = targetFeatures.rows(); VecDynFloat floatingFlags = VecDynFloat::Ones(numFloatingVertices); VecDynFloat targetFlags = VecDynFloat::Ones(numTargetVertices); //## Parameters bool symmetric = true; size_t numNearestNeighbours = 5; size_t numRigidIterations = 10; float kappa = 3.0f; registration::RigidRegistration rigidRegistration; rigidRegistration.set_input(&floatingFeatures, &targetFeatures, &floatingFlags, &targetFlags); rigidRegistration.set_parameters(symmetric, numNearestNeighbours, kappa, numRigidIterations); rigidRegistration.update(); /* ############################################################################ ########################## NON-RIGID ICP ################################# ############################################################################ */ //## Initialization size_t numNonrigidIterations = 20; float sigmaSmoothing = 2.0f; registration::NonrigidRegistration nonrigidRegistration; nonrigidRegistration.set_input(&floatingFeatures, &targetFeatures, &floatingFaces, &floatingFlags, &targetFlags); nonrigidRegistration.set_parameters(symmetric, numNearestNeighbours, kappa, numNonrigidIterations, sigmaSmoothing, 100, 1, 100, 1); nonrigidRegistration.update(); /* ############################################################################ ############################## OUTPUT ##################################### ############################################################################ */ //# Write result to file registration::export_data(floatingFeatures,floatingFaces, fuckedUpBunnyResultDir); return 0; } <commit_msg>Decimating functions properly. Need to make a pyramid, downsampling and interpolation class now.<commit_after>#include <iostream> #include <OpenMesh/Core/IO/MeshIO.hh> #include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh> #include <OpenMesh/Core/IO/reader/OBJReader.hh> #include <OpenMesh/Core/IO/writer/OBJWriter.hh> #include <OpenMesh/Tools/Decimater/DecimaterT.hh> #include <OpenMesh/Tools/Decimater/ModQuadricT.hh> #include <Eigen/Dense> #include <stdio.h> #include <RigidRegistration.hpp> #include <NonrigidRegistration.hpp> #include <InlierDetector.hpp> #include <CorrespondenceFilter.hpp> #include <SymmetricCorrespondenceFilter.hpp> #include <RigidTransformer.hpp> #include <ViscoElasticTransformer.hpp> #include "global.hpp" #include <helper_functions.hpp> using namespace std; typedef OpenMesh::DefaultTraits MyTraits; typedef OpenMesh::TriMesh_ArrayKernelT<MyTraits> TriMesh; typedef OpenMesh::Decimater::DecimaterT<TriMesh> DecimaterType; typedef OpenMesh::Decimater::ModQuadricT<TriMesh>::Handle HModQuadric; typedef Eigen::Matrix< int, Eigen::Dynamic, 3> FacesMat; //matrix Mx3 of type unsigned int typedef Eigen::VectorXf VecDynFloat; typedef Eigen::Matrix< float, Eigen::Dynamic, registration::NUM_FEATURES> FeatureMat; //matrix Mx6 of type float int main() { /* ############################################################################ ############################## INPUT ##################################### ############################################################################ */ //# IO variables // const string fuckedUpBunnyDir = "/home/jonatan/meshmonk/examples/data/bunny_slightly_rotated.obj"; const string fuckedUpBunnyDir = "/home/jonatan/projects/meshmonk/examples/data/fucked_up_bunny.obj"; const string bunnyDir = "/home/jonatan/projects/meshmonk/examples/data/bunny90.obj"; const string fuckedUpBunnyResultDir = "/home/jonatan/projects/meshmonk/examples/data/bunnyNonRigid.obj"; // const string fuckedUpBunnyDir = "/home/jonatan/projects/meshmonk/examples/data/kul_gezichten/Outliers/Alspac/4707_template.obj"; // const string bunnyDir = "/home/jonatan/projects/meshmonk/examples/data/kul_gezichten/Outliers/Alspac/4707_mevislab.obj"; // const string fuckedUpBunnyResultDir = "/home/jonatan/projects/meshmonk/examples/data/kul_gezichten/Outliers/Alspac/4707_Monk.obj"; //# Load meshes and convert to feature matrices FeatureMat floatingFeatures; FeatureMat targetFeatures; FacesMat floatingFaces; registration::import_data(fuckedUpBunnyDir, bunnyDir, floatingFeatures, targetFeatures, floatingFaces); // floatingFeatures = FeatureMat::Zero(8, NUM_FEATURES); // targetFeatures = FeatureMat::Zero(8, NUM_FEATURES); // floatingFeatures << 0.1f, 0.1f, 0.1f, 0.0f, 0.0f, 1.0f, // 0.1f, 1.1f, 0.1f, 0.0f, 0.0f, 1.0f, // 1.1f, 0.1f, 0.1f, 0.0f, 0.0f, 1.0f, // 1.1f, 1.1f, 0.1f, 0.0f, 0.0f, 1.0f, // 0.1f, 0.1f, 1.1f, 0.0f, 0.0f, 1.0f, // 0.1f, 1.1f, 1.1f, 0.0f, 0.0f, 1.0f, // 1.1f, 0.1f, 1.1f, 0.0f, 0.0f, 1.0f, // 1.1f, 1.1f, 1.1f, 0.0f, 0.0f, 1.0f; // targetFeatures << 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, // 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, // 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f; /* ############################################################################ ############################## TEST SHIZZLE ############################## ############################################################################ */ // std::cout << "test features: \n" << floatingFeatures.topRows(10) << std::endl; // std::cout << "test faces: \n" << floatingFaces.topRows(10) << std::endl; /* ############################################################################ ############################## DECIMATION ################################ ############################################################################ */ //# Load the bunny TriMesh fuckedUpBunny; OpenMesh::IO::_OBJReader_(); if (!OpenMesh::IO::read_mesh(fuckedUpBunny,fuckedUpBunnyDir)){ std::cerr << "Read error \n"; exit(1); }; //# Print Mesh property std::cout << "-------- Before processing " << std::endl; std::cout << "# Vertices " << fuckedUpBunny.n_vertices() << std::endl; std::cout << "# Edges " << fuckedUpBunny.n_edges() << std::endl; std::cout << "# Faces " << fuckedUpBunny.n_faces() << std::endl; //# block boundary vertices fuckedUpBunny.request_vertex_status(); //## Get an iterator over all halfedges TriMesh::HalfedgeIter he_it, he_end=fuckedUpBunny.halfedges_end(); //## If halfedge is boundary, lock the corresponding vertices for (he_it = fuckedUpBunny.halfedges_begin(); he_it != he_end ; ++he_it) { if (fuckedUpBunny.is_boundary(*he_it)) { fuckedUpBunny.status(fuckedUpBunny.to_vertex_handle(*he_it)).set_locked(true); fuckedUpBunny.status(fuckedUpBunny.from_vertex_handle(*he_it)).set_locked(true); } } //# Make sure mesh has necessary normals etc fuckedUpBunny.request_face_normals(); fuckedUpBunny.update_face_normals(); //# Set up the decimator DecimaterType decimater(fuckedUpBunny); // a decimater object, connected to a mesh HModQuadric hModQuadric; // use a quadric module bool addSucces = decimater.add( hModQuadric ); // register module at the decimater std::cout << "Adding quadric modifier to decimater : " << addSucces << std::endl; std::cout << decimater.module( hModQuadric ).name() << std::endl; decimater.module(hModQuadric).unset_max_err(); //# Initialize the decimater bool rc = decimater.initialize(); std::cout << "Decimater Initialization: " << decimater.is_initialized() << std::endl; if (!rc){ std::cerr << " initializing failed!" << std::endl; std::cerr << " maybe no priority module or more than one were defined!" << std::endl; return false; } std::cout << "Decimater Observer: " << decimater.observer() << std::endl; //# Run the decimater // rc = decimater.decimate_to(size_t(10)); rc = decimater.decimate(size_t(10)); std::cout << " Did we fucking decimate?? -> " << rc << std::endl; //# Collect garbage fuckedUpBunny.garbage_collection(); //# Print Mesh property std::cout << "-------- After processing " << std::endl; std::cout << "# Vertices " << fuckedUpBunny.n_vertices() << std::endl; std::cout << "# Edges " << fuckedUpBunny.n_edges() << std::endl; std::cout << "# Faces " << fuckedUpBunny.n_faces() << std::endl; //# Write to file OpenMesh::IO::_OBJWriter_(); if (!OpenMesh::IO::write_mesh(fuckedUpBunny, fuckedUpBunnyResultDir)) { std::cerr << "write error\n"; exit(1); } // // //# convert to our features // registration::convert_mesh_to_matrices(fuckedUpBunny, floatingFeatures, floatingFaces); /* ############################################################################ ############################## RIGID ICP ################################# ############################################################################ */ // //# Info & Initialization // //## Data and matrices // size_t numFloatingVertices = floatingFeatures.rows(); // size_t numTargetVertices = targetFeatures.rows(); // VecDynFloat floatingFlags = VecDynFloat::Ones(numFloatingVertices); // VecDynFloat targetFlags = VecDynFloat::Ones(numTargetVertices); // // //## Parameters // bool symmetric = true; // size_t numNearestNeighbours = 5; // size_t numRigidIterations = 10; // float kappa = 3.0f; // // registration::RigidRegistration rigidRegistration; // rigidRegistration.set_input(&floatingFeatures, &targetFeatures, &floatingFlags, &targetFlags); // rigidRegistration.set_parameters(symmetric, numNearestNeighbours, kappa, numRigidIterations); // rigidRegistration.update(); // // /* // ############################################################################ // ########################## NON-RIGID ICP ################################# // ############################################################################ // */ // //## Initialization // size_t numNonrigidIterations = 20; // float sigmaSmoothing = 2.0f; // registration::NonrigidRegistration nonrigidRegistration; // nonrigidRegistration.set_input(&floatingFeatures, &targetFeatures, &floatingFaces, &floatingFlags, &targetFlags); // nonrigidRegistration.set_parameters(symmetric, numNearestNeighbours, kappa, // numNonrigidIterations, sigmaSmoothing, // 100, 1, // 100, 1); // nonrigidRegistration.update(); /* ############################################################################ ############################## OUTPUT ##################################### ############################################################################ */ //# Write result to file // registration::export_data(floatingFeatures,floatingFaces, fuckedUpBunnyResultDir); return 0; } <|endoftext|>
<commit_before>#include"all_defines.hpp" #include"symbols.hpp" #include"processes.hpp" #include"mutexes.hpp" #include<boost/noncopyable.hpp> #include<string> #include<map> void Symbol::copy_value_to(ValueHolderRef& p) { {AppLock l(m); /*Unfortunately the entire cloning has to be done while we have the lock. This is because a Symbol::set_value() might invalidate the pointer from under us if we didn't do the entire cloning locked. Other alternatives exist: we can use a locked reference counting scheme, or use some sort of deferred deallocation. */ value->clone(p); } } void Symbol::copy_value_to_and_add_notify(ValueHolderRef& p, Process* R) { {AppLock l(m); if (p.empty()) { // no value associated with this symbol throw_HlError("unbound variable"); } value->clone(p); /*check for dead processes in notification list*/ size_t j = 0; for(size_t i = 0; i < notification_list.size(); ++i) { if(!notification_list[i]->is_dead()) { if(i != j) { notification_list[j] = notification_list[i]; } ++j; } } notification_list.resize(j + 1); notification_list[j] = R; } } void Symbol::set_value(Object::ref o) { ValueHolderRef tmp; ValueHolder::copy_object(tmp, o); {AppLock l(m); value.swap(tmp); size_t j = 0; for(size_t i = 0; i < notification_list.size(); ++i) { if(!notification_list[i]->is_dead()) { if(i != j) { notification_list[j] = notification_list[i]; } notification_list[j]->notify_global_change(this); ++j; } } notification_list.resize(j); } } void Symbol::clean_notification_list(std::set<Process*> const& dead) { size_t j = 0; for(size_t i = 0; i < notification_list.size(); ++i) { /*not counted among the dead?*/ if(dead.count(notification_list[i]) == 0) { if(i != j) { notification_list[j] = notification_list[i]; } ++j; } } notification_list.resize(j); } <commit_msg>symbols.cpp: fixed previous fix<commit_after>#include"all_defines.hpp" #include"symbols.hpp" #include"processes.hpp" #include"mutexes.hpp" #include<boost/noncopyable.hpp> #include<string> #include<map> void Symbol::copy_value_to(ValueHolderRef& p) { {AppLock l(m); /*Unfortunately the entire cloning has to be done while we have the lock. This is because a Symbol::set_value() might invalidate the pointer from under us if we didn't do the entire cloning locked. Other alternatives exist: we can use a locked reference counting scheme, or use some sort of deferred deallocation. */ value->clone(p); } } void Symbol::copy_value_to_and_add_notify(ValueHolderRef& p, Process* R) { {AppLock l(m); if (value.empty()) { // no value associated with this symbol throw_HlError("unbound variable"); } value->clone(p); /*check for dead processes in notification list*/ size_t j = 0; for(size_t i = 0; i < notification_list.size(); ++i) { if(!notification_list[i]->is_dead()) { if(i != j) { notification_list[j] = notification_list[i]; } ++j; } } notification_list.resize(j + 1); notification_list[j] = R; } } void Symbol::set_value(Object::ref o) { ValueHolderRef tmp; ValueHolder::copy_object(tmp, o); {AppLock l(m); value.swap(tmp); size_t j = 0; for(size_t i = 0; i < notification_list.size(); ++i) { if(!notification_list[i]->is_dead()) { if(i != j) { notification_list[j] = notification_list[i]; } notification_list[j]->notify_global_change(this); ++j; } } notification_list.resize(j); } } void Symbol::clean_notification_list(std::set<Process*> const& dead) { size_t j = 0; for(size_t i = 0; i < notification_list.size(); ++i) { /*not counted among the dead?*/ if(dead.count(notification_list[i]) == 0) { if(i != j) { notification_list[j] = notification_list[i]; } ++j; } } notification_list.resize(j); } <|endoftext|>
<commit_before>/* * Copyright 2017 Andrei Pangin * * 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 <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <unistd.h> #include <fcntl.h> #include <linux/limits.h> #include <fstream> #include <iostream> #include <string> #include "symbols.h" class SymbolDesc { private: const char* _addr; const char* _type; public: SymbolDesc(const char* s) { _addr = s; _type = strchr(_addr, ' ') + 1; } const char* addr() { return (const char*)strtoul(_addr, NULL, 16); } char type() { return _type[0]; } const char* name() { return _type + 2; } }; class MemoryMapDesc { private: const char* _addr; const char* _end; const char* _perm; const char* _offs; const char* _device; const char* _inode; const char* _file; public: MemoryMapDesc(const char* s) { _addr = s; _end = strchr(_addr, '-') + 1; _perm = strchr(_end, ' ') + 1; _offs = strchr(_perm, ' ') + 1; _device = strchr(_offs, ' ') + 1; _inode = strchr(_device, ' ') + 1; _file = strchr(_inode, ' '); if (_file != NULL) { while (*_file == ' ') _file++; } } const char* file() { return _file; } bool isExecutable() { return _perm[0] == 'r' && _perm[2] == 'x'; } const char* addr() { return (const char*)strtoul(_addr, NULL, 16); } const char* end() { return (const char*)strtoul(_end, NULL, 16); } unsigned long offs() { return strtoul(_offs, NULL, 16); } unsigned long inode() { return strtoul(_inode, NULL, 10); } }; ElfSection* ElfParser::findSection(uint32_t type, const char* name) { const char* strtab = at(section(_header->e_shstrndx)); for (int i = 0; i < _header->e_shnum; i++) { ElfSection* section = this->section(i); if (section->sh_type == type && section->sh_name != 0) { if (strcmp(strtab + section->sh_name, name) == 0) { return section; } } } return NULL; } bool ElfParser::parseFile(NativeCodeCache* cc, const char* base, const char* file_name, bool use_debug) { int fd = open(file_name, O_RDONLY); if (fd == -1) { return false; } size_t length = (size_t)lseek64(fd, 0, SEEK_END); void* addr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0); close(fd); if (addr != NULL) { ElfParser elf(cc, base, addr, file_name); elf.loadSymbols(use_debug); munmap(addr, length); } return true; } void ElfParser::parseMem(NativeCodeCache* cc, const char* base, const void* addr) { ElfParser elf(cc, base, addr); elf.loadSymbols(false); } void ElfParser::loadSymbols(bool use_debug) { if (!valid_header()) { return; } // Look for debug symbols in the original .so ElfSection* section = findSection(SHT_SYMTAB, ".symtab"); if (section != NULL) { loadSymbolTable(section); return; } // Try to load symbols from an external debuginfo library if (use_debug) { if (loadSymbolsUsingBuildId() || loadSymbolsUsingDebugLink()) { return; } } // If everything else fails, load only exported symbols section = findSection(SHT_DYNSYM, ".dynsym"); if (section != NULL) { loadSymbolTable(section); } } // Load symbols from /usr/lib/debug/.build-id/ab/cdef1234.debug, where abcdef1234 is Build ID bool ElfParser::loadSymbolsUsingBuildId() { ElfSection* section = findSection(SHT_NOTE, ".note.gnu.build-id"); if (section == NULL || section->sh_size <= 16) { return false; } ElfNote* note = (ElfNote*)at(section); if (note->n_namesz != 4 || note->n_descsz < 2 || note->n_descsz > 64) { return false; } const char* build_id = (const char*)note + sizeof(*note) + 4; int build_id_len = note->n_descsz; char path[PATH_MAX]; char* p = path + sprintf(path, "/usr/lib/debug/.build-id/%02hhx/", build_id[0]); for (int i = 1; i < build_id_len; i++) { p += sprintf(p, "%02hhx", build_id[i]); } strcpy(p, ".debug"); return parseFile(_cc, _base, path, false); } // Look for debuginfo file specified in .gnu_debuglink section bool ElfParser::loadSymbolsUsingDebugLink() { ElfSection* section = findSection(SHT_PROGBITS, ".gnu_debuglink"); if (section == NULL || section->sh_size <= 4) { return false; } const char* basename = strrchr(_file_name, '/'); if (basename == NULL) { return false; } char* dirname = strndup(_file_name, basename - _file_name); if (dirname == NULL) { return false; } const char* debuglink = at(section); char path[PATH_MAX]; bool result = false; // 1. /path/to/libjvm.so.debug if (strcmp(debuglink, basename + 1) != 0 && snprintf(path, sizeof(path), "%s/%s", dirname, debuglink) < sizeof(path)) { result = parseFile(_cc, _base, path, false); } // 2. /path/to/.debug/libjvm.so.debug if (!result && snprintf(path, sizeof(path), "%s/.debug/%s", dirname, debuglink) < sizeof(path)) { result = parseFile(_cc, _base, path, false); } // 3. /usr/lib/debug/path/to/libjvm.so.debug if (!result && snprintf(path, sizeof(path), "/usr/lib/debug%s/%s", dirname, debuglink) < sizeof(path)) { result = parseFile(_cc, _base, path, false); } free(dirname); return result; } void ElfParser::loadSymbolTable(ElfSection* symtab) { ElfSection* strtab = section(symtab->sh_link); const char* strings = at(strtab); const char* symbols = at(symtab); const char* symbols_end = symbols + symtab->sh_size; for (; symbols < symbols_end; symbols += symtab->sh_entsize) { ElfSymbol* sym = (ElfSymbol*)symbols; if (sym->st_name != 0 && sym->st_value != 0) { _cc->add(_base + sym->st_value, (int)sym->st_size, strings + sym->st_name); } } } void Symbols::parseKernelSymbols(NativeCodeCache* cc) { std::ifstream maps("/proc/kallsyms"); std::string str; while (std::getline(maps, str)) { str += "_[k]"; SymbolDesc symbol(str.c_str()); char type = symbol.type(); if (type == 'T' || type == 't' || type == 'V' || type == 'v' || type == 'W' || type == 'w') { const char* addr = symbol.addr(); if (addr != NULL) { cc->add(addr, 0, symbol.name()); } } } } int Symbols::parseMaps(NativeCodeCache** array, int size) { int count = 0; if (count < size) { NativeCodeCache* cc = new NativeCodeCache("[kernel]"); parseKernelSymbols(cc); cc->sort(); array[count++] = cc; } std::ifstream maps("/proc/self/maps"); std::string str; while (count < size && std::getline(maps, str)) { MemoryMapDesc map(str.c_str()); if (map.isExecutable() && map.file() != NULL && map.file()[0] != 0) { NativeCodeCache* cc = new NativeCodeCache(map.file(), map.addr(), map.end()); const char* base = map.addr() - map.offs(); if (map.inode() != 0) { ElfParser::parseFile(cc, base, map.file(), true); } else if (strcmp(map.file(), "[vdso]") == 0) { ElfParser::parseMem(cc, base, base); } cc->sort(); array[count++] = cc; } } return count; } <commit_msg>Resolves #50: Bogus kernel symbols<commit_after>/* * Copyright 2017 Andrei Pangin * * 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 <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <unistd.h> #include <fcntl.h> #include <linux/limits.h> #include <fstream> #include <iostream> #include <string> #include "symbols.h" class SymbolDesc { private: const char* _addr; const char* _type; public: SymbolDesc(const char* s) { _addr = s; _type = strchr(_addr, ' ') + 1; } const char* addr() { return (const char*)strtoul(_addr, NULL, 16); } char type() { return _type[0]; } const char* name() { return _type + 2; } }; class MemoryMapDesc { private: const char* _addr; const char* _end; const char* _perm; const char* _offs; const char* _device; const char* _inode; const char* _file; public: MemoryMapDesc(const char* s) { _addr = s; _end = strchr(_addr, '-') + 1; _perm = strchr(_end, ' ') + 1; _offs = strchr(_perm, ' ') + 1; _device = strchr(_offs, ' ') + 1; _inode = strchr(_device, ' ') + 1; _file = strchr(_inode, ' '); if (_file != NULL) { while (*_file == ' ') _file++; } } const char* file() { return _file; } bool isExecutable() { return _perm[0] == 'r' && _perm[2] == 'x'; } const char* addr() { return (const char*)strtoul(_addr, NULL, 16); } const char* end() { return (const char*)strtoul(_end, NULL, 16); } unsigned long offs() { return strtoul(_offs, NULL, 16); } unsigned long inode() { return strtoul(_inode, NULL, 10); } }; ElfSection* ElfParser::findSection(uint32_t type, const char* name) { const char* strtab = at(section(_header->e_shstrndx)); for (int i = 0; i < _header->e_shnum; i++) { ElfSection* section = this->section(i); if (section->sh_type == type && section->sh_name != 0) { if (strcmp(strtab + section->sh_name, name) == 0) { return section; } } } return NULL; } bool ElfParser::parseFile(NativeCodeCache* cc, const char* base, const char* file_name, bool use_debug) { int fd = open(file_name, O_RDONLY); if (fd == -1) { return false; } size_t length = (size_t)lseek64(fd, 0, SEEK_END); void* addr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0); close(fd); if (addr != NULL) { ElfParser elf(cc, base, addr, file_name); elf.loadSymbols(use_debug); munmap(addr, length); } return true; } void ElfParser::parseMem(NativeCodeCache* cc, const char* base, const void* addr) { ElfParser elf(cc, base, addr); elf.loadSymbols(false); } void ElfParser::loadSymbols(bool use_debug) { if (!valid_header()) { return; } // Look for debug symbols in the original .so ElfSection* section = findSection(SHT_SYMTAB, ".symtab"); if (section != NULL) { loadSymbolTable(section); return; } // Try to load symbols from an external debuginfo library if (use_debug) { if (loadSymbolsUsingBuildId() || loadSymbolsUsingDebugLink()) { return; } } // If everything else fails, load only exported symbols section = findSection(SHT_DYNSYM, ".dynsym"); if (section != NULL) { loadSymbolTable(section); } } // Load symbols from /usr/lib/debug/.build-id/ab/cdef1234.debug, where abcdef1234 is Build ID bool ElfParser::loadSymbolsUsingBuildId() { ElfSection* section = findSection(SHT_NOTE, ".note.gnu.build-id"); if (section == NULL || section->sh_size <= 16) { return false; } ElfNote* note = (ElfNote*)at(section); if (note->n_namesz != 4 || note->n_descsz < 2 || note->n_descsz > 64) { return false; } const char* build_id = (const char*)note + sizeof(*note) + 4; int build_id_len = note->n_descsz; char path[PATH_MAX]; char* p = path + sprintf(path, "/usr/lib/debug/.build-id/%02hhx/", build_id[0]); for (int i = 1; i < build_id_len; i++) { p += sprintf(p, "%02hhx", build_id[i]); } strcpy(p, ".debug"); return parseFile(_cc, _base, path, false); } // Look for debuginfo file specified in .gnu_debuglink section bool ElfParser::loadSymbolsUsingDebugLink() { ElfSection* section = findSection(SHT_PROGBITS, ".gnu_debuglink"); if (section == NULL || section->sh_size <= 4) { return false; } const char* basename = strrchr(_file_name, '/'); if (basename == NULL) { return false; } char* dirname = strndup(_file_name, basename - _file_name); if (dirname == NULL) { return false; } const char* debuglink = at(section); char path[PATH_MAX]; bool result = false; // 1. /path/to/libjvm.so.debug if (strcmp(debuglink, basename + 1) != 0 && snprintf(path, sizeof(path), "%s/%s", dirname, debuglink) < sizeof(path)) { result = parseFile(_cc, _base, path, false); } // 2. /path/to/.debug/libjvm.so.debug if (!result && snprintf(path, sizeof(path), "%s/.debug/%s", dirname, debuglink) < sizeof(path)) { result = parseFile(_cc, _base, path, false); } // 3. /usr/lib/debug/path/to/libjvm.so.debug if (!result && snprintf(path, sizeof(path), "/usr/lib/debug%s/%s", dirname, debuglink) < sizeof(path)) { result = parseFile(_cc, _base, path, false); } free(dirname); return result; } void ElfParser::loadSymbolTable(ElfSection* symtab) { ElfSection* strtab = section(symtab->sh_link); const char* strings = at(strtab); const char* symbols = at(symtab); const char* symbols_end = symbols + symtab->sh_size; for (; symbols < symbols_end; symbols += symtab->sh_entsize) { ElfSymbol* sym = (ElfSymbol*)symbols; if (sym->st_name != 0 && sym->st_value != 0) { _cc->add(_base + sym->st_value, (int)sym->st_size, strings + sym->st_name); } } } void Symbols::parseKernelSymbols(NativeCodeCache* cc) { std::ifstream maps("/proc/kallsyms"); std::string str; while (std::getline(maps, str)) { str += "_[k]"; SymbolDesc symbol(str.c_str()); char type = symbol.type(); if (type == 'T' || type == 't' || type == 'W' || type == 'w') { const char* addr = symbol.addr(); if (addr != NULL) { cc->add(addr, 0, symbol.name()); } } } } int Symbols::parseMaps(NativeCodeCache** array, int size) { int count = 0; if (count < size) { NativeCodeCache* cc = new NativeCodeCache("[kernel]"); parseKernelSymbols(cc); cc->sort(); array[count++] = cc; } std::ifstream maps("/proc/self/maps"); std::string str; while (count < size && std::getline(maps, str)) { MemoryMapDesc map(str.c_str()); if (map.isExecutable() && map.file() != NULL && map.file()[0] != 0) { NativeCodeCache* cc = new NativeCodeCache(map.file(), map.addr(), map.end()); const char* base = map.addr() - map.offs(); if (map.inode() != 0) { ElfParser::parseFile(cc, base, map.file(), true); } else if (strcmp(map.file(), "[vdso]") == 0) { ElfParser::parseMem(cc, base, base); } cc->sort(); array[count++] = cc; } } return count; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Graphical Effects module. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "pngdumper.h" #include <QtQml/qqml.h> ItemCapturer::ItemCapturer(QQuickItem *parent): QQuickItem(parent) { } ItemCapturer::~ItemCapturer() { } void ItemCapturer::grabItem(QQuickItem *item, QString filename) { QImage img = canvas()->grabFrameBuffer(); while (img.width() * img.height() == 0) img = canvas()->grabFrameBuffer(); QQuickItem *rootItem = canvas()->rootItem(); QRectF rectf = rootItem->mapRectFromItem(item, QRectF(0, 0, item->width(), item->height())); QDir pwd = QDir().dirName(); pwd.mkdir("output"); img = img.copy(rectf.toRect()); img.save("output/" + filename); emit imageSaved(); } void ItemCapturer::document(QString s) { printf(s.toLatin1().data()); } <commit_msg>Fix compilation of pngdumper.<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Graphical Effects module. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "pngdumper.h" #include <QtQml/qqml.h> #include <QtQuick/QQuickWindow> ItemCapturer::ItemCapturer(QQuickItem *parent): QQuickItem(parent) { } ItemCapturer::~ItemCapturer() { } void ItemCapturer::grabItem(QQuickItem *item, QString filename) { QQuickWindow *w = window(); QImage img = w->grabWindow(); while (img.width() * img.height() == 0) img = w->grabWindow(); QQuickItem *rootItem = w->contentItem(); QRectF rectf = rootItem->mapRectFromItem(item, QRectF(0, 0, item->width(), item->height())); QDir pwd = QDir().dirName(); pwd.mkdir("output"); img = img.copy(rectf.toRect()); img.save("output/" + filename); emit imageSaved(); } void ItemCapturer::document(QString s) { printf(s.toLatin1().data()); } <|endoftext|>
<commit_before>/* RTcmix - Copyright (C) 2004 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ #include <Odelay.h> #include <stdlib.h> #include <assert.h> Odelay::Odelay(long defaultLength) : _dline(NULL), _len(0) { assert(defaultLength > 0); resize(defaultLength); _outpoint = 0; _inpoint = _len - 1; } Odelay::~Odelay() { free(_dline); } void Odelay::clear() { for (long i = 0; i < _len; i++) _dline[i] = 0.0; _lastout = 0.0; } void Odelay::putsamp(float samp) { _dline[_inpoint++] = samp; if (_inpoint == _len) _inpoint = 0; } float Odelay::getsamp(double lagsamps) { if (lagsamps >= (double) _len) resize((long)(lagsamps + 0.5)); _outpoint = long(_inpoint - lagsamps - 0.5); if (_len > 0) { while (_outpoint < 0) _outpoint += _len; } return _lastout = _dline[_outpoint++]; } // Set output pointer <_outpoint>. void Odelay::setdelay(double lagsamps) { if (lagsamps >= (double) _len) resize((long)(lagsamps + 0.5)); _outpoint = long(_inpoint - lagsamps - 0.5); if (_len > 0) { while (_outpoint < 0) _outpoint += _len; } } float Odelay::next(float input) { _dline[_inpoint++] = input; if (_inpoint == _len) _inpoint = 0; _lastout = _dline[_outpoint++]; if (_outpoint == _len) _outpoint = 0; return _lastout; } static float *newFloats(float *oldptr, long oldlen, long *newlen) { float *ptr = NULL; if (oldptr == NULL) { ptr = (float *) malloc(*newlen * sizeof(float)); } else { float *newptr = (float *) realloc(oldptr, *newlen * sizeof(float)); if (newptr) { ptr = newptr; // Zero out new portion. for (long n = oldlen; n < *newlen; ++n) ptr[n] = 0.0f; } else { *newlen = oldlen; // notify caller that realloc failed ptr = oldptr; } } return ptr; } int Odelay::resize(long thisLength) { // Make a guess at how big the new array should be. long newlen = (thisLength < _len * 2) ? _len * 2 : _len + thisLength; _dline = ::newFloats(_dline, _len, &newlen); return _len = newlen; } float Odelay::delay() const { return (float) (_len > 0) ? abs((_outpoint - _inpoint) % _len) : 0; } <commit_msg>Fixed missing zeroing of initial allocation<commit_after>/* RTcmix - Copyright (C) 2004 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ #include <Odelay.h> #include <stdlib.h> #include <assert.h> Odelay::Odelay(long defaultLength) : _dline(NULL), _len(0) { assert(defaultLength > 0); resize(defaultLength); clear(); _outpoint = 0; _inpoint = _len - 1; } Odelay::~Odelay() { free(_dline); } void Odelay::clear() { for (long i = 0; i < _len; i++) _dline[i] = 0.0; _lastout = 0.0; } void Odelay::putsamp(float samp) { _dline[_inpoint++] = samp; if (_inpoint == _len) _inpoint = 0; } float Odelay::getsamp(double lagsamps) { if (lagsamps >= (double) _len) resize((long)(lagsamps + 0.5)); _outpoint = long(_inpoint - lagsamps - 0.5); if (_len > 0) { while (_outpoint < 0) _outpoint += _len; } return _lastout = _dline[_outpoint++]; } // Set output pointer <_outpoint>. void Odelay::setdelay(double lagsamps) { if (lagsamps >= (double) _len) resize((long)(lagsamps + 0.5)); _outpoint = long(_inpoint - lagsamps - 0.5); if (_len > 0) { while (_outpoint < 0) _outpoint += _len; } } float Odelay::next(float input) { _dline[_inpoint++] = input; if (_inpoint == _len) _inpoint = 0; _lastout = _dline[_outpoint++]; if (_outpoint == _len) _outpoint = 0; return _lastout; } static float *newFloats(float *oldptr, long oldlen, long *newlen) { float *ptr = NULL; if (oldptr == NULL) { ptr = (float *) malloc(*newlen * sizeof(float)); } else { float *newptr = (float *) realloc(oldptr, *newlen * sizeof(float)); if (newptr) { ptr = newptr; // Zero out new portion. for (long n = oldlen; n < *newlen; ++n) ptr[n] = 0.0f; } else { *newlen = oldlen; // notify caller that realloc failed ptr = oldptr; } } return ptr; } int Odelay::resize(long thisLength) { // Make a guess at how big the new array should be. long newlen = (thisLength < _len * 2) ? _len * 2 : _len + thisLength; _dline = ::newFloats(_dline, _len, &newlen); return _len = newlen; } float Odelay::delay() const { return (float) (_len > 0) ? abs((_outpoint - _inpoint) % _len) : 0; } <|endoftext|>
<commit_before>// alembicPlugin // Initial code generated by Softimage SDK Wizard // Executed Fri Aug 19 09:14:49 UTC+0200 2011 by helge // // Tip: You need to compile the generated code before you can load the plug-in. // After you compile the plug-in, you can load it by clicking Update All in the Plugin Manager. #include "stdafx.h" #include "arnoldHelpers.h" using namespace XSI; using namespace MATH; #include "AlembicLicensing.h" #include "AlembicWriteJob.h" #include "AlembicPoints.h" #include "AlembicCurves.h" #include "CommonProfiler.h" #include "CommonMeshUtilities.h" #include "CommonUtilities.h" ESS_CALLBACK_START(alembic_standinop_Define, CRef&) Context ctxt( in_ctxt ); CustomOperator oCustomOperator; Parameter oParam; CRef oPDef; Factory oFactory = Application().GetFactory(); oCustomOperator = ctxt.GetSource(); oPDef = oFactory.CreateParamDef(L"tokens",CValue::siString,siPersistable,L"tokens",L"tokens",L"",L"",L"",L"",L""); oCustomOperator.AddParameter(oPDef,oParam); oPDef = oFactory.CreateParamDef(L"time",CValue::siFloat,siPersistable | siAnimatable,L"time",L"time",0.0f,-100000.0f,100000.0f,0.0f,100.0f); oCustomOperator.AddParameter(oPDef,oParam); oCustomOperator.PutAlwaysEvaluate(false); oCustomOperator.PutDebug(0); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START(alembic_standinop_DefineLayout, CRef&) Context ctxt( in_ctxt ); PPGLayout oLayout; PPGItem oItem; oLayout = ctxt.GetSource(); oLayout.Clear(); oLayout.AddItem(L"tokens",L"Tokens"); oLayout.AddItem(L"time",L"Time"); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START(alembic_standinop_Update, CRef&) // if we are not interactive, let's just return here // the property should have all of its values anyways if(!Application().IsInteractive()) return CStatus::OK; OperatorContext ctxt( in_ctxt ); CString tokens = ctxt.GetParameterValue(L"tokens"); CStringArray paths(2); CStringArray identifiers(2); CString renderidentifier; CustomOperator op(ctxt.GetInputValue(0)); CRef x3dRef; if(op.IsValid()) { paths[0] = op.GetParameterValue(L"path"); identifiers[0] = op.GetParameterValue(L"identifier"); paths[1] = op.GetParameterValue(L"renderpath"); identifiers[1] = op.GetParameterValue(L"renderidentifier"); x3dRef = op.GetParent3DObject().GetRef(); } else { ICENode node(ctxt.GetInputValue(0)); paths[0] = node.GetParameterValue(L"path_string"); identifiers[0] = node.GetParameterValue(L"identifier_string"); paths[1] = node.GetParameterValue(L"renderpath_string"); identifiers[1] = node.GetParameterValue(L"renderidentifier_string"); CString nodeFullName = node.GetFullName(); CStringArray nodeNameParts = nodeFullName.Split(L"."); CRef modelRef; modelRef.Set(nodeNameParts[0]); Model model(modelRef); if(model.IsValid()) x3dRef.Set(nodeNameParts[0]+L"."+nodeNameParts[1]); else x3dRef = modelRef; } //CStatus pathEditStat = alembicOp_PathEdit( in_ctxt ); // try to replace all tokens except for the environment token for(LONG i=0;i<paths.GetCount();i++) { // let's replace the [env name] token with a custom one // [alembicenv0], and then we can add these tokens ourselves CString result; CStringArray envVarNames; CStringArray envVarValues; while(paths[i].Length() > 0) { CString subString = paths[i].GetSubString(0,paths[i].FindString(L"[")+1); if(subString.IsEmpty()) { result += paths[i]; break; } result += subString.GetSubString(0,subString.Length()-1); paths[i] = paths[i].GetSubString(subString.Length(),10000); if(paths[i].GetSubString(0,4).IsEqualNoCase(L"env ")) { subString = paths[i].GetSubString(0,paths[i].FindString(L"]")); if(subString.IsEmpty()) { result += paths[i]; break; } paths[i] = paths[i].GetSubString(subString.Length()+1,10000); CString envVarName = L"tempenvvar"+CString(envVarNames.GetCount()); envVarNames.Add(envVarName); envVarValues.Add(L"{"+subString+L"}"); result += L"["+envVarName+L"]"; } else { // save other tokens subString = paths[i].GetSubString(0,paths[i].FindString(L"]")); paths[i] = paths[i].GetSubString(subString.Length()+1,10000); result += L"["+subString+L"]"; } } paths[i] = XSI::CUtils::ResolveTokenString(result,XSI::CTime(),false,envVarNames,envVarValues); } float time = ctxt.GetParameterValue(L"time"); CString data = tokens; CString tokensLower = tokens; tokensLower.Lower(); tokensLower = L"&" + tokensLower; if(tokensLower.FindString(L"&path=") == -1) data += CString(data.IsEmpty() ? L"" : L"&") + L"path="+(paths[1].IsEmpty() ? paths[0] : paths[1]); if(tokensLower.FindString(L"&identifier=") == -1) data += CString(data.IsEmpty() ? L"" : L"&") + L"identifier="+(identifiers[1].IsEmpty() ? identifiers[0] : identifiers[1]); float globalTime = floorf(time * 1000.0f + 0.5f) / 1000.0f; if(tokensLower.FindString(L"&time=") == -1) data += CString(data.IsEmpty() ? L"" : L"&") + L"time="+CValue(globalTime).GetAsText(); float currentTime = (float)(floor(CTime().GetTime(CTime::Seconds) * 1000.0 + 0.5) / 1000.0); if(tokensLower.FindString(L"&currtime=") == -1) data += CString(data.IsEmpty() ? L"" : L"&") + L"currtime="+CValue(currentTime).GetAsText(); // now get the motion blur keys if(tokensLower.FindString(L"&mbkeys=") == -1) { CString mbKeysStr; CDoubleArray mbKeys; GetArnoldMotionBlurData(mbKeys,globalTime * (float)CTime().GetFrameRate()); if(mbKeys.GetCount() > 0) { mbKeysStr = L"mbkeys="+CValue(floorf(float(mbKeys[0]) * 1000.0f + 0.5f) / (1000.0f * (float)CTime().GetFrameRate())).GetAsText(); for(LONG i=1;i<mbKeys.GetCount();i++) mbKeysStr += L";"+CValue(floorf(float(mbKeys[i]) * 1000.0f + 0.5f) / (1000.0f * (float)CTime().GetFrameRate())).GetAsText(); } if(!mbKeysStr.IsEmpty()) data += CString(data.IsEmpty() ? L"" : L"&")+mbKeysStr; } // output the data to a custom property CustomProperty prop(ctxt.GetOutputTarget()); prop.PutParameterValue(L"path",getDSOPath()); prop.PutParameterValue(L"dsodata",data); prop.PutParameterValue(L"boundsType",(LONG)0l); //prop.PutParameterValue(L"deferredLoading",true); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START( alembic_standinop_Term, CRef& ) return alembicOp_Term(in_ctxt); ESS_CALLBACK_END<commit_msg>path edit ref update<commit_after>// alembicPlugin // Initial code generated by Softimage SDK Wizard // Executed Fri Aug 19 09:14:49 UTC+0200 2011 by helge // // Tip: You need to compile the generated code before you can load the plug-in. // After you compile the plug-in, you can load it by clicking Update All in the Plugin Manager. #include "stdafx.h" #include "arnoldHelpers.h" using namespace XSI; using namespace MATH; #include "AlembicLicensing.h" #include "AlembicWriteJob.h" #include "AlembicPoints.h" #include "AlembicCurves.h" #include "CommonProfiler.h" #include "CommonMeshUtilities.h" #include "CommonUtilities.h" ESS_CALLBACK_START(alembic_standinop_Define, CRef&) Context ctxt( in_ctxt ); CustomOperator oCustomOperator; Parameter oParam; CRef oPDef; Factory oFactory = Application().GetFactory(); oCustomOperator = ctxt.GetSource(); oPDef = oFactory.CreateParamDef(L"tokens",CValue::siString,siPersistable,L"tokens",L"tokens",L"",L"",L"",L"",L""); oCustomOperator.AddParameter(oPDef,oParam); oPDef = oFactory.CreateParamDef(L"time",CValue::siFloat,siPersistable | siAnimatable,L"time",L"time",0.0f,-100000.0f,100000.0f,0.0f,100.0f); oCustomOperator.AddParameter(oPDef,oParam); oCustomOperator.PutAlwaysEvaluate(false); oCustomOperator.PutDebug(0); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START(alembic_standinop_DefineLayout, CRef&) Context ctxt( in_ctxt ); PPGLayout oLayout; PPGItem oItem; oLayout = ctxt.GetSource(); oLayout.Clear(); oLayout.AddItem(L"tokens",L"Tokens"); oLayout.AddItem(L"time",L"Time"); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START(alembic_standinop_Update, CRef&) // if we are not interactive, let's just return here // the property should have all of its values anyways if(!Application().IsInteractive()) return CStatus::OK; OperatorContext ctxt( in_ctxt ); CString tokens = ctxt.GetParameterValue(L"tokens"); CStringArray paths(2); CStringArray identifiers(2); CString renderidentifier; CustomOperator op(ctxt.GetInputValue(0)); CRef x3dRef; if(op.IsValid()) { paths[0] = op.GetParameterValue(L"path"); identifiers[0] = op.GetParameterValue(L"identifier"); paths[1] = op.GetParameterValue(L"renderpath"); identifiers[1] = op.GetParameterValue(L"renderidentifier"); x3dRef = op.GetParent3DObject().GetRef(); } else { ICENode node(ctxt.GetInputValue(0)); paths[0] = node.GetParameterValue(L"path_string"); identifiers[0] = node.GetParameterValue(L"identifier_string"); paths[1] = node.GetParameterValue(L"renderpath_string"); identifiers[1] = node.GetParameterValue(L"renderidentifier_string"); CString nodeFullName = node.GetFullName(); CStringArray nodeNameParts = nodeFullName.Split(L"."); CRef modelRef; modelRef.Set(nodeNameParts[0]); Model model(modelRef); if(model.IsValid()) x3dRef.Set(nodeNameParts[0]+L"."+nodeNameParts[1]); else x3dRef = modelRef; } CStatus pathEditStat = alembicOp_PathEdit( in_ctxt, paths[0] ); // try to replace all tokens except for the environment token for(LONG i=0;i<paths.GetCount();i++) { // let's replace the [env name] token with a custom one // [alembicenv0], and then we can add these tokens ourselves CString result; CStringArray envVarNames; CStringArray envVarValues; while(paths[i].Length() > 0) { CString subString = paths[i].GetSubString(0,paths[i].FindString(L"[")+1); if(subString.IsEmpty()) { result += paths[i]; break; } result += subString.GetSubString(0,subString.Length()-1); paths[i] = paths[i].GetSubString(subString.Length(),10000); if(paths[i].GetSubString(0,4).IsEqualNoCase(L"env ")) { subString = paths[i].GetSubString(0,paths[i].FindString(L"]")); if(subString.IsEmpty()) { result += paths[i]; break; } paths[i] = paths[i].GetSubString(subString.Length()+1,10000); CString envVarName = L"tempenvvar"+CString(envVarNames.GetCount()); envVarNames.Add(envVarName); envVarValues.Add(L"{"+subString+L"}"); result += L"["+envVarName+L"]"; } else { // save other tokens subString = paths[i].GetSubString(0,paths[i].FindString(L"]")); paths[i] = paths[i].GetSubString(subString.Length()+1,10000); result += L"["+subString+L"]"; } } paths[i] = XSI::CUtils::ResolveTokenString(result,XSI::CTime(),false,envVarNames,envVarValues); } float time = ctxt.GetParameterValue(L"time"); CString data = tokens; CString tokensLower = tokens; tokensLower.Lower(); tokensLower = L"&" + tokensLower; if(tokensLower.FindString(L"&path=") == -1) data += CString(data.IsEmpty() ? L"" : L"&") + L"path="+(paths[1].IsEmpty() ? paths[0] : paths[1]); if(tokensLower.FindString(L"&identifier=") == -1) data += CString(data.IsEmpty() ? L"" : L"&") + L"identifier="+(identifiers[1].IsEmpty() ? identifiers[0] : identifiers[1]); float globalTime = floorf(time * 1000.0f + 0.5f) / 1000.0f; if(tokensLower.FindString(L"&time=") == -1) data += CString(data.IsEmpty() ? L"" : L"&") + L"time="+CValue(globalTime).GetAsText(); float currentTime = (float)(floor(CTime().GetTime(CTime::Seconds) * 1000.0 + 0.5) / 1000.0); if(tokensLower.FindString(L"&currtime=") == -1) data += CString(data.IsEmpty() ? L"" : L"&") + L"currtime="+CValue(currentTime).GetAsText(); // now get the motion blur keys if(tokensLower.FindString(L"&mbkeys=") == -1) { CString mbKeysStr; CDoubleArray mbKeys; GetArnoldMotionBlurData(mbKeys,globalTime * (float)CTime().GetFrameRate()); if(mbKeys.GetCount() > 0) { mbKeysStr = L"mbkeys="+CValue(floorf(float(mbKeys[0]) * 1000.0f + 0.5f) / (1000.0f * (float)CTime().GetFrameRate())).GetAsText(); for(LONG i=1;i<mbKeys.GetCount();i++) mbKeysStr += L";"+CValue(floorf(float(mbKeys[i]) * 1000.0f + 0.5f) / (1000.0f * (float)CTime().GetFrameRate())).GetAsText(); } if(!mbKeysStr.IsEmpty()) data += CString(data.IsEmpty() ? L"" : L"&")+mbKeysStr; } // output the data to a custom property CustomProperty prop(ctxt.GetOutputTarget()); prop.PutParameterValue(L"path",getDSOPath()); prop.PutParameterValue(L"dsodata",data); prop.PutParameterValue(L"boundsType",(LONG)0l); //prop.PutParameterValue(L"deferredLoading",true); return CStatus::OK; ESS_CALLBACK_END ESS_CALLBACK_START( alembic_standinop_Term, CRef& ) return alembicOp_Term(in_ctxt); ESS_CALLBACK_END<|endoftext|>
<commit_before> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QMessageBox> #include <QtWidgets/QStatusBar> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QTextStream> #include <QtCore/QIODevice> #include <QtGui/QPalette> #include <QtGui/QColor> #include <QtGui/QGuiApplication> #include <QtGui/QClipboard> #include <QtWidgets/QMainWindow> #include <QtWidgets/QPushButton> #include <QtWidgets/QComboBox> #include <QtWidgets/QGridLayout> #include <QtWidgets/QTabWidget> #define __STDC_FORMAT_MACROS #include <cinttypes> #include "dwr.h" #include "sprites.h" #include "main-window.h" enum tabs { GAMEPLAY, COSMETIC }; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { this->mainWidget = new QWidget(); this->gameplayWidget = new QWidget(); this->funWidget = new QWidget(); this->setCentralWidget(this->mainWidget); this->initWidgets(); this->initStatus(); this->layout(); this->initSlots(); this->loadConfig(); } void MainWindow::initStatus() { QStatusBar *status = this->statusBar(); status->showMessage("Ready"); QPalette palette = this->palette(); palette.setColor(QPalette::Background, Qt::lightGray); palette.setColor(QPalette::Foreground, Qt::black); status->setPalette(palette); status->setAutoFillBackground(true); } void MainWindow::initWidgets() { this->romFile = new FileEntry(this); this->outputDir = new DirEntry(this); this->seed = new SeedEntry(this); this->flags = new FlagEntry(this); this->levelSpeed = new LevelComboBox(this); this->goButton = new QPushButton("Randomize!", this); this->spriteSelect = new QComboBox(this); for (int i=0; i < sizeof(dwr_sprite_names)/sizeof(char*); ++i) { spriteSelect->addItem(dwr_sprite_names[i]); } this->tabWidget = new QTabWidget(this); this->tabContents[0] = new QWidget(this); this->tabContents[1] = new QWidget(this); } void MainWindow::initSlots() { connect(this->flags, SIGNAL(textEdited(QString)), this, SLOT(handleFlags())); connect(this->levelSpeed, SIGNAL(activated(int)), this, SLOT(handleCheckBox())); connect(this->goButton, SIGNAL(clicked()), this, SLOT(handleButton())); } void MainWindow::layout() { QVBoxLayout *vbox; QGridLayout *grid; QGridLayout *goLayout; this->optionGrids[0] = new QGridLayout(); this->optionGrids[1] = new QGridLayout(); vbox = new QVBoxLayout(); grid = new QGridLayout(); goLayout = new QGridLayout(); vbox->addLayout(grid); vbox->addWidget(tabWidget); vbox->addLayout(goLayout); this->tabContents[0]->setLayout(this->optionGrids[0]); this->tabContents[1]->setLayout(this->optionGrids[1]); grid->addWidget(this->romFile, 0, 0, 0); grid->addWidget(this->outputDir, 0, 1, 0); grid->addWidget(this->seed, 1, 0, 0); grid->addWidget(this->flags, 1, 1, 0); tabWidget->addTab(tabContents[0], "Gameplay Options"); tabWidget->addTab(tabContents[1], "Cosmetic Options"); /* Gameplay Options */ this->addOption('C', "Shuffle Chests && Search Items", GAMEPLAY, 0, 0); this->addOption('W', "Randomize Weapon Shops", GAMEPLAY, 1, 0); this->addOption('G', "Randomize Growth", GAMEPLAY, 2, 0); this->addOption('M', "Randomize Spell Learning", GAMEPLAY, 3, 0); this->addOption('X', "Chaos Mode", GAMEPLAY, 4, 0); this->addOption('P', "Randomize Enemy Attacks", GAMEPLAY, 0, 1); this->addOption('Z', "Randomize Enemy Zones", GAMEPLAY, 1, 1); this->addOption('R', "Enable Menu Wrapping", GAMEPLAY, 2, 1); this->addOption('D', "Enable Death Necklace", GAMEPLAY, 3, 1); this->addOption('b', "Big Swamp", GAMEPLAY, 4, 1); this->addOption('t', "Fast Text", GAMEPLAY, 0, 2); this->addOption('h', "Speed Hacks", GAMEPLAY, 1, 2); this->addOption('o', "Open Charlock", GAMEPLAY, 2, 2); this->addOption('s', "Short Charlock", GAMEPLAY, 3, 2); this->addOption('k', "Don't Require Magic Keys", GAMEPLAY, 4, 2); /* Cosmetic Options */ this->addOption('K', "Shuffle Music", COSMETIC, 0, 0); this->addOption('Q', "Disable Music", COSMETIC, 1, 0); this->addOption('m', "Modern Spell Names", COSMETIC, 2, 0); this->addLabel("Leveling Speed", GAMEPLAY, 7, 0); this->placeWidget(this->levelSpeed, GAMEPLAY, 8, 0); this->addLabel("Player Sprite", COSMETIC, 7, 0); this->placeWidget(this->spriteSelect, COSMETIC, 8, 0); /* Add some empty labels for padding */ this->addLabel("", GAMEPLAY, 5, 1); this->addLabel("", GAMEPLAY, 6, 1); this->addLabel("", COSMETIC, 0, 1); this->addLabel("", COSMETIC, 0, 2); this->addLabel("", COSMETIC, 2, 0); this->addLabel("", COSMETIC, 3, 0); this->addLabel("", COSMETIC, 4, 0); this->addLabel("", COSMETIC, 5, 0); this->addLabel("", COSMETIC, 6, 0); goLayout->addWidget(new QLabel("", this), 0, 0, 0); goLayout->addWidget(new QLabel("", this), 0, 1, 0); goLayout->addWidget(this->goButton, 0, 2, 0); this->mainWidget->setLayout(vbox); } void MainWindow::addOption(char flag, QString text, int tab, int x, int y) { CheckBox *option = new CheckBox(flag, text, this); connect(option, SIGNAL(clicked()), this, SLOT(handleCheckBox())); this->options.append(option); this->optionGrids[tab]->addWidget(option, x, y, 0); } void MainWindow::addLabel(QString text, int tab, int x, int y) { this->optionGrids[tab]->addWidget(new QLabel(text, this), x, y, 0); } void MainWindow::placeWidget(QWidget *widget, int tab, int x, int y) { this->optionGrids[tab]->addWidget(widget, x, y, 0); } QString MainWindow::getOptions() { QList<CheckBox*>::const_iterator i; std::string flags = std::string() + this->levelSpeed->getFlag(); for (i = this->options.begin(); i != this->options.end(); ++i) { flags += (*i)->getFlag(); } std::sort(flags.begin(), flags.end()); std::replace(flags.begin(), flags.end(), NO_FLAG, '\0'); return QString(flags.c_str()); } void MainWindow::setOptions(QString flags) { QList<CheckBox*>::const_iterator i; for (i = this->options.begin(); i != this->options.end(); ++i) { flags += (*i)->updateState(flags); } this->levelSpeed->updateState(flags); } QString MainWindow::getFlags() { std::string flags = this->flags->text().toStdString(); std::sort(flags.begin(), flags.end()); return QString::fromStdString(flags); } void MainWindow::setFlags(QString flags) { this->flags->setText(flags); } void MainWindow::handleCheckBox() { QString flags = this->getOptions(); this->setFlags(flags); } void MainWindow::handleComboBox(int index) { this->handleCheckBox(); } void MainWindow::handleFlags() { QString flags = this->getFlags(); this->setOptions(flags); } void MainWindow::handleButton() { char flags[64], checksum[64]; QString flagStr = this->getFlags(); strncpy(flags, flagStr.toLatin1().constData(), 63); uint64_t seed = this->seed->getSeed(); std::string inputFile = this->romFile->text().toLatin1().constData(); std::string outputDir = this->outputDir->text().toLatin1().constData(); std::string spriteName = this->spriteSelect->currentText().toLatin1().constData(); uint64_t crc = dwr_randomize(inputFile.c_str(), seed, flags, spriteName.c_str(), outputDir.c_str()); if (crc) { sprintf(checksum, "Checksum: %016" PRIx64, crc); QGuiApplication::clipboard()->setText(checksum); this->statusBar()->showMessage( QString("%1 (copied to clipboard)").arg(checksum)); QMessageBox::information(this, "Success!", "The new ROM has been created."); } else { QMessageBox::critical(this, "Failed", "An error occurred and" "the ROM could not be created."); } this->saveConfig(); // this->seed->random(); } bool MainWindow::saveConfig() { QDir configDir(""); if (!configDir.exists(QDir::homePath() + "/.config/")){ configDir.mkdir(QDir::homePath() + "/.config/"); } QFile configFile(QDir::homePath() + "/.config/dwrandomizer2.conf"); if (!configFile.open(QIODevice::WriteOnly | QIODevice::Text)) { printf("Failed to save configuration.\n"); return false; } QTextStream out(&configFile); out << this->romFile->text() << endl; out << this->outputDir->text() << endl; out << this->getFlags() << endl; out << this->spriteSelect->currentIndex() << endl; return true; } bool MainWindow::loadConfig() { char tmp[1024]; qint64 read; QFile configFile(QDir::homePath() + "/.config/dwrandomizer2.conf"); if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text)) { printf("Failed to load configuration.\n"); return false; } read = configFile.readLine(tmp, 1024); if (read) { tmp[read - 1] = '\0'; this->romFile->setText(tmp); if (configFile.atEnd()) { return false; } } read = configFile.readLine(tmp, 1024); if (read) { tmp[read - 1] = '\0'; this->outputDir->setText(tmp); if (configFile.atEnd()) { return false; } } read = configFile.readLine(tmp, 1024); if (read) { tmp[read - 1] = '\0'; this->setFlags(tmp); this->setOptions(tmp); } read = configFile.readLine(tmp, 1024); if (read) { int spriteIndex = atoi(tmp); this->spriteSelect->setCurrentIndex(spriteIndex); } return true; } <commit_msg>Fixed another UI issue<commit_after> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QMessageBox> #include <QtWidgets/QStatusBar> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QTextStream> #include <QtCore/QIODevice> #include <QtGui/QPalette> #include <QtGui/QColor> #include <QtGui/QGuiApplication> #include <QtGui/QClipboard> #include <QtWidgets/QMainWindow> #include <QtWidgets/QPushButton> #include <QtWidgets/QComboBox> #include <QtWidgets/QGridLayout> #include <QtWidgets/QTabWidget> #define __STDC_FORMAT_MACROS #include <cinttypes> #include "dwr.h" #include "sprites.h" #include "main-window.h" enum tabs { GAMEPLAY, COSMETIC }; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { this->mainWidget = new QWidget(); this->gameplayWidget = new QWidget(); this->funWidget = new QWidget(); this->setCentralWidget(this->mainWidget); this->initWidgets(); this->initStatus(); this->layout(); this->initSlots(); this->loadConfig(); } void MainWindow::initStatus() { QStatusBar *status = this->statusBar(); status->showMessage("Ready"); QPalette palette = this->palette(); palette.setColor(QPalette::Background, Qt::lightGray); palette.setColor(QPalette::Foreground, Qt::black); status->setPalette(palette); status->setAutoFillBackground(true); } void MainWindow::initWidgets() { this->romFile = new FileEntry(this); this->outputDir = new DirEntry(this); this->seed = new SeedEntry(this); this->flags = new FlagEntry(this); this->levelSpeed = new LevelComboBox(this); this->goButton = new QPushButton("Randomize!", this); this->spriteSelect = new QComboBox(this); for (int i=0; i < sizeof(dwr_sprite_names)/sizeof(char*); ++i) { spriteSelect->addItem(dwr_sprite_names[i]); } this->tabWidget = new QTabWidget(this); this->tabContents[0] = new QWidget(this); this->tabContents[1] = new QWidget(this); } void MainWindow::initSlots() { connect(this->flags, SIGNAL(textEdited(QString)), this, SLOT(handleFlags())); connect(this->levelSpeed, SIGNAL(activated(int)), this, SLOT(handleCheckBox())); connect(this->goButton, SIGNAL(clicked()), this, SLOT(handleButton())); } void MainWindow::layout() { QVBoxLayout *vbox; QGridLayout *grid; QGridLayout *goLayout; this->optionGrids[0] = new QGridLayout(); this->optionGrids[1] = new QGridLayout(); vbox = new QVBoxLayout(); grid = new QGridLayout(); goLayout = new QGridLayout(); vbox->addLayout(grid); vbox->addWidget(tabWidget); vbox->addLayout(goLayout); this->tabContents[0]->setLayout(this->optionGrids[0]); this->tabContents[1]->setLayout(this->optionGrids[1]); grid->addWidget(this->romFile, 0, 0, 0); grid->addWidget(this->outputDir, 0, 1, 0); grid->addWidget(this->seed, 1, 0, 0); grid->addWidget(this->flags, 1, 1, 0); tabWidget->addTab(tabContents[0], "Gameplay Options"); tabWidget->addTab(tabContents[1], "Cosmetic Options"); /* Add some empty labels for padding */ this->addLabel("", GAMEPLAY, 5, 1); this->addLabel("", GAMEPLAY, 6, 1); this->addLabel("", COSMETIC, 0, 1); this->addLabel("", COSMETIC, 0, 2); this->addLabel("", COSMETIC, 3, 0); this->addLabel("", COSMETIC, 4, 0); this->addLabel("", COSMETIC, 5, 0); this->addLabel("", COSMETIC, 6, 0); /* Gameplay Options */ this->addOption('C', "Shuffle Chests && Search Items", GAMEPLAY, 0, 0); this->addOption('W', "Randomize Weapon Shops", GAMEPLAY, 1, 0); this->addOption('G', "Randomize Growth", GAMEPLAY, 2, 0); this->addOption('M', "Randomize Spell Learning", GAMEPLAY, 3, 0); this->addOption('X', "Chaos Mode", GAMEPLAY, 4, 0); this->addOption('P', "Randomize Enemy Attacks", GAMEPLAY, 0, 1); this->addOption('Z', "Randomize Enemy Zones", GAMEPLAY, 1, 1); this->addOption('R', "Enable Menu Wrapping", GAMEPLAY, 2, 1); this->addOption('D', "Enable Death Necklace", GAMEPLAY, 3, 1); this->addOption('b', "Big Swamp", GAMEPLAY, 4, 1); this->addOption('t', "Fast Text", GAMEPLAY, 0, 2); this->addOption('h', "Speed Hacks", GAMEPLAY, 1, 2); this->addOption('o', "Open Charlock", GAMEPLAY, 2, 2); this->addOption('s', "Short Charlock", GAMEPLAY, 3, 2); this->addOption('k', "Don't Require Magic Keys", GAMEPLAY, 4, 2); /* Cosmetic Options */ this->addOption('K', "Shuffle Music", COSMETIC, 0, 0); this->addOption('Q', "Disable Music", COSMETIC, 1, 0); this->addOption('m', "Modern Spell Names", COSMETIC, 2, 0); this->addLabel("Leveling Speed", GAMEPLAY, 7, 0); this->placeWidget(this->levelSpeed, GAMEPLAY, 8, 0); this->addLabel("Player Sprite", COSMETIC, 7, 0); this->placeWidget(this->spriteSelect, COSMETIC, 8, 0); goLayout->addWidget(new QLabel("", this), 0, 0, 0); goLayout->addWidget(new QLabel("", this), 0, 1, 0); goLayout->addWidget(this->goButton, 0, 2, 0); this->mainWidget->setLayout(vbox); } void MainWindow::addOption(char flag, QString text, int tab, int x, int y) { CheckBox *option = new CheckBox(flag, text, this); connect(option, SIGNAL(clicked()), this, SLOT(handleCheckBox())); this->options.append(option); this->optionGrids[tab]->addWidget(option, x, y, 0); } void MainWindow::addLabel(QString text, int tab, int x, int y) { this->optionGrids[tab]->addWidget(new QLabel(text, this), x, y, 0); } void MainWindow::placeWidget(QWidget *widget, int tab, int x, int y) { this->optionGrids[tab]->addWidget(widget, x, y, 0); } QString MainWindow::getOptions() { QList<CheckBox*>::const_iterator i; std::string flags = std::string() + this->levelSpeed->getFlag(); for (i = this->options.begin(); i != this->options.end(); ++i) { flags += (*i)->getFlag(); } std::sort(flags.begin(), flags.end()); std::replace(flags.begin(), flags.end(), NO_FLAG, '\0'); return QString(flags.c_str()); } void MainWindow::setOptions(QString flags) { QList<CheckBox*>::const_iterator i; for (i = this->options.begin(); i != this->options.end(); ++i) { flags += (*i)->updateState(flags); } this->levelSpeed->updateState(flags); } QString MainWindow::getFlags() { std::string flags = this->flags->text().toStdString(); std::sort(flags.begin(), flags.end()); return QString::fromStdString(flags); } void MainWindow::setFlags(QString flags) { this->flags->setText(flags); } void MainWindow::handleCheckBox() { QString flags = this->getOptions(); this->setFlags(flags); } void MainWindow::handleComboBox(int index) { this->handleCheckBox(); } void MainWindow::handleFlags() { QString flags = this->getFlags(); this->setOptions(flags); } void MainWindow::handleButton() { char flags[64], checksum[64]; QString flagStr = this->getFlags(); strncpy(flags, flagStr.toLatin1().constData(), 63); uint64_t seed = this->seed->getSeed(); std::string inputFile = this->romFile->text().toLatin1().constData(); std::string outputDir = this->outputDir->text().toLatin1().constData(); std::string spriteName = this->spriteSelect->currentText().toLatin1().constData(); uint64_t crc = dwr_randomize(inputFile.c_str(), seed, flags, spriteName.c_str(), outputDir.c_str()); if (crc) { sprintf(checksum, "Checksum: %016" PRIx64, crc); QGuiApplication::clipboard()->setText(checksum); this->statusBar()->showMessage( QString("%1 (copied to clipboard)").arg(checksum)); QMessageBox::information(this, "Success!", "The new ROM has been created."); } else { QMessageBox::critical(this, "Failed", "An error occurred and" "the ROM could not be created."); } this->saveConfig(); // this->seed->random(); } bool MainWindow::saveConfig() { QDir configDir(""); if (!configDir.exists(QDir::homePath() + "/.config/")){ configDir.mkdir(QDir::homePath() + "/.config/"); } QFile configFile(QDir::homePath() + "/.config/dwrandomizer2.conf"); if (!configFile.open(QIODevice::WriteOnly | QIODevice::Text)) { printf("Failed to save configuration.\n"); return false; } QTextStream out(&configFile); out << this->romFile->text() << endl; out << this->outputDir->text() << endl; out << this->getFlags() << endl; out << this->spriteSelect->currentIndex() << endl; return true; } bool MainWindow::loadConfig() { char tmp[1024]; qint64 read; QFile configFile(QDir::homePath() + "/.config/dwrandomizer2.conf"); if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text)) { printf("Failed to load configuration.\n"); return false; } read = configFile.readLine(tmp, 1024); if (read) { tmp[read - 1] = '\0'; this->romFile->setText(tmp); if (configFile.atEnd()) { return false; } } read = configFile.readLine(tmp, 1024); if (read) { tmp[read - 1] = '\0'; this->outputDir->setText(tmp); if (configFile.atEnd()) { return false; } } read = configFile.readLine(tmp, 1024); if (read) { tmp[read - 1] = '\0'; this->setFlags(tmp); this->setOptions(tmp); } read = configFile.readLine(tmp, 1024); if (read) { int spriteIndex = atoi(tmp); this->spriteSelect->setCurrentIndex(spriteIndex); } return true; } <|endoftext|>
<commit_before>/** * @file ArdusatLogging.cpp * @Author Ben Peters ([email protected]) * @date December 3, 2014 * @brief Implements functions necessary for logging results to an SD card instead of stdout. */ #include <stdio.h> #include <string.h> #include "ArdusatLogging.h" RTC_DS1307 RTC; SdVolume vol; SdFat sd; File file; prog_char sd_card_error[] = "Not enough RAM for SD card sys(free: "; prog_char csv_header_fmt[] = "timestamp: %lu at millis %lu\n"; /** * Helper function to log null-terminated output buffer string to file. * * @param output_buf pointer to output buffer to log. * * @return number of bytes written */ int logString(const char *output_buf) { int buf_len = strlen(output_buf); return logBytes((const unsigned char *)output_buf, buf_len); } /** * Log the byte array pointed to by buffer to the SD card. Note that there is * absolutely no safety checking on numBytes, so use with care. * * Since we use a shared buffer between the SD card library and many of the output * functions, performs a check first to see if we need to allocate a new buffer. * * @param buffer byte array to log * @param number of bytes to log * * @return number of bytes written */ int logBytes(const unsigned char *buffer, unsigned char numBytes) { unsigned char *buf; int written; bool buf_allocated = false; if (numBytes > OUTPUT_BUF_SIZE - 1) { numBytes = OUTPUT_BUF_SIZE - 1; } if (file.isOpen()) { if (buffer == (unsigned char *) _getOutBuf()) { buf = (unsigned char *) malloc(numBytes); buf_allocated = true; memcpy(buf, buffer, numBytes); } else { buf = (unsigned char *) buffer; } written = file.write(buf, numBytes); file.sync(); if (buf_allocated) free(buf); return written; } else { return 0; } } /** * Logs a line of CSV formatted acceleration data to the SD card. * * @param sensorName of this sensor * @param data acceleration_t data to log * * @return number of bytes written */ int logAcceleration(const char *sensorName, acceleration_t & data) { return logString(accelerationToCSV(sensorName, data)); } /** * Logs a line of CSV formatted magnetic data to the SD card. * * @param sensorName of this sensor * @param data magnetic_t data to log * * @return number of bytes written */ int logMagnetic(const char *sensorName, magnetic_t & data) { return logString(magneticToCSV(sensorName, data)); } /** * Logs a line of CSV formatted orientation data to the SD card. * * @param sensorName of this sensor * @param data gyro_t data to log * * @return number of bytes written */ int logGyro(const char *sensorName, gyro_t & data) { return logString(gyroToCSV(sensorName, data)); } /** * Logs a line of CSV formatted tempoerature data to the SD card. * * @param sensorName of this sensor * @param data temperature_t data to log * * @return number of bytes written */ int logTemperature(const char *sensorName, temperature_t & data) { return logString(temperatureToCSV(sensorName, data)); } /** * Logs a line of CSV formatted luminosity data to the SD card. * * @param sensorName of this sensor * @param data luminosity_t data to log * * @return number of bytes written */ int logLuminosity(const char *sensorName, luminosity_t & data) { return logString(luminosityToCSV(sensorName, data)); } /** * Logs a line of CSV formatted UV light data to the SD card. * * @param sensorName of this sensor * @param data uvlight_t data to log * * @return number of bytes written */ int logUVLight(const char *sensorName, uvlight_t & data) { return logString(uvlightToCSV(sensorName, data)); } /** * Logs a line of CSV formatted orientation data to SD card. * * @param sensorName of this sensor * @param data orientation_t data to log * * @return number of bytes written */ int logOrientation(const char *sensorName, orientation_t & data) { return logString(orientationToCSV(sensorName, data)); } /** * Logs a line of CSV formatted pressure data to SD card. * * @param sensorName of this sensor * @param data pressure_t data to log * * @return number of bytes written */ int logPressure(const char *sensorName, pressure_t & data) { return logString(pressureToCSV(sensorName, data)); } #define init_data_struct(type_def, type_enum) \ type_def bin_data; \ bin_data.type = type_enum; \ bin_data.id = sensorId; \ bin_data.timestamp = data.header.timestamp; int binaryLogAcceleration(const unsigned char sensorId, acceleration_t & data) { init_data_struct(acceleration_bin_t, ARDUSAT_SENSOR_TYPE_ACCELERATION) bin_data.x = data.x; bin_data.y = data.y; bin_data.z = data.z; return logBytes((unsigned char *) &bin_data, sizeof(acceleration_bin_t)); } int binaryLogMagnetic(const unsigned char sensorId, magnetic_t & data) { init_data_struct(magnetic_bin_t, ARDUSAT_SENSOR_TYPE_MAGNETIC) bin_data.x = data.x; bin_data.y = data.y; bin_data.z = data.z; return logBytes((unsigned char *) &bin_data, sizeof(magnetic_bin_t)); } int binaryLogGyro(const unsigned char sensorId, gyro_t & data) { init_data_struct(gyro_bin_t, ARDUSAT_SENSOR_TYPE_GYRO) bin_data.x = data.x; bin_data.y = data.y; bin_data.z = data.z; return logBytes((unsigned char *) &bin_data, sizeof(gyro_bin_t)); } int binaryLogTemperature(const unsigned char sensorId, temperature_t & data) { init_data_struct(temperature_bin_t, ARDUSAT_SENSOR_TYPE_TEMPERATURE) bin_data.temp = data.t; return logBytes((unsigned char *) &bin_data, sizeof(temperature_bin_t)); } int binaryLogLuminosity(const unsigned char sensorId, luminosity_t & data) { init_data_struct(luminosity_bin_t, ARDUSAT_SENSOR_TYPE_LUMINOSITY) bin_data.luminosity = data.lux; return logBytes((unsigned char *) &bin_data, sizeof(luminosity_bin_t)); } int binaryLogUVLight(const unsigned char sensorId, uvlight_t & data) { init_data_struct(uv_light_bin_t, ARDUSAT_SENSOR_TYPE_UV) bin_data.uv = data.uvindex; return logBytes((unsigned char *) &bin_data, sizeof(uv_light_bin_t)); } int binaryLogOrientation(const unsigned char sensorId, orientation_t & data) { init_data_struct(orientation_bin_t, ARDUSAT_SENSOR_TYPE_ORIENTATION) bin_data.roll = data.roll; bin_data.pitch = data.pitch; bin_data.heading = data.heading; return logBytes((unsigned char *) &bin_data, sizeof(orientation_bin_t)); } int binaryLogPressure(const unsigned char sensorId, pressure_t & data) { init_data_struct(pressure_bin_t, ARDUSAT_SENSOR_TYPE_PRESSURE) bin_data.pressure = data.pressure; return logBytes((unsigned char *) &bin_data, sizeof(pressure_bin_t)); } /* * Helper function to log to the top of the CSV header with the current time */ int _log_csv_time_header(DateTime & now, unsigned long curr_millis) { char fmt_buf[32]; strcpy_P(fmt_buf, csv_header_fmt); memset(_getOutBuf(), 0, OUTPUT_BUF_SIZE); sprintf(_getOutBuf(), fmt_buf, now.unixtime(), curr_millis); return logString(_getOutBuf()); } int _log_binary_time_header(DateTime & now, unsigned long curr_millis) { unsigned char buf[10]; unsigned long unixtime = now.unixtime(); buf[0] = 0xFF; buf[1] = 0xFF; memcpy(buf + 2, &unixtime, 4); memcpy(buf + 6, &curr_millis, 4); return logBytes(buf, 10); } /** * Function starts the SD card service and makes sure that the appropriate directory * structure exists, then creates the file to use for logging data. Data will be logged * to a file called fileNamePrefix_0.csv or fileNamePrefix_0.bin (number will be incremented * for each new log file) * * @param chipSelectPin Arduino pin SD card reader CS pin is attached to * @param fileNamePrefix string to prefix at beginning of data file * @param csvData boolean flag whether we are writing csv data or binary data (used for filename) * * @return true if successful, false if failed */ bool beginDataLog(int chipSelectPin, const char *fileNamePrefix, bool csvData) { bool ret; int i = 0; int max_len; char fileName[19]; char prefix[8]; char rootPath[] = "/data"; unsigned long curr_millis = 0; DateTime now; if (_output_buffer != NULL) { delete []_output_buffer; } OUTPUT_BUF_SIZE = 512; _output_buffer = vol.cacheAddress()->output_buf; // Try to get the current time from the RTC, if available. This will be prepended to the log file // to be used to convert relative timestamps to real time values. Wire.begin(); RTC.begin(); if (RTC.isrunning()) { now = RTC.now(); curr_millis = millis(); } if (freeMemory() < 400) { strcpy_P(_getOutBuf(), sd_card_error); Serial.print(_getOutBuf()); Serial.print(freeMemory()); Serial.println(", need 400)"); ret = false; } else { ret = sd.begin(chipSelectPin, SPI_FULL_SPEED); } //Filenames need to fit the 8.3 filename convention, so truncate down the //given filename if it is too long. memcpy(prefix, fileNamePrefix, 7); prefix[7] = '\0'; if (ret) { if (!sd.exists(rootPath)) ret = sd.mkdir(rootPath); if (ret) { while (true) { if (i < 10) { max_len = 7; } else if (i < 100) { max_len = 6; } else if (i < 1000) { max_len = 5; } else { break; } prefix[max_len - 1] = '\0'; sprintf(fileName, "%s/%s%d.%s", rootPath, prefix, i, csvData ? "csv" : "bin"); if (!sd.exists(fileName)) { file = sd.open(fileName, FILE_WRITE); break; } i++; } } } else { sd.initErrorPrint(); } if (RTC.isrunning() && file.isOpen()) { if (csvData) { _log_csv_time_header(now, curr_millis); } else { _log_binary_time_header(now, curr_millis); } } return file.isOpen(); } bool setRTC() { Wire.begin(); RTC.begin(); // Sets RTC to the date & time sketch was compiled RTC.adjust(DateTime(__DATE__, __TIME__)); return true; } <commit_msg>Updated prog_char definition for old Arduino IDE compatibility<commit_after>/** * @file ArdusatLogging.cpp * @Author Ben Peters ([email protected]) * @date December 3, 2014 * @brief Implements functions necessary for logging results to an SD card instead of stdout. */ #include <stdio.h> #include <string.h> #include "ArdusatLogging.h" RTC_DS1307 RTC; SdVolume vol; SdFat sd; File file; const prog_char sd_card_error[] = "Not enough RAM for SD card sys(free: "; const prog_char csv_header_fmt[] = "timestamp: %lu at millis %lu\n"; /** * Helper function to log null-terminated output buffer string to file. * * @param output_buf pointer to output buffer to log. * * @return number of bytes written */ int logString(const char *output_buf) { int buf_len = strlen(output_buf); return logBytes((const unsigned char *)output_buf, buf_len); } /** * Log the byte array pointed to by buffer to the SD card. Note that there is * absolutely no safety checking on numBytes, so use with care. * * Since we use a shared buffer between the SD card library and many of the output * functions, performs a check first to see if we need to allocate a new buffer. * * @param buffer byte array to log * @param number of bytes to log * * @return number of bytes written */ int logBytes(const unsigned char *buffer, unsigned char numBytes) { unsigned char *buf; int written; bool buf_allocated = false; if (numBytes > OUTPUT_BUF_SIZE - 1) { numBytes = OUTPUT_BUF_SIZE - 1; } if (file.isOpen()) { if (buffer == (unsigned char *) _getOutBuf()) { buf = (unsigned char *) malloc(numBytes); buf_allocated = true; memcpy(buf, buffer, numBytes); } else { buf = (unsigned char *) buffer; } written = file.write(buf, numBytes); file.sync(); if (buf_allocated) free(buf); return written; } else { return 0; } } /** * Logs a line of CSV formatted acceleration data to the SD card. * * @param sensorName of this sensor * @param data acceleration_t data to log * * @return number of bytes written */ int logAcceleration(const char *sensorName, acceleration_t & data) { return logString(accelerationToCSV(sensorName, data)); } /** * Logs a line of CSV formatted magnetic data to the SD card. * * @param sensorName of this sensor * @param data magnetic_t data to log * * @return number of bytes written */ int logMagnetic(const char *sensorName, magnetic_t & data) { return logString(magneticToCSV(sensorName, data)); } /** * Logs a line of CSV formatted orientation data to the SD card. * * @param sensorName of this sensor * @param data gyro_t data to log * * @return number of bytes written */ int logGyro(const char *sensorName, gyro_t & data) { return logString(gyroToCSV(sensorName, data)); } /** * Logs a line of CSV formatted tempoerature data to the SD card. * * @param sensorName of this sensor * @param data temperature_t data to log * * @return number of bytes written */ int logTemperature(const char *sensorName, temperature_t & data) { return logString(temperatureToCSV(sensorName, data)); } /** * Logs a line of CSV formatted luminosity data to the SD card. * * @param sensorName of this sensor * @param data luminosity_t data to log * * @return number of bytes written */ int logLuminosity(const char *sensorName, luminosity_t & data) { return logString(luminosityToCSV(sensorName, data)); } /** * Logs a line of CSV formatted UV light data to the SD card. * * @param sensorName of this sensor * @param data uvlight_t data to log * * @return number of bytes written */ int logUVLight(const char *sensorName, uvlight_t & data) { return logString(uvlightToCSV(sensorName, data)); } /** * Logs a line of CSV formatted orientation data to SD card. * * @param sensorName of this sensor * @param data orientation_t data to log * * @return number of bytes written */ int logOrientation(const char *sensorName, orientation_t & data) { return logString(orientationToCSV(sensorName, data)); } /** * Logs a line of CSV formatted pressure data to SD card. * * @param sensorName of this sensor * @param data pressure_t data to log * * @return number of bytes written */ int logPressure(const char *sensorName, pressure_t & data) { return logString(pressureToCSV(sensorName, data)); } #define init_data_struct(type_def, type_enum) \ type_def bin_data; \ bin_data.type = type_enum; \ bin_data.id = sensorId; \ bin_data.timestamp = data.header.timestamp; int binaryLogAcceleration(const unsigned char sensorId, acceleration_t & data) { init_data_struct(acceleration_bin_t, ARDUSAT_SENSOR_TYPE_ACCELERATION) bin_data.x = data.x; bin_data.y = data.y; bin_data.z = data.z; return logBytes((unsigned char *) &bin_data, sizeof(acceleration_bin_t)); } int binaryLogMagnetic(const unsigned char sensorId, magnetic_t & data) { init_data_struct(magnetic_bin_t, ARDUSAT_SENSOR_TYPE_MAGNETIC) bin_data.x = data.x; bin_data.y = data.y; bin_data.z = data.z; return logBytes((unsigned char *) &bin_data, sizeof(magnetic_bin_t)); } int binaryLogGyro(const unsigned char sensorId, gyro_t & data) { init_data_struct(gyro_bin_t, ARDUSAT_SENSOR_TYPE_GYRO) bin_data.x = data.x; bin_data.y = data.y; bin_data.z = data.z; return logBytes((unsigned char *) &bin_data, sizeof(gyro_bin_t)); } int binaryLogTemperature(const unsigned char sensorId, temperature_t & data) { init_data_struct(temperature_bin_t, ARDUSAT_SENSOR_TYPE_TEMPERATURE) bin_data.temp = data.t; return logBytes((unsigned char *) &bin_data, sizeof(temperature_bin_t)); } int binaryLogLuminosity(const unsigned char sensorId, luminosity_t & data) { init_data_struct(luminosity_bin_t, ARDUSAT_SENSOR_TYPE_LUMINOSITY) bin_data.luminosity = data.lux; return logBytes((unsigned char *) &bin_data, sizeof(luminosity_bin_t)); } int binaryLogUVLight(const unsigned char sensorId, uvlight_t & data) { init_data_struct(uv_light_bin_t, ARDUSAT_SENSOR_TYPE_UV) bin_data.uv = data.uvindex; return logBytes((unsigned char *) &bin_data, sizeof(uv_light_bin_t)); } int binaryLogOrientation(const unsigned char sensorId, orientation_t & data) { init_data_struct(orientation_bin_t, ARDUSAT_SENSOR_TYPE_ORIENTATION) bin_data.roll = data.roll; bin_data.pitch = data.pitch; bin_data.heading = data.heading; return logBytes((unsigned char *) &bin_data, sizeof(orientation_bin_t)); } int binaryLogPressure(const unsigned char sensorId, pressure_t & data) { init_data_struct(pressure_bin_t, ARDUSAT_SENSOR_TYPE_PRESSURE) bin_data.pressure = data.pressure; return logBytes((unsigned char *) &bin_data, sizeof(pressure_bin_t)); } /* * Helper function to log to the top of the CSV header with the current time */ int _log_csv_time_header(DateTime & now, unsigned long curr_millis) { char fmt_buf[32]; strcpy_P(fmt_buf, csv_header_fmt); memset(_getOutBuf(), 0, OUTPUT_BUF_SIZE); sprintf(_getOutBuf(), fmt_buf, now.unixtime(), curr_millis); return logString(_getOutBuf()); } int _log_binary_time_header(DateTime & now, unsigned long curr_millis) { unsigned char buf[10]; unsigned long unixtime = now.unixtime(); buf[0] = 0xFF; buf[1] = 0xFF; memcpy(buf + 2, &unixtime, 4); memcpy(buf + 6, &curr_millis, 4); return logBytes(buf, 10); } /** * Function starts the SD card service and makes sure that the appropriate directory * structure exists, then creates the file to use for logging data. Data will be logged * to a file called fileNamePrefix_0.csv or fileNamePrefix_0.bin (number will be incremented * for each new log file) * * @param chipSelectPin Arduino pin SD card reader CS pin is attached to * @param fileNamePrefix string to prefix at beginning of data file * @param csvData boolean flag whether we are writing csv data or binary data (used for filename) * * @return true if successful, false if failed */ bool beginDataLog(int chipSelectPin, const char *fileNamePrefix, bool csvData) { bool ret; int i = 0; int max_len; char fileName[19]; char prefix[8]; char rootPath[] = "/data"; unsigned long curr_millis = 0; DateTime now; if (_output_buffer != NULL) { delete []_output_buffer; } OUTPUT_BUF_SIZE = 512; _output_buffer = vol.cacheAddress()->output_buf; // Try to get the current time from the RTC, if available. This will be prepended to the log file // to be used to convert relative timestamps to real time values. Wire.begin(); RTC.begin(); if (RTC.isrunning()) { now = RTC.now(); curr_millis = millis(); } if (freeMemory() < 400) { strcpy_P(_getOutBuf(), sd_card_error); Serial.print(_getOutBuf()); Serial.print(freeMemory()); Serial.println(", need 400)"); ret = false; } else { ret = sd.begin(chipSelectPin, SPI_FULL_SPEED); } //Filenames need to fit the 8.3 filename convention, so truncate down the //given filename if it is too long. memcpy(prefix, fileNamePrefix, 7); prefix[7] = '\0'; if (ret) { if (!sd.exists(rootPath)) ret = sd.mkdir(rootPath); if (ret) { while (true) { if (i < 10) { max_len = 7; } else if (i < 100) { max_len = 6; } else if (i < 1000) { max_len = 5; } else { break; } prefix[max_len - 1] = '\0'; sprintf(fileName, "%s/%s%d.%s", rootPath, prefix, i, csvData ? "csv" : "bin"); if (!sd.exists(fileName)) { file = sd.open(fileName, FILE_WRITE); break; } i++; } } } else { sd.initErrorPrint(); } if (RTC.isrunning() && file.isOpen()) { if (csvData) { _log_csv_time_header(now, curr_millis); } else { _log_binary_time_header(now, curr_millis); } } return file.isOpen(); } bool setRTC() { Wire.begin(); RTC.begin(); // Sets RTC to the date & time sketch was compiled RTC.adjust(DateTime(__DATE__, __TIME__)); return true; } <|endoftext|>
<commit_before>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cfloat> #include <visionaray/math/math.h> #include <gtest/gtest.h> using namespace visionaray; template <typename T> void test_representability() { //------------------------------------------------------------------------- // isnan // EXPECT_TRUE ( all(isnan(T(NAN))) ); EXPECT_FALSE( any(isnan(T(INFINITY))) ); EXPECT_FALSE( any(isnan(T(0.0))) ); EXPECT_FALSE( any(isnan(T(DBL_MIN / 2.0))) ); EXPECT_TRUE ( all(isnan(T(0.0 / 0.0))) ); EXPECT_TRUE ( all(isnan(T(INFINITY - INFINITY))) ); //------------------------------------------------------------------------- // isinf // EXPECT_FALSE( any(isinf(T(NAN))) ); EXPECT_TRUE ( all(isinf(T(INFINITY))) ); EXPECT_FALSE( any(isinf(T(0.0))) ); EXPECT_TRUE ( all(isinf(T(std::exp(800)))) ); EXPECT_FALSE( any(isinf(T(DBL_MIN / 2.0))) ); //------------------------------------------------------------------------- // isfinite // EXPECT_FALSE( any(isfinite(T(NAN))) ); EXPECT_FALSE( any(isfinite(T(INFINITY))) ); EXPECT_TRUE ( all(isfinite(T(0.0))) ); EXPECT_FALSE( any(isfinite(T(exp(800)))) ); EXPECT_TRUE ( all(isfinite(T(DBL_MIN / 2.0))) ); } static void test_pred_4() { using M = simd::mask4; M z(0,0,0,0); M a(1,1,0,0); M i(1,1,1,1); EXPECT_TRUE(!any(z) ); EXPECT_TRUE(!all(z) ); EXPECT_TRUE( any(a) ); EXPECT_TRUE(!all(a) ); EXPECT_TRUE( any(i) ); EXPECT_TRUE( all(i) ); } #if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX static void test_pred_8() { using M = simd::mask8; M z(0,0,0,0, 0,0,0,0); M a(1,1,0,0, 1,1,0,0); M i(1,1,1,1, 1,1,1,1); EXPECT_TRUE(!any(z) ); EXPECT_TRUE(!all(z) ); EXPECT_TRUE( any(a) ); EXPECT_TRUE(!all(a) ); EXPECT_TRUE( any(i) ); EXPECT_TRUE( all(i) ); } #endif static void test_logical_4() { using M = simd::mask4; M a(1,1,0,0); M b(1,0,1,0); M c(0,0,1,1); EXPECT_TRUE( all((a && b) == M(1,0,0,0)) ); EXPECT_TRUE( all((a && c) == M(0,0,0,0)) ); EXPECT_TRUE( all((a || b) == M(1,1,1,0)) ); EXPECT_TRUE( all((a || c) == M(1,1,1,1)) ); EXPECT_TRUE( any(a && b) ); EXPECT_TRUE(!any(a && c) ); EXPECT_TRUE( any(a || b) ); EXPECT_TRUE( all(a || c) ); EXPECT_TRUE( any(!(a && b)) ); EXPECT_TRUE( all(!(a && c)) ); EXPECT_TRUE( any(!(a || b)) ); EXPECT_TRUE(!any(!(a || c)) ); } #if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX static void test_logical_8() { using M = simd::mask8; M a(1,1,0,0, 1,1,0,0); M b(1,0,1,0, 1,0,1,0); M c(0,0,1,1, 0,0,1,1); EXPECT_TRUE( all((a && b) == M(1,0,0,0, 1,0,0,0)) ); EXPECT_TRUE( all((a && c) == M(0,0,0,0, 0,0,0,0)) ); EXPECT_TRUE( all((a || b) == M(1,1,1,0, 1,1,1,0)) ); EXPECT_TRUE( all((a || c) == M(1,1,1,1, 1,1,1,1)) ); EXPECT_TRUE( any(a && b) ); EXPECT_TRUE(!any(a && c) ); EXPECT_TRUE( any(a || b) ); EXPECT_TRUE( all(a || c) ); EXPECT_TRUE( any(!(a && b)) ); EXPECT_TRUE( all(!(a && c)) ); EXPECT_TRUE( any(!(a || b)) ); EXPECT_TRUE(!any(!(a || c)) ); } #endif //------------------------------------------------------------------------------------------------- // Test isnan(), isinf(), and isfinite() // TEST(SIMD, Representability) { test_representability<simd::float4>(); #if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX test_representability<simd::float8>(); #endif } //------------------------------------------------------------------------------------------------- // Test all() and any() // TEST(SIMD, Pred) { test_pred_4(); #if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX test_pred_8(); #endif } //------------------------------------------------------------------------------------------------- // Test logical operations // TEST(SIMD, Logical) { test_logical_4(); #if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX test_logical_8(); #endif } <commit_msg>Add tests for simd comparisons<commit_after>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cfloat> #include <limits> #include <visionaray/math/math.h> #include <gtest/gtest.h> using namespace visionaray; template <typename T> void test_representability() { //------------------------------------------------------------------------- // isnan // EXPECT_TRUE ( all(isnan(T(NAN))) ); EXPECT_FALSE( any(isnan(T(INFINITY))) ); EXPECT_FALSE( any(isnan(T(0.0))) ); EXPECT_FALSE( any(isnan(T(DBL_MIN / 2.0))) ); EXPECT_TRUE ( all(isnan(T(0.0 / 0.0))) ); EXPECT_TRUE ( all(isnan(T(INFINITY - INFINITY))) ); //------------------------------------------------------------------------- // isinf // EXPECT_FALSE( any(isinf(T(NAN))) ); EXPECT_TRUE ( all(isinf(T(INFINITY))) ); EXPECT_FALSE( any(isinf(T(0.0))) ); EXPECT_TRUE ( all(isinf(T(std::exp(800)))) ); EXPECT_FALSE( any(isinf(T(DBL_MIN / 2.0))) ); //------------------------------------------------------------------------- // isfinite // EXPECT_FALSE( any(isfinite(T(NAN))) ); EXPECT_FALSE( any(isfinite(T(INFINITY))) ); EXPECT_TRUE ( all(isfinite(T(0.0))) ); EXPECT_FALSE( any(isfinite(T(exp(800)))) ); EXPECT_TRUE ( all(isfinite(T(DBL_MIN / 2.0))) ); } static void test_pred_4() { using M = simd::mask4; M z(0,0,0,0); M a(1,1,0,0); M i(1,1,1,1); EXPECT_TRUE(!any(z) ); EXPECT_TRUE(!all(z) ); EXPECT_TRUE( any(a) ); EXPECT_TRUE(!all(a) ); EXPECT_TRUE( any(i) ); EXPECT_TRUE( all(i) ); } #if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX static void test_pred_8() { using M = simd::mask8; M z(0,0,0,0, 0,0,0,0); M a(1,1,0,0, 1,1,0,0); M i(1,1,1,1, 1,1,1,1); EXPECT_TRUE(!any(z) ); EXPECT_TRUE(!all(z) ); EXPECT_TRUE( any(a) ); EXPECT_TRUE(!all(a) ); EXPECT_TRUE( any(i) ); EXPECT_TRUE( all(i) ); } #endif static void test_cmp_4() { using F = simd::float4; using I = simd::int4; using M = simd::mask4; // float { F a(1.0f, 2.0f, 3.0f, 4.0f); F b(5.0f, 6.0f, 7.0f, 8.0f); F c(1.0f, 0.0f, 3.0f, 0.0f); F x(std::numeric_limits<float>::max()); F y(std::numeric_limits<float>::min()); F z(std::numeric_limits<float>::lowest()); EXPECT_TRUE( all(a == a) ); EXPECT_TRUE( all(a != b) ); EXPECT_TRUE( all(a < b) ); EXPECT_TRUE( all(a <= b) ); EXPECT_TRUE( all(b > a) ); EXPECT_TRUE( all(b >= a) ); EXPECT_TRUE( all(c <= a) ); EXPECT_TRUE( all(a >= c) ); EXPECT_TRUE( all((a > c) == M(0,1,0,1)) ); EXPECT_TRUE( all((c < a) == M(0,1,0,1)) ); EXPECT_TRUE( all(x > F(0.0f)) ); EXPECT_TRUE( all(y > F(0.0f)) ); EXPECT_TRUE( all(z < F(0.0f)) ); EXPECT_TRUE( all(x >= F(0.0f)) ); EXPECT_TRUE( all(y >= F(0.0f)) ); EXPECT_TRUE( all(z <= F(0.0f)) ); EXPECT_TRUE( all(y < x) ); EXPECT_TRUE( all(z < y) ); EXPECT_TRUE( all(z < x) ); EXPECT_TRUE( all(y <= x) ); EXPECT_TRUE( all(z <= y) ); EXPECT_TRUE( all(z <= x) ); } // int { I a(1, 2, 3, 4); I b(5, 6, 7, 8); I c(1, 0, 3, 0); I x(std::numeric_limits<int>::max()); I y(std::numeric_limits<int>::min()); EXPECT_TRUE( all(a == a) ); EXPECT_TRUE( all(a != b) ); EXPECT_TRUE( all(a < b) ); EXPECT_TRUE( all(a <= b) ); EXPECT_TRUE( all(b > a) ); EXPECT_TRUE( all(b >= a) ); EXPECT_TRUE( all(c <= a) ); EXPECT_TRUE( all(a >= c) ); EXPECT_TRUE( all((a > c) == M(0,1,0,1)) ); EXPECT_TRUE( all((c < a) == M(0,1,0,1)) ); EXPECT_TRUE( all(x > I(0)) ); EXPECT_TRUE( all(y < I(0)) ); EXPECT_TRUE( all(x >= I(0)) ); EXPECT_TRUE( all(y <= I(0)) ); EXPECT_TRUE( all(y < x) ); EXPECT_TRUE( all(y <= x) ); } // mask { M a(0,0,0,0); M b(1,1,1,1); M c(1,0,1,0); EXPECT_TRUE( all(a == a) ); EXPECT_TRUE( all(a != b) ); EXPECT_TRUE( all((a == c) == M(0,1,0,1)) ); EXPECT_TRUE( all((a != c) == M(1,0,1,0)) ); } } #if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX static void test_cmp_8() { using F = simd::float8; using I = simd::int8; using M = simd::mask8; // float { F a( 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f); F b( 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f); F c( 1.0f, 0.0f, 3.0f, 0.0f, 5.0f, 0.0f, 7.0f, 0.0f); F x(std::numeric_limits<float>::max()); F y(std::numeric_limits<float>::min()); F z(std::numeric_limits<float>::lowest()); EXPECT_TRUE( all(a == a) ); EXPECT_TRUE( all(a != b) ); EXPECT_TRUE( all(a < b) ); EXPECT_TRUE( all(a <= b) ); EXPECT_TRUE( all(b > a) ); EXPECT_TRUE( all(b >= a) ); EXPECT_TRUE( all(c <= a) ); EXPECT_TRUE( all(a >= c) ); EXPECT_TRUE( all((a > c) == M(0,1,0,1, 0,1,0,1)) ); EXPECT_TRUE( all((c < a) == M(0,1,0,1, 0,1,0,1)) ); EXPECT_TRUE( all(x > F(0.0f)) ); EXPECT_TRUE( all(y > F(0.0f)) ); EXPECT_TRUE( all(z < F(0.0f)) ); EXPECT_TRUE( all(x >= F(0.0f)) ); EXPECT_TRUE( all(y >= F(0.0f)) ); EXPECT_TRUE( all(z <= F(0.0f)) ); EXPECT_TRUE( all(y < x) ); EXPECT_TRUE( all(z < y) ); EXPECT_TRUE( all(z < x) ); EXPECT_TRUE( all(y <= x) ); EXPECT_TRUE( all(z <= y) ); EXPECT_TRUE( all(z <= x) ); } // int { I a( 1, 2, 3, 4, 5, 6, 7, 8); I b( 9, 10, 11, 12, 13, 14, 15, 16); I c( 1, 0, 3, 0, 5, 0, 7, 0); I x(std::numeric_limits<int>::max()); I y(std::numeric_limits<int>::min()); EXPECT_TRUE( all(a == a) ); EXPECT_TRUE( all(a != b) ); EXPECT_TRUE( all(a < b) ); EXPECT_TRUE( all(a <= b) ); EXPECT_TRUE( all(b > a) ); EXPECT_TRUE( all(b >= a) ); EXPECT_TRUE( all(c <= a) ); EXPECT_TRUE( all(a >= c) ); EXPECT_TRUE( all((a > c) == M(0,1,0,1, 0,1,0,1)) ); EXPECT_TRUE( all((c < a) == M(0,1,0,1, 0,1,0,1)) ); EXPECT_TRUE( all(x > I(0)) ); EXPECT_TRUE( all(y < I(0)) ); EXPECT_TRUE( all(x >= I(0)) ); EXPECT_TRUE( all(y <= I(0)) ); EXPECT_TRUE( all(y < x) ); EXPECT_TRUE( all(y <= x) ); } // mask { M a(0,0,0,0, 0,0,0,0); M b(1,1,1,1, 1,1,1,1); M c(1,0,1,0, 1,0,1,0); EXPECT_TRUE( all(a == a) ); EXPECT_TRUE( all(a != b) ); EXPECT_TRUE( all((a == c) == M(0,1,0,1, 0,1,0,1)) ); EXPECT_TRUE( all((a != c) == M(1,0,1,0, 1,0,1,0)) ); } } #endif static void test_logical_4() { using M = simd::mask4; M a(1,1,0,0); M b(1,0,1,0); M c(0,0,1,1); EXPECT_TRUE( all((a && b) == M(1,0,0,0)) ); EXPECT_TRUE( all((a && c) == M(0,0,0,0)) ); EXPECT_TRUE( all((a || b) == M(1,1,1,0)) ); EXPECT_TRUE( all((a || c) == M(1,1,1,1)) ); EXPECT_TRUE( any(a && b) ); EXPECT_TRUE(!any(a && c) ); EXPECT_TRUE( any(a || b) ); EXPECT_TRUE( all(a || c) ); EXPECT_TRUE( any(!(a && b)) ); EXPECT_TRUE( all(!(a && c)) ); EXPECT_TRUE( any(!(a || b)) ); EXPECT_TRUE(!any(!(a || c)) ); } #if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX static void test_logical_8() { using M = simd::mask8; M a(1,1,0,0, 1,1,0,0); M b(1,0,1,0, 1,0,1,0); M c(0,0,1,1, 0,0,1,1); EXPECT_TRUE( all((a && b) == M(1,0,0,0, 1,0,0,0)) ); EXPECT_TRUE( all((a && c) == M(0,0,0,0, 0,0,0,0)) ); EXPECT_TRUE( all((a || b) == M(1,1,1,0, 1,1,1,0)) ); EXPECT_TRUE( all((a || c) == M(1,1,1,1, 1,1,1,1)) ); EXPECT_TRUE( any(a && b) ); EXPECT_TRUE(!any(a && c) ); EXPECT_TRUE( any(a || b) ); EXPECT_TRUE( all(a || c) ); EXPECT_TRUE( any(!(a && b)) ); EXPECT_TRUE( all(!(a && c)) ); EXPECT_TRUE( any(!(a || b)) ); EXPECT_TRUE(!any(!(a || c)) ); } #endif //------------------------------------------------------------------------------------------------- // Test isnan(), isinf(), and isfinite() // TEST(SIMD, Representability) { test_representability<simd::float4>(); #if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX test_representability<simd::float8>(); #endif } //------------------------------------------------------------------------------------------------- // Test all() and any() // TEST(SIMD, Pred) { test_pred_4(); #if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX test_pred_8(); #endif } //------------------------------------------------------------------------------------------------- // Test comparisons // TEST(SIMD, Comparison) { test_cmp_4(); #if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX test_cmp_8(); #endif } //------------------------------------------------------------------------------------------------- // Test logical operations // TEST(SIMD, Logical) { test_logical_4(); #if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX test_logical_8(); #endif } <|endoftext|>
<commit_before>/* This file is part of Csound. Copyright (C) 2014 Rory Walsh The Csound Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "OpcodeBase.hpp" #include <algorithm> #include <cmath> #include <dirent.h> #include <iostream> #include <sstream> #include <string> #include <sys/types.h> #include <vector> using namespace std; using namespace csound; /* this function will load all samples of supported types into function tables number 'index' and upwards. It return the number of samples loaded */ int loadSamplesToTables(CSOUND *csound, int index, char *directory, int skiptime, int format, int channel); //----------------------------------------------------------------- // i-rate class //----------------------------------------------------------------- class iftsamplebank : public OpcodeBase<iftsamplebank> { public: // Outputs. MYFLT *numberOfFiles; // Inputs. STRINGDAT *sDirectory; MYFLT *index; // MYFLT* trigger; MYFLT *skiptime; MYFLT *format; MYFLT *channel; iftsamplebank() { channel = 0; index = 0; skiptime = 0; format = 0; index = 0; numberOfFiles = 0; sDirectory = NULL; } // init-pass int init(CSOUND *csound) { *numberOfFiles = loadSamplesToTables( csound, *index, (char *)sDirectory->data, *skiptime, *format, *channel); return OK; } int noteoff(CSOUND *) { return OK; } }; //----------------------------------------------------------------- // k-rate class //----------------------------------------------------------------- class kftsamplebank : public OpcodeBase<kftsamplebank> { public: // Outputs. MYFLT *numberOfFiles; // Inputs. STRINGDAT *sDirectory; MYFLT *index; MYFLT *trigger; MYFLT *skiptime; MYFLT *format; MYFLT *channel; int internalCounter; kftsamplebank() : internalCounter(0) { channel = 0; index = 0; skiptime = 0; format = 0; index = 0; trigger = 0; } // init-pass int init(CSOUND *csound) { IGN(csound); *numberOfFiles = loadSamplesToTables(csound, *index, (char *)sDirectory->data, *skiptime, *format, *channel); *trigger = 0; return OK; } int noteoff(CSOUND *) { return OK; } int kontrol(CSOUND *csound) { // if directry changes update tables.. if (*trigger == 1) { *numberOfFiles = loadSamplesToTables(csound, *index, (char *)sDirectory->data, *skiptime, *format, *channel); *trigger = 0; } return OK; } }; //----------------------------------------------------------------- // load samples into function tables //----------------------------------------------------------------- int loadSamplesToTables(CSOUND *csound, int index, char *directory, int skiptime, int format, int channel) { if (directory) { DIR *dir = opendir(directory); std::vector<std::string> fileNames; std::vector<std::string> fileExtensions; int noOfFiles = 0; fileExtensions.push_back(".wav"); fileExtensions.push_back(".aiff"); fileExtensions.push_back(".ogg"); fileExtensions.push_back(".flac"); // check for valid path first if (dir) { struct dirent *ent; while ((ent = readdir(dir)) != NULL) { std::ostringstream fullFileName; // only use supported file types for (int i = 0; (size_t)i < fileExtensions.size(); i++) { std::string fname = ent->d_name; std::string extension; if(fname.find_last_of(".") != std::string::npos) extension = fname.substr(fname.find_last_of(".")); if(extension == fileExtensions[i]) { if (strlen(directory) > 0) { #if defined(WIN32) fullFileName << directory << "\\" << ent->d_name; #else fullFileName << directory << "/" << ent->d_name; #endif } else fullFileName << ent->d_name; noOfFiles++; fileNames.push_back(fullFileName.str()); } } } // Sort names std::sort(fileNames.begin(), fileNames.end()); // push statements to score, starting with table number 'index' for (int y = 0; (size_t)y < fileNames.size(); y++) { std::ostringstream statement; statement << "f" << index + y << " 0 0 1 \"" << fileNames[y] << "\" " << skiptime << " " << format << " " << channel << "\n"; // csound->MessageS(csound, CSOUNDMSG_ORCH, statement.str().c_str()); csound->InputMessage(csound, statement.str().c_str()); } closedir(dir); } else { csound->Message(csound, Str("Cannot load file. Error opening directory: %s\n"), directory); } // return number of files return noOfFiles; } else return 0; } typedef struct { OPDS h; ARRAYDAT *outArr; STRINGDAT *directoryName; MYFLT *extension; } DIR_STRUCT; /* this function will looks for files of a set type, in a particular directory */ std::vector<std::string> searchDir(CSOUND *csound, char *directory, char *extension); #include "arrays.h" #if 0 /* from Opcodes/arrays.c */ static inline void tabensure(CSOUND *csound, ARRAYDAT *p, int size) { if (p->data==NULL || p->dimensions == 0 || (p->dimensions==1 && p->sizes[0] < size)) { size_t ss; if (p->data == NULL) { CS_VARIABLE* var = p->arrayType->createVariable(csound, NULL); p->arrayMemberSize = var->memBlockSize; } ss = p->arrayMemberSize*size; if (p->data==NULL) { p->data = (MYFLT*)csound->Calloc(csound, ss); p->allocated = ss; } else if (ss > p->allocated) { p->data = (MYFLT*) csound->ReAlloc(csound, p->data, ss); p->allocated = ss; } if (p->dimensions==0) { p->dimensions = 1; p->sizes = (int32_t*)csound->Malloc(csound, sizeof(int32_t)); } } p->sizes[0] = size; } #endif static int directory(CSOUND *csound, DIR_STRUCT *p) { int inArgCount = p->INOCOUNT; char *extension, *file; std::vector<std::string> fileNames; if (inArgCount == 0) return csound->InitError( csound, "%s", Str("Error: you must pass a directory as a string.")); if (inArgCount == 1) { fileNames = searchDir(csound, p->directoryName->data, (char *)""); } else if (inArgCount == 2) { CS_TYPE *argType = csound->GetTypeForArg(p->extension); if (strcmp("S", argType->varTypeName) == 0) { extension = csound->Strdup(csound, ((STRINGDAT *)p->extension)->data); fileNames = searchDir(csound, p->directoryName->data, extension); } else return csound->InitError(csound, "%s", Str("Error: second parameter to directory" " must be a string")); } int numberOfFiles = fileNames.size(); tabinit(csound, p->outArr, numberOfFiles); STRINGDAT *strings = (STRINGDAT *)p->outArr->data; for (int i = 0; i < numberOfFiles; i++) { file = &fileNames[i][0u]; strings[i].size = strlen(file) + 1; strings[i].data = csound->Strdup(csound, file); } fileNames.clear(); return OK; } //----------------------------------------------------------------- // load samples into function tables //----------------------------------------------------------------- std::vector<std::string> searchDir(CSOUND *csound, char *directory, char *extension) { std::vector<std::string> fileNames; if (directory) { DIR *dir = opendir(directory); std::string fileExtension(extension); int noOfFiles = 0; // check for valid path first if (dir) { struct dirent *ent; while ((ent = readdir(dir)) != NULL) { std::ostringstream fullFileName; std::string fname = ent->d_name; size_t lastPos = fname.find_last_of("."); if (fname.length() > 0 && (fileExtension.empty() || (lastPos != std::string::npos && fname.substr(lastPos) == fileExtension))) { if (strlen(directory) > 0) { #if defined(WIN32) fullFileName << directory << "\\" << ent->d_name; #else fullFileName << directory << "/" << ent->d_name; #endif } else fullFileName << ent->d_name; noOfFiles++; fileNames.push_back(fullFileName.str()); } } // Sort names std::sort(fileNames.begin(), fileNames.end()); } else { csound->Message(csound, Str("Cannot find directory. " "Error opening directory: %s\n"), directory); } closedir(dir); } return fileNames; } extern "C" { PUBLIC int csoundModuleInit_ftsamplebank(CSOUND *csound) { int status = csound->AppendOpcode( csound, (char *)"ftsamplebank.k", sizeof(kftsamplebank), 0, 3, (char *)"k", (char *)"Skkkkk", (int (*)(CSOUND *, void *))kftsamplebank::init_, (int (*)(CSOUND *, void *))kftsamplebank::kontrol_, (int (*)(CSOUND *, void *))0); status |= csound->AppendOpcode( csound, (char *)"ftsamplebank.i", sizeof(iftsamplebank), 0, 1, (char *)"i", (char *)"Siiii", (int (*)(CSOUND *, void *))iftsamplebank::init_, (int (*)(CSOUND *, void *))0, (int (*)(CSOUND *, void *))0); /* status |= csound->AppendOpcode(csound, (char*)"ftsamplebank", 0xffff, 0, 0, 0, 0, 0, 0, 0); */ status |= csound->AppendOpcode( csound, (char *)"directory", sizeof(DIR_STRUCT), 0, 1, (char *)"S[]", (char *)"SN", (int (*)(CSOUND *, void *))directory, (int (*)(CSOUND *, void *))0, (int (*)(CSOUND *, void *))0); return status; } #ifndef INIT_STATIC_MODULES PUBLIC int csoundModuleCreate(CSOUND *csound) { IGN(csound); return 0; } PUBLIC int csoundModuleInit(CSOUND *csound) { return csoundModuleInit_ftsamplebank(csound); } PUBLIC int csoundModuleDestroy(CSOUND *csound) { IGN(csound); return 0; } #endif } <commit_msg>Missed one for _CR workaround.<commit_after>/* This file is part of Csound. Copyright (C) 2014 Rory Walsh The Csound Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <algorithm> #include <cmath> #include <iostream> #include <sstream> #include <string> #include <vector> #include "OpcodeBase.hpp" #include <dirent.h> #include <sys/types.h> using namespace std; using namespace csound; /* this function will load all samples of supported types into function tables number 'index' and upwards. It return the number of samples loaded */ int loadSamplesToTables(CSOUND *csound, int index, char *directory, int skiptime, int format, int channel); //----------------------------------------------------------------- // i-rate class //----------------------------------------------------------------- class iftsamplebank : public OpcodeBase<iftsamplebank> { public: // Outputs. MYFLT *numberOfFiles; // Inputs. STRINGDAT *sDirectory; MYFLT *index; // MYFLT* trigger; MYFLT *skiptime; MYFLT *format; MYFLT *channel; iftsamplebank() { channel = 0; index = 0; skiptime = 0; format = 0; index = 0; numberOfFiles = 0; sDirectory = NULL; } // init-pass int init(CSOUND *csound) { *numberOfFiles = loadSamplesToTables( csound, *index, (char *)sDirectory->data, *skiptime, *format, *channel); return OK; } int noteoff(CSOUND *) { return OK; } }; //----------------------------------------------------------------- // k-rate class //----------------------------------------------------------------- class kftsamplebank : public OpcodeBase<kftsamplebank> { public: // Outputs. MYFLT *numberOfFiles; // Inputs. STRINGDAT *sDirectory; MYFLT *index; MYFLT *trigger; MYFLT *skiptime; MYFLT *format; MYFLT *channel; int internalCounter; kftsamplebank() : internalCounter(0) { channel = 0; index = 0; skiptime = 0; format = 0; index = 0; trigger = 0; } // init-pass int init(CSOUND *csound) { IGN(csound); *numberOfFiles = loadSamplesToTables(csound, *index, (char *)sDirectory->data, *skiptime, *format, *channel); *trigger = 0; return OK; } int noteoff(CSOUND *) { return OK; } int kontrol(CSOUND *csound) { // if directry changes update tables.. if (*trigger == 1) { *numberOfFiles = loadSamplesToTables(csound, *index, (char *)sDirectory->data, *skiptime, *format, *channel); *trigger = 0; } return OK; } }; //----------------------------------------------------------------- // load samples into function tables //----------------------------------------------------------------- int loadSamplesToTables(CSOUND *csound, int index, char *directory, int skiptime, int format, int channel) { if (directory) { DIR *dir = opendir(directory); std::vector<std::string> fileNames; std::vector<std::string> fileExtensions; int noOfFiles = 0; fileExtensions.push_back(".wav"); fileExtensions.push_back(".aiff"); fileExtensions.push_back(".ogg"); fileExtensions.push_back(".flac"); // check for valid path first if (dir) { struct dirent *ent; while ((ent = readdir(dir)) != NULL) { std::ostringstream fullFileName; // only use supported file types for (int i = 0; (size_t)i < fileExtensions.size(); i++) { std::string fname = ent->d_name; std::string extension; if(fname.find_last_of(".") != std::string::npos) extension = fname.substr(fname.find_last_of(".")); if(extension == fileExtensions[i]) { if (strlen(directory) > 0) { #if defined(WIN32) fullFileName << directory << "\\" << ent->d_name; #else fullFileName << directory << "/" << ent->d_name; #endif } else fullFileName << ent->d_name; noOfFiles++; fileNames.push_back(fullFileName.str()); } } } // Sort names std::sort(fileNames.begin(), fileNames.end()); // push statements to score, starting with table number 'index' for (int y = 0; (size_t)y < fileNames.size(); y++) { std::ostringstream statement; statement << "f" << index + y << " 0 0 1 \"" << fileNames[y] << "\" " << skiptime << " " << format << " " << channel << "\n"; // csound->MessageS(csound, CSOUNDMSG_ORCH, statement.str().c_str()); csound->InputMessage(csound, statement.str().c_str()); } closedir(dir); } else { csound->Message(csound, Str("Cannot load file. Error opening directory: %s\n"), directory); } // return number of files return noOfFiles; } else return 0; } typedef struct { OPDS h; ARRAYDAT *outArr; STRINGDAT *directoryName; MYFLT *extension; } DIR_STRUCT; /* this function will looks for files of a set type, in a particular directory */ std::vector<std::string> searchDir(CSOUND *csound, char *directory, char *extension); #include "arrays.h" #if 0 /* from Opcodes/arrays.c */ static inline void tabensure(CSOUND *csound, ARRAYDAT *p, int size) { if (p->data==NULL || p->dimensions == 0 || (p->dimensions==1 && p->sizes[0] < size)) { size_t ss; if (p->data == NULL) { CS_VARIABLE* var = p->arrayType->createVariable(csound, NULL); p->arrayMemberSize = var->memBlockSize; } ss = p->arrayMemberSize*size; if (p->data==NULL) { p->data = (MYFLT*)csound->Calloc(csound, ss); p->allocated = ss; } else if (ss > p->allocated) { p->data = (MYFLT*) csound->ReAlloc(csound, p->data, ss); p->allocated = ss; } if (p->dimensions==0) { p->dimensions = 1; p->sizes = (int32_t*)csound->Malloc(csound, sizeof(int32_t)); } } p->sizes[0] = size; } #endif static int directory(CSOUND *csound, DIR_STRUCT *p) { int inArgCount = p->INOCOUNT; char *extension, *file; std::vector<std::string> fileNames; if (inArgCount == 0) return csound->InitError( csound, "%s", Str("Error: you must pass a directory as a string.")); if (inArgCount == 1) { fileNames = searchDir(csound, p->directoryName->data, (char *)""); } else if (inArgCount == 2) { CS_TYPE *argType = csound->GetTypeForArg(p->extension); if (strcmp("S", argType->varTypeName) == 0) { extension = csound->Strdup(csound, ((STRINGDAT *)p->extension)->data); fileNames = searchDir(csound, p->directoryName->data, extension); } else return csound->InitError(csound, "%s", Str("Error: second parameter to directory" " must be a string")); } int numberOfFiles = fileNames.size(); tabinit(csound, p->outArr, numberOfFiles); STRINGDAT *strings = (STRINGDAT *)p->outArr->data; for (int i = 0; i < numberOfFiles; i++) { file = &fileNames[i][0u]; strings[i].size = strlen(file) + 1; strings[i].data = csound->Strdup(csound, file); } fileNames.clear(); return OK; } //----------------------------------------------------------------- // load samples into function tables //----------------------------------------------------------------- std::vector<std::string> searchDir(CSOUND *csound, char *directory, char *extension) { std::vector<std::string> fileNames; if (directory) { DIR *dir = opendir(directory); std::string fileExtension(extension); int noOfFiles = 0; // check for valid path first if (dir) { struct dirent *ent; while ((ent = readdir(dir)) != NULL) { std::ostringstream fullFileName; std::string fname = ent->d_name; size_t lastPos = fname.find_last_of("."); if (fname.length() > 0 && (fileExtension.empty() || (lastPos != std::string::npos && fname.substr(lastPos) == fileExtension))) { if (strlen(directory) > 0) { #if defined(WIN32) fullFileName << directory << "\\" << ent->d_name; #else fullFileName << directory << "/" << ent->d_name; #endif } else fullFileName << ent->d_name; noOfFiles++; fileNames.push_back(fullFileName.str()); } } // Sort names std::sort(fileNames.begin(), fileNames.end()); } else { csound->Message(csound, Str("Cannot find directory. " "Error opening directory: %s\n"), directory); } closedir(dir); } return fileNames; } extern "C" { PUBLIC int csoundModuleInit_ftsamplebank(CSOUND *csound) { int status = csound->AppendOpcode( csound, (char *)"ftsamplebank.k", sizeof(kftsamplebank), 0, 3, (char *)"k", (char *)"Skkkkk", (int (*)(CSOUND *, void *))kftsamplebank::init_, (int (*)(CSOUND *, void *))kftsamplebank::kontrol_, (int (*)(CSOUND *, void *))0); status |= csound->AppendOpcode( csound, (char *)"ftsamplebank.i", sizeof(iftsamplebank), 0, 1, (char *)"i", (char *)"Siiii", (int (*)(CSOUND *, void *))iftsamplebank::init_, (int (*)(CSOUND *, void *))0, (int (*)(CSOUND *, void *))0); /* status |= csound->AppendOpcode(csound, (char*)"ftsamplebank", 0xffff, 0, 0, 0, 0, 0, 0, 0); */ status |= csound->AppendOpcode( csound, (char *)"directory", sizeof(DIR_STRUCT), 0, 1, (char *)"S[]", (char *)"SN", (int (*)(CSOUND *, void *))directory, (int (*)(CSOUND *, void *))0, (int (*)(CSOUND *, void *))0); return status; } #ifndef INIT_STATIC_MODULES PUBLIC int csoundModuleCreate(CSOUND *csound) { IGN(csound); return 0; } PUBLIC int csoundModuleInit(CSOUND *csound) { return csoundModuleInit_ftsamplebank(csound); } PUBLIC int csoundModuleDestroy(CSOUND *csound) { IGN(csound); return 0; } #endif } <|endoftext|>
<commit_before>#include "oglWidget.h" #include <iostream> // // CONSTRUCTORS //////////////////////////////////////////////////////////////// // /** * @brief Default constructor for OGLWidget. */ OGLWidget::OGLWidget() { // Update the widget after a frameswap connect( this, SIGNAL( frameSwapped() ), this, SLOT( update() ) ); // Allows keyboard input to fall through setFocusPolicy( Qt::ClickFocus ); // Default camera view camera.rotate( -40.0f, 1.0f, 0.0f, 0.0f ); camera.rotate( 90.0f, 0.0f, 1.0f, 0.0f ); camera.translate( 55.8f, 56.7f, 1.74f ); renderables["Table"] = new HockeyTable(); renderables["Puck"] = new HockeyPuck(); renderables["Paddle"] = new HockeyPaddle( "Red" ); renderables["Paddle2"] = new HockeyPaddle( "Blue" ); renderables["Skybox"] = new Skybox(); const btVector3 goalSize = btVector3(0.5,50,4.5); btVector3 stublocation = btVector3(0.0, 0.0, 0.0); walls["Goal"] = new Wall(goalSize, stublocation); walls["Goal2"] = new Wall(goalSize, stublocation); // invisible wall in the middle is offset just a little bit to be in table's center walls["Middle"] = new Wall(btVector3(0.5,50,20), btVector3(1,0,0)); } /** * @brief Destructor class to unallocate OpenGL information. */ OGLWidget::~OGLWidget() { makeCurrent(); teardownGL(); teardownBullet(); } // // OPENGL FUNCTIONS //////////////////////////////////////////////////////////// // /** * @brief Initializes any OpenGL operations. */ void OGLWidget::initializeGL() { // Init OpenGL Backend initializeOpenGLFunctions(); printContextInfo(); initializeBullet(); for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); iter != renderables.end(); iter++ ) { (*iter)->initializeGL(); } // renderables m_dynamicsWorld->addRigidBody( ((HockeyTable*)renderables["Table"])->RigidBody, COL_TABLE, m_TableCollidesWith ); m_dynamicsWorld->addRigidBody( ((HockeyPuck*)renderables["Puck"])->RigidBody, COL_PUCK, m_PuckCollidesWith ); m_dynamicsWorld->addRigidBody( ((HockeyPaddle*)renderables["Paddle"])->RigidBody, COL_PADDLE, m_PaddleCollidesWith ); m_dynamicsWorld->addRigidBody( ((HockeyPaddle*)renderables["Paddle2"])->RigidBody, COL_PADDLE, m_PaddleCollidesWith ); // walls m_dynamicsWorld->addRigidBody( walls["Goal"]->RigidBody, COL_GOAL, m_GoalCollidesWith ); m_dynamicsWorld->addRigidBody( walls["Goal2"]->RigidBody, COL_GOAL, m_GoalCollidesWith ); m_dynamicsWorld->addRigidBody( walls["Middle"]->RigidBody, COL_MIDDLE, m_MiddleCollidesWith ); } /** * @brief Sets the prespective whenever the window is resized. * * @param[in] width The width of the new window. * @param[in] height The height of the new window. */ void OGLWidget::resizeGL( int width, int height ) { projection.setToIdentity(); projection.perspective( 55.0f, // Field of view angle float( width ) / float( height ), // Aspect Ratio 0.001f, // Near Plane (MUST BE GREATER THAN 0) 1500.0f ); // Far Plane } /** * @brief OpenGL function to draw elements to the surface. */ void OGLWidget::paintGL() { // Set the default OpenGL states glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LEQUAL ); glDepthMask( GL_TRUE ); glEnable( GL_CULL_FACE ); glClearColor( 0.0f, 0.0f, 0.2f, 1.0f ); // Clear the screen glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); iter != renderables.end(); iter++ ) { (*iter)->paintGL( camera, projection ); } // 2D Elements QFont NHLFont( "NHL", 47 ); QFont ConsolasFont( "Consolas", 35, QFont::Bold ); // Draw 2D Elements QPainter painter(this); QRect rect( 0, 10, QWidget::width(), QWidget::height() / 4 ); painter.beginNativePainting(); painter.setPen( QColor( 255, 255, 255, 255 ) ); painter.setFont( ConsolasFont ); painter.drawText( rect, Qt::AlignHCenter, "0 - 0" ); painter.setFont( NHLFont ); painter.setPen( QColor( 255, 0, 0, 255 ) ); painter.drawText( rect, Qt::AlignLeft, "\t\t\t\td" ); painter.setPen( QColor( 0, 0, 255, 255 ) ); painter.drawText( rect, Qt::AlignRight, "e\t\t\t\t" ); painter.endNativePainting(); } /** * @brief Destroys any OpenGL data. */ void OGLWidget::teardownGL() { for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); iter != renderables.end(); iter++ ) { (*iter)->teardownGL(); } } // // SLOTS /////////////////////////////////////////////////////////////////////// // /** * @brief Updates any user interactions and model transformations. */ void OGLWidget::update() { Input::update(); flyThroughCamera(); btVector3 linearVelocity(0,0,0); if( Input::keyPressed( Qt::Key_Up ) ) { linearVelocity[0] = -5; } else if( Input::keyPressed( Qt::Key_Down ) ){ linearVelocity[0] = 5; } if( Input::keyPressed( Qt::Key_Left ) ){ linearVelocity[2] = 5; } else if( Input::keyPressed( Qt::Key_Right ) ) { linearVelocity[2] = -5; } ((HockeyPaddle*)renderables["Paddle2"])->RigidBody->setLinearVelocity( linearVelocity ); for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); iter != renderables.end(); iter++ ) { (*iter)->update(); } m_dynamicsWorld->stepSimulation( 1, 10 ); QOpenGLWidget::update(); } // // INPUT EVENTS //////////////////////////////////////////////////////////////// // /** * @brief Default slot for handling key press events. * * @param event The key event information. */ void OGLWidget::keyPressEvent( QKeyEvent* event ) { if( event->isAutoRepeat() ) event->ignore(); else Input::registerKeyPress( event->key() ); } /** * @brief Default slot for handling key release events. * * @param event The key event information. */ void OGLWidget::keyReleaseEvent( QKeyEvent* event ) { if( event->isAutoRepeat() ) event->ignore(); else Input::registerKeyRelease( event->key() ); } /** * @brief Default slot for handling mouse press events. * * @param event The mouse event information. */ void OGLWidget::mousePressEvent( QMouseEvent* event ) { Input::registerMousePress( event->button() ); } /** * @brief Default slot for handling mouse release events. * * @param event The mouse event information. */ void OGLWidget::mouseReleaseEvent( QMouseEvent* event ) { Input::registerMouseRelease( event->button() ); } // // PRIVATE HELPER FUNCTIONS //////////////////////////////////////////////////// // void OGLWidget::initializeBullet() { m_broadphase = new btDbvtBroadphase(); m_collisionConfig = new btDefaultCollisionConfiguration(); m_dispatcher = new btCollisionDispatcher( m_collisionConfig ); m_solver = new btSequentialImpulseConstraintSolver(); m_dynamicsWorld = new btDiscreteDynamicsWorld( m_dispatcher, m_broadphase, m_solver, m_collisionConfig ); m_dynamicsWorld->setGravity( btVector3( 0, -9.8, 0 ) ); } void OGLWidget::teardownBullet() { delete m_dynamicsWorld; delete m_solver; delete m_dispatcher; delete m_collisionConfig; delete m_broadphase; } /** * @brief Updates the main camera to behave like a Fly-Through Camera. */ void OGLWidget::flyThroughCamera() { static const float cameraTranslationSpeed = 0.03f; static const float cameraRotationSpeed = 0.2f; if( Input::buttonPressed( Qt::RightButton ) ) { // Rotate the camera based on mouse movement camera.rotate( -cameraRotationSpeed * Input::mouseDelta().x(), Camera3D::LocalUp ); camera.rotate( -cameraRotationSpeed * Input::mouseDelta().y(), camera.right() ); } // Translate the camera based on keyboard input QVector3D cameraTranslations; if( Input::keyPressed( Qt::Key_W ) ) cameraTranslations += camera.forward(); if( Input::keyPressed( Qt::Key_S ) ) cameraTranslations -= camera.forward(); if( Input::keyPressed( Qt::Key_A ) ) cameraTranslations -= camera.right(); if( Input::keyPressed( Qt::Key_D ) ) cameraTranslations += camera.right(); if( Input::keyPressed( Qt::Key_Q ) ) cameraTranslations -= camera.up(); if( Input::keyPressed( Qt::Key_E ) ) cameraTranslations += camera.up(); camera.translate( cameraTranslationSpeed * cameraTranslations ); } /** * @brief Helper function to print OpenGL Context information to the debug. */ void OGLWidget::printContextInfo() { QString glType; QString glVersion; QString glProfile; // Get Version Information glType = ( context()->isOpenGLES() ) ? "OpenGL ES" : "OpenGL"; glVersion = reinterpret_cast<const char*>( glGetString( GL_VERSION ) ); // Get Profile Information switch( format().profile() ) { case QSurfaceFormat::NoProfile: glProfile = "No Profile"; break; case QSurfaceFormat::CoreProfile: glProfile = "Core Profile"; break; case QSurfaceFormat::CompatibilityProfile: glProfile = "Compatibility Profile"; break; } qDebug() << qPrintable( glType ) << qPrintable( glVersion ) << "(" << qPrintable( glProfile ) << ")"; }<commit_msg>Goal walls in correct locations<commit_after>#include "oglWidget.h" // #include <iostream> // for debug // // CONSTRUCTORS //////////////////////////////////////////////////////////////// // /** * @brief Default constructor for OGLWidget. */ OGLWidget::OGLWidget() { // Update the widget after a frameswap connect( this, SIGNAL( frameSwapped() ), this, SLOT( update() ) ); // Allows keyboard input to fall through setFocusPolicy( Qt::ClickFocus ); // Default camera view camera.rotate( -40.0f, 1.0f, 0.0f, 0.0f ); camera.rotate( 90.0f, 0.0f, 1.0f, 0.0f ); camera.translate( 55.8f, 56.7f, 1.74f ); renderables["Table"] = new HockeyTable(); renderables["Puck"] = new HockeyPuck(); renderables["Paddle"] = new HockeyPaddle( "Red" ); renderables["Paddle2"] = new HockeyPaddle( "Blue" ); renderables["Skybox"] = new Skybox(); // Note: Actual height of the table is around 30.5 // So all of these walls are underneath the table but are really tall const btVector3 goalSize = btVector3(0.5,35,4.5); // red goal walls["Goal"] = new Wall(goalSize, btVector3(-30.5, 0, 1)); // blue goal walls["Goal2"] = new Wall(goalSize, btVector3( 33.5, 0, 1)); // invisible wall in the middle is offset just a little bit to be in table's center walls["Middle"] = new Wall(btVector3(0.5,35,20), btVector3(1,0,0)); } /** * @brief Destructor class to unallocate OpenGL information. */ OGLWidget::~OGLWidget() { makeCurrent(); teardownGL(); teardownBullet(); } // // OPENGL FUNCTIONS //////////////////////////////////////////////////////////// // /** * @brief Initializes any OpenGL operations. */ void OGLWidget::initializeGL() { // Init OpenGL Backend initializeOpenGLFunctions(); printContextInfo(); initializeBullet(); for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); iter != renderables.end(); iter++ ) { (*iter)->initializeGL(); } // renderables m_dynamicsWorld->addRigidBody( ((HockeyTable*)renderables["Table"])->RigidBody, COL_TABLE, m_TableCollidesWith ); m_dynamicsWorld->addRigidBody( ((HockeyPuck*)renderables["Puck"])->RigidBody, COL_PUCK, m_PuckCollidesWith ); m_dynamicsWorld->addRigidBody( ((HockeyPaddle*)renderables["Paddle"])->RigidBody, COL_PADDLE, m_PaddleCollidesWith ); m_dynamicsWorld->addRigidBody( ((HockeyPaddle*)renderables["Paddle2"])->RigidBody, COL_PADDLE, m_PaddleCollidesWith ); // walls m_dynamicsWorld->addRigidBody( walls["Goal"]->RigidBody, COL_GOAL, m_GoalCollidesWith ); m_dynamicsWorld->addRigidBody( walls["Goal2"]->RigidBody, COL_GOAL, m_GoalCollidesWith ); m_dynamicsWorld->addRigidBody( walls["Middle"]->RigidBody, COL_MIDDLE, m_MiddleCollidesWith ); } /** * @brief Sets the prespective whenever the window is resized. * * @param[in] width The width of the new window. * @param[in] height The height of the new window. */ void OGLWidget::resizeGL( int width, int height ) { projection.setToIdentity(); projection.perspective( 55.0f, // Field of view angle float( width ) / float( height ), // Aspect Ratio 0.001f, // Near Plane (MUST BE GREATER THAN 0) 1500.0f ); // Far Plane } /** * @brief OpenGL function to draw elements to the surface. */ void OGLWidget::paintGL() { // Set the default OpenGL states glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LEQUAL ); glDepthMask( GL_TRUE ); glEnable( GL_CULL_FACE ); glClearColor( 0.0f, 0.0f, 0.2f, 1.0f ); // Clear the screen glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); iter != renderables.end(); iter++ ) { (*iter)->paintGL( camera, projection ); } // 2D Elements QFont NHLFont( "NHL", 47 ); QFont ConsolasFont( "Consolas", 35, QFont::Bold ); // Draw 2D Elements QPainter painter(this); QRect rect( 0, 10, QWidget::width(), QWidget::height() / 4 ); painter.beginNativePainting(); painter.setPen( QColor( 255, 255, 255, 255 ) ); painter.setFont( ConsolasFont ); painter.drawText( rect, Qt::AlignHCenter, "0 - 0" ); painter.setFont( NHLFont ); painter.setPen( QColor( 255, 0, 0, 255 ) ); painter.drawText( rect, Qt::AlignLeft, "\t\t\t\td" ); painter.setPen( QColor( 0, 0, 255, 255 ) ); painter.drawText( rect, Qt::AlignRight, "e\t\t\t\t" ); painter.endNativePainting(); } /** * @brief Destroys any OpenGL data. */ void OGLWidget::teardownGL() { for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); iter != renderables.end(); iter++ ) { (*iter)->teardownGL(); } } // // SLOTS /////////////////////////////////////////////////////////////////////// // /** * @brief Updates any user interactions and model transformations. */ void OGLWidget::update() { Input::update(); flyThroughCamera(); btVector3 linearVelocity(0,0,0); if( Input::keyPressed( Qt::Key_Up ) ) { linearVelocity[0] = -5; } else if( Input::keyPressed( Qt::Key_Down ) ){ linearVelocity[0] = 5; } if( Input::keyPressed( Qt::Key_Left ) ){ linearVelocity[2] = 5; } else if( Input::keyPressed( Qt::Key_Right ) ) { linearVelocity[2] = -5; } ((HockeyPaddle*)renderables["Paddle2"])->RigidBody->setLinearVelocity( linearVelocity ); for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); iter != renderables.end(); iter++ ) { (*iter)->update(); } m_dynamicsWorld->stepSimulation( 1, 10 ); QOpenGLWidget::update(); } // // INPUT EVENTS //////////////////////////////////////////////////////////////// // /** * @brief Default slot for handling key press events. * * @param event The key event information. */ void OGLWidget::keyPressEvent( QKeyEvent* event ) { if( event->isAutoRepeat() ) event->ignore(); else Input::registerKeyPress( event->key() ); } /** * @brief Default slot for handling key release events. * * @param event The key event information. */ void OGLWidget::keyReleaseEvent( QKeyEvent* event ) { if( event->isAutoRepeat() ) event->ignore(); else Input::registerKeyRelease( event->key() ); } /** * @brief Default slot for handling mouse press events. * * @param event The mouse event information. */ void OGLWidget::mousePressEvent( QMouseEvent* event ) { Input::registerMousePress( event->button() ); } /** * @brief Default slot for handling mouse release events. * * @param event The mouse event information. */ void OGLWidget::mouseReleaseEvent( QMouseEvent* event ) { Input::registerMouseRelease( event->button() ); } // // PRIVATE HELPER FUNCTIONS //////////////////////////////////////////////////// // void OGLWidget::initializeBullet() { m_broadphase = new btDbvtBroadphase(); m_collisionConfig = new btDefaultCollisionConfiguration(); m_dispatcher = new btCollisionDispatcher( m_collisionConfig ); m_solver = new btSequentialImpulseConstraintSolver(); m_dynamicsWorld = new btDiscreteDynamicsWorld( m_dispatcher, m_broadphase, m_solver, m_collisionConfig ); m_dynamicsWorld->setGravity( btVector3( 0, -9.8, 0 ) ); } void OGLWidget::teardownBullet() { delete m_dynamicsWorld; delete m_solver; delete m_dispatcher; delete m_collisionConfig; delete m_broadphase; } /** * @brief Updates the main camera to behave like a Fly-Through Camera. */ void OGLWidget::flyThroughCamera() { static const float cameraTranslationSpeed = 0.03f; static const float cameraRotationSpeed = 0.2f; if( Input::buttonPressed( Qt::RightButton ) ) { // Rotate the camera based on mouse movement camera.rotate( -cameraRotationSpeed * Input::mouseDelta().x(), Camera3D::LocalUp ); camera.rotate( -cameraRotationSpeed * Input::mouseDelta().y(), camera.right() ); } // Translate the camera based on keyboard input QVector3D cameraTranslations; if( Input::keyPressed( Qt::Key_W ) ) cameraTranslations += camera.forward(); if( Input::keyPressed( Qt::Key_S ) ) cameraTranslations -= camera.forward(); if( Input::keyPressed( Qt::Key_A ) ) cameraTranslations -= camera.right(); if( Input::keyPressed( Qt::Key_D ) ) cameraTranslations += camera.right(); if( Input::keyPressed( Qt::Key_Q ) ) cameraTranslations -= camera.up(); if( Input::keyPressed( Qt::Key_E ) ) cameraTranslations += camera.up(); camera.translate( cameraTranslationSpeed * cameraTranslations ); /* Insanely useful for debugging std::cout << camera.translation().x() << ' ' << camera.translation().y() << ' ' << camera.translation().z() << std::endl; */ } /** * @brief Helper function to print OpenGL Context information to the debug. */ void OGLWidget::printContextInfo() { QString glType; QString glVersion; QString glProfile; // Get Version Information glType = ( context()->isOpenGLES() ) ? "OpenGL ES" : "OpenGL"; glVersion = reinterpret_cast<const char*>( glGetString( GL_VERSION ) ); // Get Profile Information switch( format().profile() ) { case QSurfaceFormat::NoProfile: glProfile = "No Profile"; break; case QSurfaceFormat::CoreProfile: glProfile = "Core Profile"; break; case QSurfaceFormat::CompatibilityProfile: glProfile = "Compatibility Profile"; break; } qDebug() << qPrintable( glType ) << qPrintable( glVersion ) << "(" << qPrintable( glProfile ) << ")"; }<|endoftext|>