text
stringlengths
54
60.6k
<commit_before>d3cc5ae1-2e4e-11e5-a405-28cfe91dbc4b<commit_msg>d3d1bfd1-2e4e-11e5-bae2-28cfe91dbc4b<commit_after>d3d1bfd1-2e4e-11e5-bae2-28cfe91dbc4b<|endoftext|>
<commit_before>1f75cda6-585b-11e5-bd2d-6c40088e03e4<commit_msg>1f7d1d10-585b-11e5-a7d9-6c40088e03e4<commit_after>1f7d1d10-585b-11e5-a7d9-6c40088e03e4<|endoftext|>
<commit_before>3e057e3d-2e4f-11e5-8cae-28cfe91dbc4b<commit_msg>3e0e1940-2e4f-11e5-bf8b-28cfe91dbc4b<commit_after>3e0e1940-2e4f-11e5-bf8b-28cfe91dbc4b<|endoftext|>
<commit_before>6515e034-2fa5-11e5-a3fe-00012e3d3f12<commit_msg>6517dc06-2fa5-11e5-8d5b-00012e3d3f12<commit_after>6517dc06-2fa5-11e5-8d5b-00012e3d3f12<|endoftext|>
<commit_before>a25966ee-327f-11e5-afbd-9cf387a8033e<commit_msg>a25fb582-327f-11e5-b771-9cf387a8033e<commit_after>a25fb582-327f-11e5-b771-9cf387a8033e<|endoftext|>
<commit_before>ec7a2647-313a-11e5-95b5-3c15c2e10482<commit_msg>ec801e54-313a-11e5-9f5b-3c15c2e10482<commit_after>ec801e54-313a-11e5-9f5b-3c15c2e10482<|endoftext|>
<commit_before>8562794a-2d15-11e5-af21-0401358ea401<commit_msg>8562794b-2d15-11e5-af21-0401358ea401<commit_after>8562794b-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>06bdbfc0-2f67-11e5-a409-6c40088e03e4<commit_msg>06c42b9e-2f67-11e5-9711-6c40088e03e4<commit_after>06c42b9e-2f67-11e5-9711-6c40088e03e4<|endoftext|>
<commit_before>92b1011a-35ca-11e5-866d-6c40088e03e4<commit_msg>92b7a81c-35ca-11e5-af14-6c40088e03e4<commit_after>92b7a81c-35ca-11e5-af14-6c40088e03e4<|endoftext|>
<commit_before>6627c33a-5216-11e5-aed8-6c40088e03e4<commit_msg>662f9cba-5216-11e5-b8b9-6c40088e03e4<commit_after>662f9cba-5216-11e5-b8b9-6c40088e03e4<|endoftext|>
<commit_before>aaf18b3d-2e4f-11e5-aebe-28cfe91dbc4b<commit_msg>aaf84a11-2e4f-11e5-8faa-28cfe91dbc4b<commit_after>aaf84a11-2e4f-11e5-8faa-28cfe91dbc4b<|endoftext|>
<commit_before>16d8b3ec-585b-11e5-bbfa-6c40088e03e4<commit_msg>16e0c710-585b-11e5-8dee-6c40088e03e4<commit_after>16e0c710-585b-11e5-8dee-6c40088e03e4<|endoftext|>
<commit_before>d26d0180-313a-11e5-9397-3c15c2e10482<commit_msg>d27309f5-313a-11e5-b0c4-3c15c2e10482<commit_after>d27309f5-313a-11e5-b0c4-3c15c2e10482<|endoftext|>
<commit_before>16f44858-585b-11e5-b649-6c40088e03e4<commit_msg>16faac52-585b-11e5-a25b-6c40088e03e4<commit_after>16faac52-585b-11e5-a25b-6c40088e03e4<|endoftext|>
<commit_before>c2b5d62e-35ca-11e5-b5ae-6c40088e03e4<commit_msg>c2bbd808-35ca-11e5-b3bc-6c40088e03e4<commit_after>c2bbd808-35ca-11e5-b3bc-6c40088e03e4<|endoftext|>
<commit_before>bf35a623-2747-11e6-8a55-e0f84713e7b8<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>bf4a4e68-2747-11e6-a5bd-e0f84713e7b8<|endoftext|>
<commit_before>/* * Menu * * Copyright (C)2016 Laurentiu Badea * * This file may be redistributed under the terms of the MIT license. * A copy of this license has been included with this distribution in the file LICENSE. */ #include "menu.h" #define BLACK 0 #define WHITE 1 #define INVERSE 2 /* * OptionSelector: share functionality among the other menu classes */ OptionSelector::OptionSelector(const char *description, volatile int *value, int default_val) :description(description), value(value), default_val(default_val) { active = false; pos = default_val; if (value){ *value = default_val; } } int OptionSelector::render(DISPLAY_DEVICE display, int rows){ Serial.println(FLASH_STRING description); Serial.println("---------------------"); display.println(FLASH_STRING description); rows--; if (rows > 4){ display.print("---------------------"); rows--; } return rows; } void OptionSelector::cancel(void){ pointer = pos; active = false; } void OptionSelector::open(void){ pointer = pos; active = true; } void OptionSelector::next(void){ if (pointer < count-1){ pointer++; } } void OptionSelector::prev(void){ if (pointer > 0){ pointer--; } } void OptionSelector::select(void){ pos = pointer; } void OptionSelector::sync(void){ } int OptionSelector::calc_start(int rows){ int start = 0; if (count > rows && pointer > rows/2){ if (pointer < count - rows/2){ start = pointer - rows/2; } else { start = count - rows; } } return start; } /* * RangeSelector: a number with up/down controls */ RangeSelector::RangeSelector(const char *description, volatile int *value, int default_val, int min_val, int max_val, int step) :OptionSelector(description, value, default_val), min_val(min_val), max_val(max_val), step(step) { }; void RangeSelector::next(void){ if (pointer > min_val){ pointer -= step; } } void RangeSelector::prev(void){ if (pointer < max_val){ pointer += step; } } void RangeSelector::select(void){ OptionSelector::select(); pos = pointer; *value = pointer; } void RangeSelector::sync(void){ pointer = *value; pos = pointer; } int RangeSelector::render(DISPLAY_DEVICE display, int rows){ const char *marker; rows = OptionSelector::render(display, rows); marker = (pointer < max_val) ? " \x1e": ""; Serial.println(marker); display.println(marker); rows--; if (pointer == pos) display.setTextColor(BLACK, WHITE); Serial.println(pointer); display.println(pointer); rows--; if (pointer == pos) display.setTextColor(WHITE, BLACK); marker = (pointer > min_val) ? " \x1f": ""; Serial.println(marker); display.println(marker); rows--; return rows; } /* * ListSelector: list of numeric options */ ListSelector::ListSelector(const char *description, volatile int *value, int default_val, int count, const int values[]) :OptionSelector(description, value, default_val), values(values) { this->count = count; // find the position corresponding to the default value for (pos=count-1; pos > 0; pos--){ if (FLASH_READ_INT(values, pos) == default_val){ break; } } pointer = pos; }; void ListSelector::select(void){ OptionSelector::select(); pos = pointer; *value = FLASH_READ_INT(values, pos); } void ListSelector::sync(void){ // find the position corresponding to the default value for (pos=count-1; pos > 0; pos--){ if (FLASH_READ_INT(values,pos) == *value){ break; } } pointer = pos; } int ListSelector::render(DISPLAY_DEVICE display, int rows){ char buf[16]; int start; rows = OptionSelector::render(display, rows); start = calc_start(rows); for (int i=start; i<start+rows && i<count; i++){ snprintf(buf, sizeof(buf), "%d", FLASH_READ_INT(values, i)); char marker = (i==pointer) ? '\x10' : ' '; Serial.print((i==pointer) ? F(">") : F(" ")); display.print(marker); if (i == pos) display.setTextColor(BLACK, WHITE); Serial.print(buf); display.print(buf); if (i == pos) display.setTextColor(WHITE, BLACK); marker = (i==pointer) ? '\x11' : ' '; display.println(marker); Serial.println(""); } return 0; } /* * NamedListSelector: list of named numeric options */ NamedListSelector::NamedListSelector(const char *description, volatile int *value, int default_val, int count, const char * const names[], const int values[]) :ListSelector(description, value, default_val, count, values), names(names) { } int NamedListSelector::render(DISPLAY_DEVICE display, int rows){ int start; rows = OptionSelector::render(display, rows); start = calc_start(rows); for (int i=start; i<start+rows && i<count; i++){ char marker = (i==pointer) ? '\x10' : ' '; Serial.print((i==pointer) ? F(">") : F(" ")); display.print(marker); if (i == pos) display.setTextColor(BLACK, WHITE); Serial.println(FLASH_READ_STR(names, i)); display.print(FLASH_READ_STR(names, i)); if (i == pos) display.setTextColor(WHITE, BLACK); marker = (i==pointer) ? '\x11' : ' '; display.println(marker); } return 0; } /* * Menu: this is a regular menu, nothing is set here. */ Menu::Menu(const char *description, int count, const union MenuItem * const menus, const int *types) :OptionSelector(description, NULL, 0), menus(menus), types(types) { pos = 0; this->count = count; drilldown = false; } void Menu::open(void){ OptionSelector::open(); drilldown = false; } void Menu::cancel(void){ if (drilldown){ invoke_method(pos, cancel); if (types[pos] != Menu::class_id || !menus[pos].menu->active){ drilldown = false; } } else { OptionSelector::cancel(); } } void Menu::next(void){ if (drilldown){ invoke_method(pos, next); } else { OptionSelector::next(); } } void Menu::prev(void){ if (drilldown){ invoke_method(pos, prev); } else { OptionSelector::prev(); } } void Menu::select(void){ if (drilldown){ invoke_method(pos, select); } else { OptionSelector::select(); drilldown = true; invoke_method(pos, open); } } void Menu::sync(void){ for (int i=0; i<count; i++){ invoke_method(i, sync); } } int Menu::render(DISPLAY_DEVICE display, int rows){ int start; if (drilldown){ rows = invoke_method(pos, render, display, rows); return rows; } rows = OptionSelector::render(display, rows); start = calc_start(rows); for (int i=start; i<start+rows && i<count; i++){ if (i == pointer){ Serial.print(F(">")); display.setTextColor(BLACK, WHITE); } Serial.println(FLASH_STRING FLASH_CAST_PTR(OptionSelector, menus, i)->description); display.println(FLASH_STRING FLASH_CAST_PTR(OptionSelector, menus, i)->description); if (i == pointer){ display.setTextColor(WHITE, BLACK); } } return 0; } <commit_msg>Fix one flash read that was missed in commit b9f54b6<commit_after>/* * Menu * * Copyright (C)2016 Laurentiu Badea * * This file may be redistributed under the terms of the MIT license. * A copy of this license has been included with this distribution in the file LICENSE. */ #include "menu.h" #define BLACK 0 #define WHITE 1 #define INVERSE 2 /* * OptionSelector: share functionality among the other menu classes */ OptionSelector::OptionSelector(const char *description, volatile int *value, int default_val) :description(description), value(value), default_val(default_val) { active = false; pos = default_val; if (value){ *value = default_val; } } int OptionSelector::render(DISPLAY_DEVICE display, int rows){ Serial.println(FLASH_STRING description); Serial.println("---------------------"); display.println(FLASH_STRING description); rows--; if (rows > 4){ display.print("---------------------"); rows--; } return rows; } void OptionSelector::cancel(void){ pointer = pos; active = false; } void OptionSelector::open(void){ pointer = pos; active = true; } void OptionSelector::next(void){ if (pointer < count-1){ pointer++; } } void OptionSelector::prev(void){ if (pointer > 0){ pointer--; } } void OptionSelector::select(void){ pos = pointer; } void OptionSelector::sync(void){ } int OptionSelector::calc_start(int rows){ int start = 0; if (count > rows && pointer > rows/2){ if (pointer < count - rows/2){ start = pointer - rows/2; } else { start = count - rows; } } return start; } /* * RangeSelector: a number with up/down controls */ RangeSelector::RangeSelector(const char *description, volatile int *value, int default_val, int min_val, int max_val, int step) :OptionSelector(description, value, default_val), min_val(min_val), max_val(max_val), step(step) { }; void RangeSelector::next(void){ if (pointer > min_val){ pointer -= step; } } void RangeSelector::prev(void){ if (pointer < max_val){ pointer += step; } } void RangeSelector::select(void){ OptionSelector::select(); pos = pointer; *value = pointer; } void RangeSelector::sync(void){ pointer = *value; pos = pointer; } int RangeSelector::render(DISPLAY_DEVICE display, int rows){ const char *marker; rows = OptionSelector::render(display, rows); marker = (pointer < max_val) ? " \x1e": ""; Serial.println(marker); display.println(marker); rows--; if (pointer == pos) display.setTextColor(BLACK, WHITE); Serial.println(pointer); display.println(pointer); rows--; if (pointer == pos) display.setTextColor(WHITE, BLACK); marker = (pointer > min_val) ? " \x1f": ""; Serial.println(marker); display.println(marker); rows--; return rows; } /* * ListSelector: list of numeric options */ ListSelector::ListSelector(const char *description, volatile int *value, int default_val, int count, const int values[]) :OptionSelector(description, value, default_val), values(values) { this->count = count; // find the position corresponding to the default value for (pos=count-1; pos > 0; pos--){ if (FLASH_READ_INT(values, pos) == default_val){ break; } } pointer = pos; }; void ListSelector::select(void){ OptionSelector::select(); pos = pointer; *value = FLASH_READ_INT(values, pos); } void ListSelector::sync(void){ // find the position corresponding to the default value for (pos=count-1; pos > 0; pos--){ if (FLASH_READ_INT(values,pos) == *value){ break; } } pointer = pos; } int ListSelector::render(DISPLAY_DEVICE display, int rows){ char buf[16]; int start; rows = OptionSelector::render(display, rows); start = calc_start(rows); for (int i=start; i<start+rows && i<count; i++){ snprintf(buf, sizeof(buf), "%d", FLASH_READ_INT(values, i)); char marker = (i==pointer) ? '\x10' : ' '; Serial.print((i==pointer) ? F(">") : F(" ")); display.print(marker); if (i == pos) display.setTextColor(BLACK, WHITE); Serial.print(buf); display.print(buf); if (i == pos) display.setTextColor(WHITE, BLACK); marker = (i==pointer) ? '\x11' : ' '; display.println(marker); Serial.println(""); } return 0; } /* * NamedListSelector: list of named numeric options */ NamedListSelector::NamedListSelector(const char *description, volatile int *value, int default_val, int count, const char * const names[], const int values[]) :ListSelector(description, value, default_val, count, values), names(names) { } int NamedListSelector::render(DISPLAY_DEVICE display, int rows){ int start; rows = OptionSelector::render(display, rows); start = calc_start(rows); for (int i=start; i<start+rows && i<count; i++){ char marker = (i==pointer) ? '\x10' : ' '; Serial.print((i==pointer) ? F(">") : F(" ")); display.print(marker); if (i == pos) display.setTextColor(BLACK, WHITE); Serial.println(FLASH_READ_STR(names, i)); display.print(FLASH_READ_STR(names, i)); if (i == pos) display.setTextColor(WHITE, BLACK); marker = (i==pointer) ? '\x11' : ' '; display.println(marker); } return 0; } /* * Menu: this is a regular menu, nothing is set here. */ Menu::Menu(const char *description, int count, const union MenuItem * const menus, const int *types) :OptionSelector(description, NULL, 0), menus(menus), types(types) { pos = 0; this->count = count; drilldown = false; } void Menu::open(void){ OptionSelector::open(); drilldown = false; } void Menu::cancel(void){ if (drilldown){ invoke_method(pos, cancel); if (FLASH_READ_INT(types, pos) != Menu::class_id || ! FLASH_CAST_PTR(Menu, menus, pos)->active){ drilldown = false; } } else { OptionSelector::cancel(); } } void Menu::next(void){ if (drilldown){ invoke_method(pos, next); } else { OptionSelector::next(); } } void Menu::prev(void){ if (drilldown){ invoke_method(pos, prev); } else { OptionSelector::prev(); } } void Menu::select(void){ if (drilldown){ invoke_method(pos, select); } else { OptionSelector::select(); drilldown = true; invoke_method(pos, open); } } void Menu::sync(void){ for (int i=0; i<count; i++){ invoke_method(i, sync); } } int Menu::render(DISPLAY_DEVICE display, int rows){ int start; if (drilldown){ rows = invoke_method(pos, render, display, rows); return rows; } rows = OptionSelector::render(display, rows); start = calc_start(rows); for (int i=start; i<start+rows && i<count; i++){ if (i == pointer){ Serial.print(F(">")); display.setTextColor(BLACK, WHITE); } Serial.println(FLASH_STRING FLASH_CAST_PTR(OptionSelector, menus, i)->description); display.println(FLASH_STRING FLASH_CAST_PTR(OptionSelector, menus, i)->description); if (i == pointer){ display.setTextColor(WHITE, BLACK); } } return 0; } <|endoftext|>
<commit_before>#ifndef ROCFFT_HPP_ #define ROCFFT_HPP_ #include "core/application.hpp" #include "core/timer_hip.hpp" #include "core/fft.hpp" #include "core/types.hpp" #include "core/traits.hpp" #include "core/context.hpp" #include "rocfft_helper.hpp" #include "hip/hip_runtime_api.h" #include "hip/hip_vector_types.h" #include "rocfft.h" #include <array> #include <regex> namespace gearshifft { namespace RocFFT { namespace traits{ template<typename T_Precision=float> struct Types { using ComplexType = std::complex<float>; using RealType = float; static constexpr rocfft_transform_type_e FFTRealForward = rocfft_transform_type_real_forward; static constexpr rocfft_transform_type_e FFTRealInverse = rocfft_transform_type_real_inverse; static constexpr rocfft_transform_type_e FFTComplexForward = rocfft_transform_type_complex_forward; static constexpr rocfft_transform_type_e FFTComplexInverse = rocfft_transform_type_complex_inverse; }; template<> struct Types<double> { using ComplexType = std::complex<double>; using RealType = double; static constexpr rocfft_transform_type_e FFTRealForward = rocfft_transform_type_real_forward; static constexpr rocfft_transform_type_e FFTRealInverse = rocfft_transform_type_real_inverse; static constexpr rocfft_transform_type_e FFTComplexForward = rocfft_transform_type_complex_forward; static constexpr rocfft_transform_type_e FFTComplexInverse = rocfft_transform_type_complex_inverse; }; } // namespace traits /** * HIP context create() and destroy(). Time is benchmarked. */ struct RocFFTContext : public ContextDefault<> { int device = 0; static const std::string title() { return "RocFFT"; } static std::string get_device_list() { std::stringstream msg; listHipDevices(msg); return msg.str(); } std::string get_used_device_properties() { std::stringstream ss; getHIPDeviceInformations(device,ss); return ss.str(); } void create() { const std::string options_devtype = options().getDevice(); device = atoi(options_devtype.c_str()); int nrdev=0; CHECK_HIP(hipGetDeviceCount(&nrdev)); assert(nrdev>0); if(device<0 || device>=nrdev) device = 0; CHECK_HIP(hipSetDevice(device)); } void destroy() { CHECK_HIP(hipDeviceReset()); } }; /** * Estimates memory required/reserved by rocfft plan to perform the transformation */ size_t estimateAllocSize(rocfft_plan& plan) { size_t s=0; if(plan != 0){ CHECK_HIP( rocfft_plan_get_work_buffer_size(plan, &s) );} return s; } /** * RocFFT plan and execution class. * * This class handles: * - {1D, 2D, 3D} x {R2C, C2R, C2C} x {inplace, outplace} x {float, double}. */ template<typename TFFT, // see fft.hpp (FFT_Inplace_Real, ...) typename TPrecision, // double, float size_t NDim // 1..3 > struct RocFFTImpl { using Extent = std::array<size_t,NDim>; using Types = typename traits::Types<TPrecision>; using ComplexType = typename Types::ComplexType; using RealType = typename Types::RealType; static constexpr bool IsInplace = TFFT::IsInplace; static constexpr bool IsComplex = TFFT::IsComplex; // static constexpr // bool IsHalf = std::is_same<TPrecision, float16>::value; static constexpr bool IsSingle = std::is_same<TPrecision, float>::value; static constexpr bool IsInplaceReal = IsInplace && IsComplex==false; static constexpr rocfft_transform_type FFTForward = IsComplex ? Types::FFTComplexForward : Types::FFTRealForward; static constexpr rocfft_transform_type FFTInverse = IsComplex ? Types::FFTComplexInverse : Types::FFTRealInverse; static constexpr rocfft_precision FFTPrecision = IsSingle ? rocfft_precision_single : rocfft_precision_double; static constexpr rocfft_result_placement FFTPlacement = IsInplace ? rocfft_placement_inplace : rocfft_placement_notinplace; using value_type = typename std::conditional<IsComplex,ComplexType,RealType>::type; /// extents of the FFT input data Extent extents_ = {{0}}; /// extents of the FFT complex data (=FFT(input)) Extent extents_complex_ = {{0}}; /// product of corresponding extents size_t n_ = 0; /// product of corresponding extents size_t n_complex_ = 0; rocfft_plan plan_ = 0; rocfft_execution_info plan_info_= nullptr; void * work_buffer_ = nullptr; value_type* data_ = nullptr; ComplexType* data_complex_ = nullptr; /// size in bytes of FFT input data size_t data_size_ = 0; /// size in bytes of FFT(input) for out-of-place transforms size_t data_complex_size_ = 0; size_t work_buffer_size_allocated_ = 0; RocFFTImpl(const Extent& cextents) { extents_ = interpret_as::column_major(cextents); extents_complex_ = extents_; n_ = std::accumulate(extents_.begin(), extents_.end(), 1, std::multiplies<size_t>()); if(IsComplex==false){ extents_complex_.back() = (extents_.back()/2 + 1); } n_complex_ = std::accumulate(extents_complex_.begin(), extents_complex_.end(), 1, std::multiplies<size_t>()); data_size_ = (IsInplaceReal? 2*n_complex_ : n_) * sizeof(value_type); if(IsInplace==false) data_complex_size_ = n_complex_ * sizeof(ComplexType); rocfft_setup(); } ~RocFFTImpl() { destroy(); rocfft_cleanup(); } /** * Returns allocated memory on device for FFT */ size_t get_allocation_size() { return data_size_ + data_complex_size_; } /** * Returns size in bytes of one data transfer. * * Upload and download have the same size due to round-trip FFT. * \return Size in bytes of FFT data to be transferred (to device or to host memory buffer). */ size_t get_transfer_size() { // when inplace-real then alloc'd data is bigger than data to be transferred return IsInplaceReal ? n_*sizeof(RealType) : data_size_; } /** * Returns estimated allocated memory on device for FFT plan */ size_t get_plan_size() { size_t size1 = 0; // size forward trafo size_t size2 = 0; // size inverse trafo size1 = work_buffer_size_allocated_ > 0 ? work_buffer_size_allocated_ : estimateAllocSize(plan_); size2 = size1; // check available GPU memory size_t mem_free=0, mem_tot=0; CHECK_HIP( hipMemGetInfo(&mem_free, &mem_tot) ); size_t wanted = std::max(size1,size2) + data_size_ + data_complex_size_; if(mem_free<wanted) { std::stringstream ss; ss << mem_free << "<" << wanted << " (bytes)"; throw std::runtime_error("Not enough GPU memory available. "+ss.str()); } size_t total_mem = 95*getMemorySize()/100; // keep some memory available, otherwise an out-of-memory killer becomes more likely if(total_mem < 2*data_size_) { // includes host input buffers std::stringstream ss; ss << total_mem << "<" << 2*data_size_ << " (bytes)"; throw std::runtime_error("Host data exceeds physical memory. "+ss.str()); } return std::max(size1,size2); } /** * Free work buffer for rocfft */ void free_work_buffer(){ if(work_buffer_){ CHECK_HIP( hipFree(work_buffer_) ); work_buffer_ = nullptr; } work_buffer_size_allocated_ = 0; } /** * Allocate work buffer for rocfft on HIP device (free it first if requred, do nothing if work buffer is already large enough) */ void allocate_work_buffer(std::size_t _bytes){ if(_bytes > work_buffer_size_allocated_){ free_work_buffer(); CHECK_HIP(hipMalloc(&work_buffer_, _bytes)); work_buffer_size_allocated_ = _bytes; } } // --- next methods are benchmarked --- /** * Allocate buffers on HIP device */ void allocate() { CHECK_HIP(hipMalloc(&data_, data_size_)); if(IsInplace) { data_complex_ = reinterpret_cast<ComplexType*>(data_); }else{ CHECK_HIP(hipMalloc(&data_complex_, data_complex_size_)); } } // create FFT plan handle void init_forward() { CHECK_HIP(rocfft_plan_create(&plan_, FFTPlacement, FFTForward, FFTPrecision, extents_.size(), extents_.data(), 1, nullptr)); size_t workBufferSize = 0; CHECK_HIP(rocfft_plan_get_work_buffer_size(plan_, &workBufferSize)); if(!plan_info_) CHECK_HIP(rocfft_execution_info_create(&plan_info_)); if(work_buffer_size_allocated_ < workBufferSize) { allocate_work_buffer(workBufferSize); CHECK_HIP(rocfft_execution_info_set_work_buffer(plan_info_, work_buffer_, workBufferSize)); } } // recreates plan if needed void init_inverse() { CHECK_HIP(rocfft_plan_create(&plan_, FFTPlacement, FFTInverse, FFTPrecision, extents_.size(), extents_.data(), 1, nullptr)); size_t workBufferSize = 0; CHECK_HIP(rocfft_plan_get_work_buffer_size(plan_, &workBufferSize)); if(!plan_info_) CHECK_HIP(rocfft_execution_info_create(&plan_info_)); if(work_buffer_size_allocated_ < workBufferSize) { allocate_work_buffer(workBufferSize); CHECK_HIP(rocfft_execution_info_set_work_buffer(plan_info_, work_buffer_, workBufferSize)); } } void execute_forward() { CHECK_HIP(rocfft_execute(plan_, (void**) &data_, (void**) &data_complex_, plan_info_)); } void execute_inverse() { CHECK_HIP(rocfft_execute(plan_, (void**) &data_complex_, (void**) &data_, plan_info_)); } template<typename THostData> void upload(THostData* input) { if(IsInplaceReal && NDim>1) { size_t w = extents_[NDim-1] * sizeof(THostData); size_t h = n_ * sizeof(THostData) / w; size_t pitch = (extents_[NDim-1]/2+1) * sizeof(ComplexType); CHECK_HIP(hipMemcpy2D(data_, pitch, input, w, w, h, hipMemcpyHostToDevice)); }else{ CHECK_HIP(hipMemcpy(data_, input, get_transfer_size(), hipMemcpyHostToDevice)); } } template<typename THostData> void download(THostData* output) { if(IsInplaceReal && NDim>1) { size_t w = extents_[NDim-1] * sizeof(THostData); size_t h = n_ * sizeof(THostData) / w; size_t pitch = (extents_[NDim-1]/2+1) * sizeof(ComplexType); CHECK_HIP(hipMemcpy2D(output, w, data_, pitch, w, h, hipMemcpyDeviceToHost)); }else{ CHECK_HIP(hipMemcpy(output, data_, get_transfer_size(), hipMemcpyDeviceToHost)); } } void destroy() { CHECK_HIP( hipFree(data_) ); data_=nullptr; if(IsInplace==false && data_complex_) { CHECK_HIP( hipFree(data_complex_) ); data_complex_ = nullptr; } if(plan_) { CHECK_HIP( rocfft_plan_destroy(plan_) ); plan_=0; } if(work_buffer_){ CHECK_HIP( hipFree(work_buffer_) ); work_buffer_ = nullptr; } if(plan_info_){ CHECK_HIP(rocfft_execution_info_destroy(plan_info_)); plan_info_ = nullptr; } } }; using Inplace_Real = gearshifft::FFT<FFT_Inplace_Real, FFT_Plan_Reusable, RocFFTImpl, TimerGPU >; using Outplace_Real = gearshifft::FFT<FFT_Outplace_Real, FFT_Plan_Reusable, RocFFTImpl, TimerGPU >; using Inplace_Complex = gearshifft::FFT<FFT_Inplace_Complex, FFT_Plan_Reusable, RocFFTImpl, TimerGPU >; using Outplace_Complex = gearshifft::FFT<FFT_Outplace_Complex, FFT_Plan_Reusable, RocFFTImpl, TimerGPU >; } // namespace RocFFT } // namespace gearshifft #endif /* ROCFFT_HPP_ */ <commit_msg>added status check<commit_after>#ifndef ROCFFT_HPP_ #define ROCFFT_HPP_ #include "core/application.hpp" #include "core/timer_hip.hpp" #include "core/fft.hpp" #include "core/types.hpp" #include "core/traits.hpp" #include "core/context.hpp" #include "rocfft_helper.hpp" #include "hip/hip_runtime_api.h" #include "hip/hip_vector_types.h" #include "rocfft.h" #include <array> #include <regex> namespace gearshifft { namespace RocFFT { namespace traits{ template<typename T_Precision=float> struct Types { using ComplexType = std::complex<float>; using RealType = float; static constexpr rocfft_transform_type_e FFTRealForward = rocfft_transform_type_real_forward; static constexpr rocfft_transform_type_e FFTRealInverse = rocfft_transform_type_real_inverse; static constexpr rocfft_transform_type_e FFTComplexForward = rocfft_transform_type_complex_forward; static constexpr rocfft_transform_type_e FFTComplexInverse = rocfft_transform_type_complex_inverse; }; template<> struct Types<double> { using ComplexType = std::complex<double>; using RealType = double; static constexpr rocfft_transform_type_e FFTRealForward = rocfft_transform_type_real_forward; static constexpr rocfft_transform_type_e FFTRealInverse = rocfft_transform_type_real_inverse; static constexpr rocfft_transform_type_e FFTComplexForward = rocfft_transform_type_complex_forward; static constexpr rocfft_transform_type_e FFTComplexInverse = rocfft_transform_type_complex_inverse; }; } // namespace traits /** * HIP context create() and destroy(). Time is benchmarked. */ struct RocFFTContext : public ContextDefault<> { int device = 0; static const std::string title() { return "RocFFT"; } static std::string get_device_list() { std::stringstream msg; listHipDevices(msg); return msg.str(); } std::string get_used_device_properties() { std::stringstream ss; getHIPDeviceInformations(device,ss); return ss.str(); } void create() { const std::string options_devtype = options().getDevice(); device = atoi(options_devtype.c_str()); int nrdev=0; CHECK_HIP(hipGetDeviceCount(&nrdev)); assert(nrdev>0); if(device<0 || device>=nrdev) device = 0; CHECK_HIP(hipSetDevice(device)); } void destroy() { CHECK_HIP(hipDeviceReset()); } }; /** * Estimates memory required/reserved by rocfft plan to perform the transformation */ size_t estimateAllocSize(rocfft_plan& plan) { size_t s=0; if(plan != 0){ CHECK_HIP( rocfft_plan_get_work_buffer_size(plan, &s) );} return s; } /** * RocFFT plan and execution class. * * This class handles: * - {1D, 2D, 3D} x {R2C, C2R, C2C} x {inplace, outplace} x {float, double}. */ template<typename TFFT, // see fft.hpp (FFT_Inplace_Real, ...) typename TPrecision, // double, float size_t NDim // 1..3 > struct RocFFTImpl { using Extent = std::array<size_t,NDim>; using Types = typename traits::Types<TPrecision>; using ComplexType = typename Types::ComplexType; using RealType = typename Types::RealType; static constexpr bool IsInplace = TFFT::IsInplace; static constexpr bool IsComplex = TFFT::IsComplex; // static constexpr // bool IsHalf = std::is_same<TPrecision, float16>::value; static constexpr bool IsSingle = std::is_same<TPrecision, float>::value; static constexpr bool IsInplaceReal = IsInplace && IsComplex==false; static constexpr rocfft_transform_type FFTForward = IsComplex ? Types::FFTComplexForward : Types::FFTRealForward; static constexpr rocfft_transform_type FFTInverse = IsComplex ? Types::FFTComplexInverse : Types::FFTRealInverse; static constexpr rocfft_precision FFTPrecision = IsSingle ? rocfft_precision_single : rocfft_precision_double; static constexpr rocfft_result_placement FFTPlacement = IsInplace ? rocfft_placement_inplace : rocfft_placement_notinplace; using value_type = typename std::conditional<IsComplex,ComplexType,RealType>::type; /// extents of the FFT input data Extent extents_ = {{0}}; /// extents of the FFT complex data (=FFT(input)) Extent extents_complex_ = {{0}}; /// product of corresponding extents size_t n_ = 0; /// product of corresponding extents size_t n_complex_ = 0; rocfft_plan plan_ = 0; rocfft_execution_info plan_info_= nullptr; void * work_buffer_ = nullptr; value_type* data_ = nullptr; ComplexType* data_complex_ = nullptr; /// size in bytes of FFT input data size_t data_size_ = 0; /// size in bytes of FFT(input) for out-of-place transforms size_t data_complex_size_ = 0; size_t work_buffer_size_allocated_ = 0; RocFFTImpl(const Extent& cextents) { extents_ = interpret_as::column_major(cextents); extents_complex_ = extents_; n_ = std::accumulate(extents_.begin(), extents_.end(), 1, std::multiplies<size_t>()); if(IsComplex==false){ extents_complex_.back() = (extents_.back()/2 + 1); } n_complex_ = std::accumulate(extents_complex_.begin(), extents_complex_.end(), 1, std::multiplies<size_t>()); data_size_ = (IsInplaceReal? 2*n_complex_ : n_) * sizeof(value_type); if(IsInplace==false) data_complex_size_ = n_complex_ * sizeof(ComplexType); CHECK_HIP(rocfft_setup()); } ~RocFFTImpl() { destroy(); CHECK_HIP(rocfft_cleanup()); } /** * Returns allocated memory on device for FFT */ size_t get_allocation_size() { return data_size_ + data_complex_size_; } /** * Returns size in bytes of one data transfer. * * Upload and download have the same size due to round-trip FFT. * \return Size in bytes of FFT data to be transferred (to device or to host memory buffer). */ size_t get_transfer_size() { // when inplace-real then alloc'd data is bigger than data to be transferred return IsInplaceReal ? n_*sizeof(RealType) : data_size_; } /** * Returns estimated allocated memory on device for FFT plan */ size_t get_plan_size() { size_t size1 = 0; // size forward trafo size_t size2 = 0; // size inverse trafo size1 = work_buffer_size_allocated_ > 0 ? work_buffer_size_allocated_ : estimateAllocSize(plan_); size2 = size1; // check available GPU memory size_t mem_free=0, mem_tot=0; CHECK_HIP( hipMemGetInfo(&mem_free, &mem_tot) ); size_t wanted = std::max(size1,size2) + data_size_ + data_complex_size_; if(mem_free<wanted) { std::stringstream ss; ss << mem_free << "<" << wanted << " (bytes)"; throw std::runtime_error("Not enough GPU memory available. "+ss.str()); } size_t total_mem = 95*getMemorySize()/100; // keep some memory available, otherwise an out-of-memory killer becomes more likely if(total_mem < 2*data_size_) { // includes host input buffers std::stringstream ss; ss << total_mem << "<" << 2*data_size_ << " (bytes)"; throw std::runtime_error("Host data exceeds physical memory. "+ss.str()); } return std::max(size1,size2); } /** * Free work buffer for rocfft */ void free_work_buffer(){ if(work_buffer_){ CHECK_HIP( hipFree(work_buffer_) ); work_buffer_ = nullptr; } work_buffer_size_allocated_ = 0; } /** * Allocate work buffer for rocfft on HIP device (free it first if requred, do nothing if work buffer is already large enough) */ void allocate_work_buffer(std::size_t _bytes){ if(_bytes > work_buffer_size_allocated_){ free_work_buffer(); CHECK_HIP(hipMalloc(&work_buffer_, _bytes)); work_buffer_size_allocated_ = _bytes; } } // --- next methods are benchmarked --- /** * Allocate buffers on HIP device */ void allocate() { CHECK_HIP(hipMalloc(&data_, data_size_)); if(IsInplace) { data_complex_ = reinterpret_cast<ComplexType*>(data_); }else{ CHECK_HIP(hipMalloc(&data_complex_, data_complex_size_)); } } // create FFT plan handle void init_forward() { CHECK_HIP(rocfft_plan_create(&plan_, FFTPlacement, FFTForward, FFTPrecision, extents_.size(), extents_.data(), 1, nullptr)); size_t workBufferSize = 0; CHECK_HIP(rocfft_plan_get_work_buffer_size(plan_, &workBufferSize)); if(!plan_info_) CHECK_HIP(rocfft_execution_info_create(&plan_info_)); if(work_buffer_size_allocated_ < workBufferSize) { allocate_work_buffer(workBufferSize); CHECK_HIP(rocfft_execution_info_set_work_buffer(plan_info_, work_buffer_, workBufferSize)); } } // recreates plan if needed void init_inverse() { CHECK_HIP(rocfft_plan_create(&plan_, FFTPlacement, FFTInverse, FFTPrecision, extents_.size(), extents_.data(), 1, nullptr)); size_t workBufferSize = 0; CHECK_HIP(rocfft_plan_get_work_buffer_size(plan_, &workBufferSize)); if(!plan_info_) CHECK_HIP(rocfft_execution_info_create(&plan_info_)); if(work_buffer_size_allocated_ < workBufferSize) { allocate_work_buffer(workBufferSize); CHECK_HIP(rocfft_execution_info_set_work_buffer(plan_info_, work_buffer_, workBufferSize)); } } void execute_forward() { CHECK_HIP(rocfft_execute(plan_, (void**) &data_, (void**) &data_complex_, plan_info_)); } void execute_inverse() { CHECK_HIP(rocfft_execute(plan_, (void**) &data_complex_, (void**) &data_, plan_info_)); } template<typename THostData> void upload(THostData* input) { if(IsInplaceReal && NDim>1) { size_t w = extents_[NDim-1] * sizeof(THostData); size_t h = n_ * sizeof(THostData) / w; size_t pitch = (extents_[NDim-1]/2+1) * sizeof(ComplexType); CHECK_HIP(hipMemcpy2D(data_, pitch, input, w, w, h, hipMemcpyHostToDevice)); }else{ CHECK_HIP(hipMemcpy(data_, input, get_transfer_size(), hipMemcpyHostToDevice)); } } template<typename THostData> void download(THostData* output) { if(IsInplaceReal && NDim>1) { size_t w = extents_[NDim-1] * sizeof(THostData); size_t h = n_ * sizeof(THostData) / w; size_t pitch = (extents_[NDim-1]/2+1) * sizeof(ComplexType); CHECK_HIP(hipMemcpy2D(output, w, data_, pitch, w, h, hipMemcpyDeviceToHost)); }else{ CHECK_HIP(hipMemcpy(output, data_, get_transfer_size(), hipMemcpyDeviceToHost)); } } void destroy() { CHECK_HIP( hipFree(data_) ); data_=nullptr; if(IsInplace==false && data_complex_) { CHECK_HIP( hipFree(data_complex_) ); data_complex_ = nullptr; } if(plan_) { CHECK_HIP( rocfft_plan_destroy(plan_) ); plan_=0; } if(work_buffer_){ CHECK_HIP( hipFree(work_buffer_) ); work_buffer_ = nullptr; } if(plan_info_){ CHECK_HIP(rocfft_execution_info_destroy(plan_info_)); plan_info_ = nullptr; } } }; using Inplace_Real = gearshifft::FFT<FFT_Inplace_Real, FFT_Plan_Reusable, RocFFTImpl, TimerGPU >; using Outplace_Real = gearshifft::FFT<FFT_Outplace_Real, FFT_Plan_Reusable, RocFFTImpl, TimerGPU >; using Inplace_Complex = gearshifft::FFT<FFT_Inplace_Complex, FFT_Plan_Reusable, RocFFTImpl, TimerGPU >; using Outplace_Complex = gearshifft::FFT<FFT_Outplace_Complex, FFT_Plan_Reusable, RocFFTImpl, TimerGPU >; } // namespace RocFFT } // namespace gearshifft #endif /* ROCFFT_HPP_ */ <|endoftext|>
<commit_before>// Copyright (C) 2014 Jérôme Leclercq // This file is part of the "Nazara Engine - Mathematics module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_MATRIX4_HPP #define NAZARA_MATRIX4_HPP #include <Nazara/Core/String.hpp> #include <Nazara/Math/Config.hpp> template<typename T> class NzEulerAngles; template<typename T> class NzQuaternion; template<typename T> class NzVector2; template<typename T> class NzVector3; template<typename T> class NzVector4; template<typename T> class NzMatrix4 { public: NzMatrix4() = default; NzMatrix4(T r11, T r12, T r13, T r14, T r21, T r22, T r23, T r24, T r31, T r32, T r33, T r34, T r41, T r42, T r43, T r44); //NzMatrix4(const NzMatrix3<T>& matrix); NzMatrix4(const T matrix[16]); template<typename U> explicit NzMatrix4(const NzMatrix4<U>& matrix); NzMatrix4(const NzMatrix4& matrix) = default; ~NzMatrix4() = default; NzMatrix4& ApplyRotation(const NzQuaternion<T>& rotation); NzMatrix4& ApplyScale(const NzVector3<T>& scale); NzMatrix4& ApplyTranslation(const NzVector3<T>& translation); NzMatrix4& Concatenate(const NzMatrix4& matrix); NzMatrix4& ConcatenateAffine(const NzMatrix4& matrix); NzVector4<T> GetColumn(unsigned int column) const; T GetDeterminant() const; T GetDeterminantAffine() const; bool GetInverse(NzMatrix4* dest) const; bool GetInverseAffine(NzMatrix4* dest) const; NzQuaternion<T> GetRotation() const; //NzMatrix3 GetRotationMatrix() const; NzVector4<T> GetRow(unsigned int row) const; NzVector3<T> GetScale() const; NzVector3<T> GetTranslation() const; void GetTransposed(NzMatrix4* dest) const; bool HasNegativeScale() const; bool HasScale() const; NzMatrix4& Inverse(bool* succeeded = nullptr); NzMatrix4& InverseAffine(bool* succeeded = nullptr); bool IsAffine() const; bool IsIdentity() const; NzMatrix4& MakeIdentity(); NzMatrix4& MakeLookAt(const NzVector3<T>& eye, const NzVector3<T>& target, const NzVector3<T>& up = NzVector3<T>::Up()); NzMatrix4& MakeOrtho(T left, T right, T top, T bottom, T zNear = -1.0, T zFar = 1.0); NzMatrix4& MakePerspective(T angle, T ratio, T zNear, T zFar); NzMatrix4& MakeRotation(const NzQuaternion<T>& rotation); NzMatrix4& MakeScale(const NzVector3<T>& scale); NzMatrix4& MakeTranslation(const NzVector3<T>& translation); NzMatrix4& MakeTransform(const NzVector3<T>& translation, const NzQuaternion<T>& rotation); NzMatrix4& MakeTransform(const NzVector3<T>& translation, const NzQuaternion<T>& rotation, const NzVector3<T>& scale); NzMatrix4& MakeViewMatrix(const NzVector3<T>& translation, const NzQuaternion<T>& rotation); NzMatrix4& MakeZero(); NzMatrix4& Set(T r11, T r12, T r13, T r14, T r21, T r22, T r23, T r24, T r31, T r32, T r33, T r34, T r41, T r42, T r43, T r44); NzMatrix4& Set(const T matrix[16]); //NzMatrix4(const NzMatrix3<T>& matrix); NzMatrix4& Set(const NzMatrix4& matrix); NzMatrix4& Set(NzMatrix4&& matrix); template<typename U> NzMatrix4& Set(const NzMatrix4<U>& matrix); NzMatrix4& SetRotation(const NzQuaternion<T>& rotation); NzMatrix4& SetScale(const NzVector3<T>& scale); NzMatrix4& SetTranslation(const NzVector3<T>& translation); NzString ToString() const; NzVector2<T> Transform(const NzVector2<T>& vector, T z = 0.0, T w = 1.0) const; NzVector3<T> Transform(const NzVector3<T>& vector, T w = 1.0) const; NzVector4<T> Transform(const NzVector4<T>& vector) const; NzMatrix4& Transpose(); operator T*(); operator const T*() const; T& operator()(unsigned int x, unsigned int y); T operator()(unsigned int x, unsigned int y) const; NzMatrix4& operator=(const NzMatrix4& matrix) = default; NzMatrix4 operator*(const NzMatrix4& matrix) const; NzVector2<T> operator*(const NzVector2<T>& vector) const; NzVector3<T> operator*(const NzVector3<T>& vector) const; NzVector4<T> operator*(const NzVector4<T>& vector) const; NzMatrix4 operator*(T scalar) const; NzMatrix4& operator*=(const NzMatrix4& matrix); NzMatrix4& operator*=(T scalar); bool operator==(const NzMatrix4& mat) const; bool operator!=(const NzMatrix4& mat) const; static NzMatrix4 Concatenate(const NzMatrix4& left, const NzMatrix4& right); static NzMatrix4 ConcatenateAffine(const NzMatrix4& left, const NzMatrix4& right); static NzMatrix4 Identity(); static NzMatrix4 LookAt(const NzVector3<T>& eye, const NzVector3<T>& target, const NzVector3<T>& up = NzVector3<T>::Up()); static NzMatrix4 Ortho(T left, T right, T top, T bottom, T zNear = -1.0, T zFar = 1.0); static NzMatrix4 Perspective(T angle, T ratio, T zNear, T zFar); static NzMatrix4 Rotate(const NzQuaternion<T>& rotation); static NzMatrix4 Scale(const NzVector3<T>& scale); static NzMatrix4 Translate(const NzVector3<T>& translation); static NzMatrix4 Transform(const NzVector3<T>& translation, const NzQuaternion<T>& rotation); static NzMatrix4 Transform(const NzVector3<T>& translation, const NzQuaternion<T>& rotation, const NzVector3<T>& scale); static NzMatrix4 ViewMatrix(const NzVector3<T>& translation, const NzQuaternion<T>& rotation); static NzMatrix4 Zero(); T m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44; }; template<typename T> std::ostream& operator<<(std::ostream& out, const NzMatrix4<T>& matrix); template<typename T> NzMatrix4<T> operator*(T scale, const NzMatrix4<T>& matrix); typedef NzMatrix4<double> NzMatrix4d; typedef NzMatrix4<float> NzMatrix4f; #include <Nazara/Math/Matrix4.inl> #endif // NAZARA_MATRIX4_HPP <commit_msg>Added FIXME<commit_after>// Copyright (C) 2014 Jérôme Leclercq // This file is part of the "Nazara Engine - Mathematics module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_MATRIX4_HPP #define NAZARA_MATRIX4_HPP ///FIXME: Matrices column-major, difficile de bosser avec (Tout passer en row-major et transposer dans les shaders ?) #include <Nazara/Core/String.hpp> #include <Nazara/Math/Config.hpp> template<typename T> class NzEulerAngles; template<typename T> class NzQuaternion; template<typename T> class NzVector2; template<typename T> class NzVector3; template<typename T> class NzVector4; template<typename T> class NzMatrix4 { public: NzMatrix4() = default; NzMatrix4(T r11, T r12, T r13, T r14, T r21, T r22, T r23, T r24, T r31, T r32, T r33, T r34, T r41, T r42, T r43, T r44); //NzMatrix4(const NzMatrix3<T>& matrix); NzMatrix4(const T matrix[16]); template<typename U> explicit NzMatrix4(const NzMatrix4<U>& matrix); NzMatrix4(const NzMatrix4& matrix) = default; ~NzMatrix4() = default; NzMatrix4& ApplyRotation(const NzQuaternion<T>& rotation); NzMatrix4& ApplyScale(const NzVector3<T>& scale); NzMatrix4& ApplyTranslation(const NzVector3<T>& translation); NzMatrix4& Concatenate(const NzMatrix4& matrix); NzMatrix4& ConcatenateAffine(const NzMatrix4& matrix); NzVector4<T> GetColumn(unsigned int column) const; T GetDeterminant() const; T GetDeterminantAffine() const; bool GetInverse(NzMatrix4* dest) const; bool GetInverseAffine(NzMatrix4* dest) const; NzQuaternion<T> GetRotation() const; //NzMatrix3 GetRotationMatrix() const; NzVector4<T> GetRow(unsigned int row) const; NzVector3<T> GetScale() const; NzVector3<T> GetTranslation() const; void GetTransposed(NzMatrix4* dest) const; bool HasNegativeScale() const; bool HasScale() const; NzMatrix4& Inverse(bool* succeeded = nullptr); NzMatrix4& InverseAffine(bool* succeeded = nullptr); bool IsAffine() const; bool IsIdentity() const; NzMatrix4& MakeIdentity(); NzMatrix4& MakeLookAt(const NzVector3<T>& eye, const NzVector3<T>& target, const NzVector3<T>& up = NzVector3<T>::Up()); NzMatrix4& MakeOrtho(T left, T right, T top, T bottom, T zNear = -1.0, T zFar = 1.0); NzMatrix4& MakePerspective(T angle, T ratio, T zNear, T zFar); NzMatrix4& MakeRotation(const NzQuaternion<T>& rotation); NzMatrix4& MakeScale(const NzVector3<T>& scale); NzMatrix4& MakeTranslation(const NzVector3<T>& translation); NzMatrix4& MakeTransform(const NzVector3<T>& translation, const NzQuaternion<T>& rotation); NzMatrix4& MakeTransform(const NzVector3<T>& translation, const NzQuaternion<T>& rotation, const NzVector3<T>& scale); NzMatrix4& MakeViewMatrix(const NzVector3<T>& translation, const NzQuaternion<T>& rotation); NzMatrix4& MakeZero(); NzMatrix4& Set(T r11, T r12, T r13, T r14, T r21, T r22, T r23, T r24, T r31, T r32, T r33, T r34, T r41, T r42, T r43, T r44); NzMatrix4& Set(const T matrix[16]); //NzMatrix4(const NzMatrix3<T>& matrix); NzMatrix4& Set(const NzMatrix4& matrix); NzMatrix4& Set(NzMatrix4&& matrix); template<typename U> NzMatrix4& Set(const NzMatrix4<U>& matrix); NzMatrix4& SetRotation(const NzQuaternion<T>& rotation); NzMatrix4& SetScale(const NzVector3<T>& scale); NzMatrix4& SetTranslation(const NzVector3<T>& translation); NzString ToString() const; NzVector2<T> Transform(const NzVector2<T>& vector, T z = 0.0, T w = 1.0) const; NzVector3<T> Transform(const NzVector3<T>& vector, T w = 1.0) const; NzVector4<T> Transform(const NzVector4<T>& vector) const; NzMatrix4& Transpose(); operator T*(); operator const T*() const; T& operator()(unsigned int x, unsigned int y); T operator()(unsigned int x, unsigned int y) const; NzMatrix4& operator=(const NzMatrix4& matrix) = default; NzMatrix4 operator*(const NzMatrix4& matrix) const; NzVector2<T> operator*(const NzVector2<T>& vector) const; NzVector3<T> operator*(const NzVector3<T>& vector) const; NzVector4<T> operator*(const NzVector4<T>& vector) const; NzMatrix4 operator*(T scalar) const; NzMatrix4& operator*=(const NzMatrix4& matrix); NzMatrix4& operator*=(T scalar); bool operator==(const NzMatrix4& mat) const; bool operator!=(const NzMatrix4& mat) const; static NzMatrix4 Concatenate(const NzMatrix4& left, const NzMatrix4& right); static NzMatrix4 ConcatenateAffine(const NzMatrix4& left, const NzMatrix4& right); static NzMatrix4 Identity(); static NzMatrix4 LookAt(const NzVector3<T>& eye, const NzVector3<T>& target, const NzVector3<T>& up = NzVector3<T>::Up()); static NzMatrix4 Ortho(T left, T right, T top, T bottom, T zNear = -1.0, T zFar = 1.0); static NzMatrix4 Perspective(T angle, T ratio, T zNear, T zFar); static NzMatrix4 Rotate(const NzQuaternion<T>& rotation); static NzMatrix4 Scale(const NzVector3<T>& scale); static NzMatrix4 Translate(const NzVector3<T>& translation); static NzMatrix4 Transform(const NzVector3<T>& translation, const NzQuaternion<T>& rotation); static NzMatrix4 Transform(const NzVector3<T>& translation, const NzQuaternion<T>& rotation, const NzVector3<T>& scale); static NzMatrix4 ViewMatrix(const NzVector3<T>& translation, const NzQuaternion<T>& rotation); static NzMatrix4 Zero(); T m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44; }; template<typename T> std::ostream& operator<<(std::ostream& out, const NzMatrix4<T>& matrix); template<typename T> NzMatrix4<T> operator*(T scale, const NzMatrix4<T>& matrix); typedef NzMatrix4<double> NzMatrix4d; typedef NzMatrix4<float> NzMatrix4f; #include <Nazara/Math/Matrix4.inl> #endif // NAZARA_MATRIX4_HPP <|endoftext|>
<commit_before>#ifndef ARABICA_XSLT_SORT_HPP #define ARABICA_XSLT_SORT_HPP #include <algorithm> #include "handler/xslt_value_validation.hpp" namespace Arabica { namespace XSLT { class Sort { public: Sort(const Arabica::XPath::XPathExpressionPtr<std::string>& select, const Arabica::XPath::XPathExpressionPtr<std::string>& lang, //="language-code" const Arabica::XPath::XPathExpressionPtr<std::string>& datatype, //="text|number|qname" const Arabica::XPath::XPathExpressionPtr<std::string>& order, //="ascending|descending" const Arabica::XPath::XPathExpressionPtr<std::string>& caseorder) : //="upper-first|lower-first select_(select), lang_(lang), datatype_(datatype), order_(order), caseorder_(caseorder), sub_sort_(0) { } // Sort ~Sort() { delete sub_sort_; } // ~Sort void set_context(const DOM::Node<std::string>& node, ExecutionContext& context) { context_ = &context; std::string datatype = datatype_->evaluateAsString(node, context_->xpathContext()); std::string order = order_->evaluateAsString(node, context_->xpathContext()); static const char* allowed_datatypes[] = { "text", "number", 0 }; static const char* allowed_orders[] = { "ascending", "descending", 0 }; validateValues("xsl:sort", "data-type", datatype, allowed_datatypes); validateValues("xsl:sort", "order", order, allowed_orders); if(datatype == "number") if(order == "ascending") sort_fn_ = &Sort::numberAscending; else sort_fn_ = &Sort::numberDescending; else if(order == "ascending") sort_fn_ = &Sort::stringAscending; else sort_fn_ = &Sort::stringDescending; if(sub_sort_) sub_sort_->set_context(node, context); } // set_context bool operator()(const DOM::Node<std::string>& n1, const DOM::Node<std::string>& n2) const { return (this->*sort_fn_)(n1, n2); } // operator() void add_sub_sort(Sort* sort) { if(!sub_sort_) sub_sort_ = sort; else sub_sort_->add_sub_sort(sort); } // add_sub_sort private: typedef bool(Sort::*sortFn)(const DOM::Node<std::string>& n1, const DOM::Node<std::string>& n2) const; bool numberAscending(const DOM::Node<std::string>& n1, const DOM::Node<std::string>& n2) const { double v1 = select_->evaluateAsNumber(n1, context_->xpathContext()); double v2 = select_->evaluateAsNumber(n2, context_->xpathContext()); bool nan1 = Arabica::XPath::isNaN(v1); bool nan2 = Arabica::XPath::isNaN(v2); if(((nan1 && nan2) || (v1 == v2)) && (sub_sort_)) return (*sub_sort_)(n1, n2); if(nan2) return false; if(nan1) return true; return v1 < v2; } // numberAscending bool numberDescending(const DOM::Node<std::string>& n1, const DOM::Node<std::string>& n2) const { double v1 = select_->evaluateAsNumber(n1, context_->xpathContext()); double v2 = select_->evaluateAsNumber(n2, context_->xpathContext()); bool nan1 = Arabica::XPath::isNaN(v1); bool nan2 = Arabica::XPath::isNaN(v2); if(((nan1 && nan2) || (v1 == v2)) && (sub_sort_)) return (*sub_sort_)(n1, n2); if(nan1) return false; if(nan2) return true; return v1 > v2; } // numberDescending bool stringAscending(const DOM::Node<std::string>& n1, const DOM::Node<std::string>& n2) const { std::string v1 = select_->evaluateAsString(n1, context_->xpathContext()); std::string v2 = select_->evaluateAsString(n2, context_->xpathContext()); if((v1 == v2) && (sub_sort_)) return (*sub_sort_)(n1, n2); return v1 < v2; } // stringAscending bool stringDescending(const DOM::Node<std::string>& n1, const DOM::Node<std::string>& n2) const { std::string v1 = select_->evaluateAsString(n1, context_->xpathContext()); std::string v2 = select_->evaluateAsString(n2, context_->xpathContext()); if((v1 == v2) && (sub_sort_)) return (*sub_sort_)(n1, n2); return v1 > v2; } // stringAscending Arabica::XPath::XPathExpressionPtr<std::string> select_; Arabica::XPath::XPathExpressionPtr<std::string> lang_; Arabica::XPath::XPathExpressionPtr<std::string> datatype_; Arabica::XPath::XPathExpressionPtr<std::string> order_; Arabica::XPath::XPathExpressionPtr<std::string> caseorder_; ExecutionContext* context_; Sort* sub_sort_; sortFn sort_fn_; Sort& operator=(const Sort&); bool operator==(const Sort&) const; }; // class Sort class Sortable { protected: Sortable() : sort_(0) { } // Sortable ~Sortable() { delete sort_; } // ~Sortable void sort(const DOM::Node<std::string>& node, Arabica::XPath::NodeSet<std::string>& nodes, ExecutionContext& context) const { if(!sort_) { if(!nodes.forward()) nodes.to_document_order(); return; } sort_->set_context(node, context); std::sort(nodes.begin(), nodes.end(), SortP(*sort_)); } // sort bool has_sort() const { return sort_ != 0; } public: void add_sort(Sort* sort) { if(!sort_) sort_ = sort; else sort_->add_sub_sort(sort); } // add_sort private: Sort* sort_; struct SortP { SortP(Sort& sort) : sort_(sort) { } bool operator()(const DOM::Node<std::string>& n1, const DOM::Node<std::string>& n2) { return sort_(n1, n2); } // operator() private: Sort& sort_; }; // struct SortP }; // class Sortable } // namespace XSLT } // namespace Arabica #endif <commit_msg>Use std::stable_sort instead of std::sort. When xsl:sort specifies a numerical sort, but you've got some string data in there we need to maintain the relative of that string data. This is the first time I've actually used std::stable_sort. I will mark it down in my big book of programming accomplishments.<commit_after>#ifndef ARABICA_XSLT_SORT_HPP #define ARABICA_XSLT_SORT_HPP #include <algorithm> #include "handler/xslt_value_validation.hpp" namespace Arabica { namespace XSLT { class Sort { public: Sort(const Arabica::XPath::XPathExpressionPtr<std::string>& select, const Arabica::XPath::XPathExpressionPtr<std::string>& lang, //="language-code" const Arabica::XPath::XPathExpressionPtr<std::string>& datatype, //="text|number|qname" const Arabica::XPath::XPathExpressionPtr<std::string>& order, //="ascending|descending" const Arabica::XPath::XPathExpressionPtr<std::string>& caseorder) : //="upper-first|lower-first select_(select), lang_(lang), datatype_(datatype), order_(order), caseorder_(caseorder), sub_sort_(0) { } // Sort ~Sort() { delete sub_sort_; } // ~Sort void set_context(const DOM::Node<std::string>& node, ExecutionContext& context) { context_ = &context; std::string datatype = datatype_->evaluateAsString(node, context_->xpathContext()); std::string order = order_->evaluateAsString(node, context_->xpathContext()); static const char* allowed_datatypes[] = { "text", "number", 0 }; static const char* allowed_orders[] = { "ascending", "descending", 0 }; validateValues("xsl:sort", "data-type", datatype, allowed_datatypes); validateValues("xsl:sort", "order", order, allowed_orders); if(datatype == "number") if(order == "ascending") sort_fn_ = &Sort::numberAscending; else sort_fn_ = &Sort::numberDescending; else if(order == "ascending") sort_fn_ = &Sort::stringAscending; else sort_fn_ = &Sort::stringDescending; if(sub_sort_) sub_sort_->set_context(node, context); } // set_context bool operator()(const DOM::Node<std::string>& n1, const DOM::Node<std::string>& n2) const { return (this->*sort_fn_)(n1, n2); } // operator() void add_sub_sort(Sort* sort) { if(!sub_sort_) sub_sort_ = sort; else sub_sort_->add_sub_sort(sort); } // add_sub_sort private: typedef bool(Sort::*sortFn)(const DOM::Node<std::string>& n1, const DOM::Node<std::string>& n2) const; bool numberAscending(const DOM::Node<std::string>& n1, const DOM::Node<std::string>& n2) const { double v1 = select_->evaluateAsNumber(n1, context_->xpathContext()); double v2 = select_->evaluateAsNumber(n2, context_->xpathContext()); bool nan1 = Arabica::XPath::isNaN(v1); bool nan2 = Arabica::XPath::isNaN(v2); if(((nan1 && nan2) || (v1 == v2)) && (sub_sort_)) return (*sub_sort_)(n1, n2); if(nan2) return false; if(nan1) return true; return v1 < v2; } // numberAscending bool numberDescending(const DOM::Node<std::string>& n1, const DOM::Node<std::string>& n2) const { double v1 = select_->evaluateAsNumber(n1, context_->xpathContext()); double v2 = select_->evaluateAsNumber(n2, context_->xpathContext()); bool nan1 = Arabica::XPath::isNaN(v1); bool nan2 = Arabica::XPath::isNaN(v2); if(((nan1 && nan2) || (v1 == v2)) && (sub_sort_)) return (*sub_sort_)(n1, n2); if(nan1) return false; if(nan2) return true; return v1 > v2; } // numberDescending bool stringAscending(const DOM::Node<std::string>& n1, const DOM::Node<std::string>& n2) const { std::string v1 = select_->evaluateAsString(n1, context_->xpathContext()); std::string v2 = select_->evaluateAsString(n2, context_->xpathContext()); if((v1 == v2) && (sub_sort_)) return (*sub_sort_)(n1, n2); return v1 < v2; } // stringAscending bool stringDescending(const DOM::Node<std::string>& n1, const DOM::Node<std::string>& n2) const { std::string v1 = select_->evaluateAsString(n1, context_->xpathContext()); std::string v2 = select_->evaluateAsString(n2, context_->xpathContext()); if((v1 == v2) && (sub_sort_)) return (*sub_sort_)(n1, n2); return v1 > v2; } // stringAscending Arabica::XPath::XPathExpressionPtr<std::string> select_; Arabica::XPath::XPathExpressionPtr<std::string> lang_; Arabica::XPath::XPathExpressionPtr<std::string> datatype_; Arabica::XPath::XPathExpressionPtr<std::string> order_; Arabica::XPath::XPathExpressionPtr<std::string> caseorder_; ExecutionContext* context_; Sort* sub_sort_; sortFn sort_fn_; Sort& operator=(const Sort&); bool operator==(const Sort&) const; }; // class Sort class Sortable { protected: Sortable() : sort_(0) { } // Sortable ~Sortable() { delete sort_; } // ~Sortable void sort(const DOM::Node<std::string>& node, Arabica::XPath::NodeSet<std::string>& nodes, ExecutionContext& context) const { if(!sort_) { if(!nodes.forward()) nodes.to_document_order(); return; } sort_->set_context(node, context); std::stable_sort(nodes.begin(), nodes.end(), SortP(*sort_)); } // sort bool has_sort() const { return sort_ != 0; } public: void add_sort(Sort* sort) { if(!sort_) sort_ = sort; else sort_->add_sub_sort(sort); } // add_sort private: Sort* sort_; struct SortP { SortP(Sort& sort) : sort_(sort) { } bool operator()(const DOM::Node<std::string>& n1, const DOM::Node<std::string>& n2) { return sort_(n1, n2); } // operator() private: Sort& sort_; }; // struct SortP }; // class Sortable } // namespace XSLT } // namespace Arabica #endif <|endoftext|>
<commit_before>#pragma once #ifndef macros_hxx #include "encoding.hxx" #define blood_is_null(x) x == 0 #define blood_is_not_null(x) != 0 #define blood_return_if(x) if (x) {return;} #if defined(BLOOD_VS) || defined(BLOOD_32) #define blood_folder_separator '\\' #else #define blood_folder_separtor '/' #endif #define blood_filename (strrchr(__FILE__, blood_folder_separator) ? strrchr(__FILE__, blood_folder_separator) + 1 : __FILE__) #define blood_code_line blood::fn::text::string_format("%s[%d]", blood_filename, __LINE__) #endif // end macros_hxx<commit_msg>fix macros<commit_after>#pragma once #ifndef macros_hxx #define blood_is_null(x) x == 0 #define blood_is_not_null(x) != 0 #define blood_return_if(x) if (x) {return;} #if defined(BLOOD_VS) || defined(BLOOD_32) #define blood_folder_separator '\\' #else #define blood_folder_separtor '/' #endif #define blood_filename (strrchr(__FILE__, blood_folder_separator) ? strrchr(__FILE__, blood_folder_separator) + 1 : __FILE__) #define blood_code_line blood::fn::text::string_format("%s[%d]", blood_filename, __LINE__) #endif // end macros_hxx<|endoftext|>
<commit_before>/* * Copyright 2012, 2013 Matthew Harvey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef GUARD_database_connection_hpp_4041979952734886 #define GUARD_database_connection_hpp_4041979952734886 #include "sqloxx_exceptions.hpp" #include <boost/filesystem/path.hpp> #include <boost/optional.hpp> #include <memory> #include <set> #include <string> #include <unordered_map> namespace sqloxx { // Forward declarations namespace detail { class SQLiteDBConn; class SQLStatementImpl; } // namespace detail /** * @class DatabaseConnection * * Represents a SQLite3 database connection. Class can be extended to provide * representations of connections to application-specific databases. */ class DatabaseConnection { public: typedef std::unordered_map < std::string, std::shared_ptr<detail::SQLStatementImpl> > StatementCache; /** * Initializes SQLite3 and creates a database connection initially * set to null, i.e. not connected to any file. * * @param p_cache_capacity indicates the number of SQLStatementImpl * instances to * be stored in a cache for reuse (via the class SQLStatement) * by the DatabaseConnection instance. * * @throws SQLiteInitializationError if initialization fails * for any reason. * * <b>Exception safety</b>: <em>strong guarantee</em>. */ explicit DatabaseConnection(StatementCache::size_type p_cache_capacity = 300); DatabaseConnection(DatabaseConnection const&) = delete; DatabaseConnection(DatabaseConnection&&) = delete; DatabaseConnection& operator=(DatabaseConnection const&) = delete; DatabaseConnection& operator=(DatabaseConnection&&) = delete; /** * <b>Exception safety</b>: <em>nothrow guarantee</em>. (Of course, the exception * safety of derived classes will depend on their own destructors.) */ virtual ~DatabaseConnection(); /** * @returns \e true if and only if the DatabaseConnection is currently * connected to a database file. * * <b>Exception safety</b>: <em>nothrow guarantee</em>. */ virtual bool is_valid() const; /** * Opens the database connection to a specific file * given by \e filename. If the file * does not already exist it is created. Note the SQLite pragma * \e foreign_keys is always executed immediately the file is opened, to * enable foreign key constraints. * * As a final step in this function, \b do_setup() is called. * This is a private virtual function which by default does nothing. * Derived classes may override it to provide their own initialization * code. * * @param p_filepath File to connect to. The is in the form of a * \c boost::filesystem::path to facilitate portability. * * @throws sqloxx::InvalidFilename if filename is an empty string. * * @throws sqloxx::MultipleConnectionException if already connected to a * database (be it this or another database). * * @throws SQLiteException or an exception derived therefrom (likely, but * not guaranteed, to be SQLiteCantOpen) if for some other reason the * connection cannot be opened. * * <b>Exception safety</b>: appears to offer the <em>basic guarantee</em>, * <em>however</em> this has not been properly tested. This wraps * a SQLite function for which the error-safety is not clear. If the * derived class overrides \b do_setup(), then this may affect exception * safety, since \b do_setup() is called by the open() function. */ void open(boost::filesystem::path const& p_filepath); /** * Executes a string as an SQL command on the database connection. * This should be used only where the developer has complete * control of the string being passed, to prevent SQL injection * attacks. Generally, the functions provided by SQLStatement should * be the preferred means for building and executing SQL statements. * * @throws DatabaseException or some exception inheriting thereof, * whenever * there is any kind of error executing the statement. * * @throws InvalidConnection if the database connection is invalid. * * <b>Exception safety</b>: <em>basic guarantee</em>. (Possibly also offers * strong guarantee, but not certain.) */ void execute_sql(std::string const& str); /** * Creates table containing integers representing boolean values. * This might be used to provide foreign key constraints for other * tables where we wish a particular column to have boolean values * only. * * The table is called "booleans" and has one column, an integer * primary key field named "representation". There are * two rows, one with 0 in the "representation" column, representing * \e false, and the other with 1, representing \e true. * * @throws InvalidConnection if the database connection is invalid (e.g. * not connected to a file). * * @throws SQLiteException or an exception inheriting therefrom, if there * is some other error setting up the table (should be rare). For example, * if the table has been set up already. * * <b>Exception safety</b>: <em>strong guarantee</em>. */ void setup_boolean_table(); /** * @returns maximum level of transaction nesting. * * <b>Exception safety</b>: <em>nothrow guarantee</em>. */ static int max_nesting(); /** * @returns an absolute filepath corresponding to the filepath to * which the database connection was last opened. * * @throws InvalidConnection if the database connection * has not been opened to a file, or if the database connection * is otherwise invalid. */ boost::filesystem::path filepath() const; ///@cond /** * Controls access to DatabaseConnection::provide_sql_statement, * deliberately limiting this access to the class SQLStatement. */ class StatementAttorney { public: friend class SQLStatement; private: static std::shared_ptr<detail::SQLStatementImpl> provide_sql_statement ( DatabaseConnection& p_database_connection, std::string const& p_statement_text ); }; friend class StatementAttorney; /** * Controls access to the database transaction control facilities * of DatabaseConnection, deliberately * limiting this access to the class DatabaseTransaction. */ class TransactionAttorney { public: friend class DatabaseTransaction; private: static void begin_transaction ( DatabaseConnection& p_database_connection ); static void end_transaction ( DatabaseConnection& p_database_connection ); static void cancel_transaction ( DatabaseConnection& p_database_connection ); }; friend class TransactionAttorney; // Self-test function, returns a number indicating the number of // test failures. 0 means all pass. This is not intended to test // all functions - conventional unit tests take care of that - but // only to test aspects of DatabaseConnection that are difficult // to test without accessing private functions and data. int self_test(); ///@endcond private: /** * See documentation for open(). * * Note, do_setup \e is able to call filepath() if required, as * m_filepath is initialized with open(...) prior to do_setup() being * entered. */ virtual void do_setup(); /** * @returns a shared pointer to a SQLStatementImpl. This will * either point to an existing SQLStatementImpl that is cached within * the DatabaseConnection (if a SQLStatementImpl with \c * statement_text has already been created on this DatabaseConnection and * is not being used elsewhere), or * will be a pointer to a newly created and new cached SQLStatementImpl * (if a * SQLStatementImpl with \c statement_text has not yet been created * on this * DatabaseConnection, or it has been created but is being used * elsewhere). * * This function is only intended to be called by * during construction of an SQLStatement. It should not be called * elsewhere. * * @throws InvalidConnection if p_database_connection is an invalid * connection. * * @throws SQLiteException, or an exception derived therefrom, if there * is some other problem in preparing the statement, which results in a * SQLite error code (that is not SQLITE_OK) being returned. * * @throws TooManyStatements if the first purported SQL statement * in str is syntactically acceptable to SQLite, <em>but</em> there * are characters in str after this statement, other than ';' and ' '. * This includes the case where there are further syntactically * acceptable SQL statements after the first one - as each * SQLStatementImpl can encapsulate only one statement. * * @throws std::bad_alloc in the extremely unlikely event of memory * allocation failure in execution. * * <b>Exception safety</b>: <em>strong guarantee</em>. */ std::shared_ptr<detail::SQLStatementImpl> provide_sql_statement ( std::string const& statement_text ); /** * Begins a SQL transaction. Transactions may be nested. Only the * outermost call to begin_transaction causes the "begin transaction" * SQL command to be executed. Inner calls instead cause a * transaction savepoint to be set (see SQLite documentation * re. savepoints). * * SQL transactions should be controlled either solely through the * methods begin_transaction and end_transaction, \e or solely through * the direct execution of SQL statement strings "begin transaction" and * "end transaction". Mixing the two will result in undefined behaviour. * * @throws TransactionNestingException in the event that the maximum * level of nesting has been reached. The maximum level of nesting is * equal to the value returned by max_nesting(); * * @throws InvalidConnection if the database connection is invalid. * * @throws std::bad_alloc in the extremely unlikely event of a memory * allocation error in execution. * * <b>Exception safety</b>: the <em>strong guarantee</em> is provided, on * the condition that the control of SQL transactions is managed * entirely by calls to begin_transaction(), end_transaction() and * canced_transaction(), rather than by executing the corresponding * SQL commands directly. */ void begin_transaction(); /** * Ends a SQL transaction. Transactions may be nested. Only the outermost * call to end_transaction causes the "end transaction" SQL command * to be executed. Inner calls cause the previous savepoint to be * released (see SQLite documentation re. savepoints). * * @throws TransactionNestingException in the event that there are * more calls to end_transaction than there have been to * begin_transaction - in other words, there are no active * transactions. * * @throws InvalidConnection if the database connection is invalid. * * @throws std::bad_alloc in the extremely unlikely event of a memory * allocation error in execution. * * <b>Exception safety</b>: as per begin_transaction(). */ void end_transaction(); /** * Cancels a SQL transaction. If the active transaction is an * outermost transaction, i.e. there is no nesting in the current * transaction, then this causes the entire transaction to be rolled * back. Otherwise, it causes a rollback to the last savepoint, AND * the release of that savepoint. (See SQLite documentation for * explanation of rollbacks, savepoints and releases of savepoints.) * * @throws TransactionNestingException if there is no open active * transaction. * * @throws InvalidConnection if the database connection is invalid. * * @throws std::bad_alloc in the very unlikely event of a memory * allocation failure in execution. * * <b>Exception safety</b>: as per begin_transaction(). */ void cancel_transaction(); void unchecked_begin_transaction(); void unchecked_end_transaction(); void unchecked_set_savepoint(); void unchecked_release_savepoint(); void unchecked_rollback_transaction(); void unchecked_rollback_to_savepoint(); std::unique_ptr<detail::SQLiteDBConn> m_sqlite_dbconn; // s_max_nesting relies on m_transaction_nesting_level being an int int m_transaction_nesting_level; static int const s_max_nesting; StatementCache m_statement_cache; StatementCache::size_type m_cache_capacity; boost::optional<boost::filesystem::path> m_filepath; }; /// @cond inline std::shared_ptr<detail::SQLStatementImpl> DatabaseConnection::StatementAttorney::provide_sql_statement ( DatabaseConnection& p_database_connection, std::string const& p_statement_text ) { return p_database_connection.provide_sql_statement ( p_statement_text ); } inline void DatabaseConnection::TransactionAttorney::begin_transaction ( DatabaseConnection& p_database_connection ) { p_database_connection.begin_transaction(); return; } inline void DatabaseConnection::TransactionAttorney::end_transaction ( DatabaseConnection& p_database_connection ) { p_database_connection.end_transaction(); return; } inline void DatabaseConnection::TransactionAttorney::cancel_transaction ( DatabaseConnection& p_database_connection ) { p_database_connection.cancel_transaction(); return; } /// @endcond } // namespace sqloxx #endif // GUARD_database_connection_hpp_4041979952734886 <commit_msg>Minor documentation edit.<commit_after>/* * Copyright 2012, 2013 Matthew Harvey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef GUARD_database_connection_hpp_4041979952734886 #define GUARD_database_connection_hpp_4041979952734886 #include "sqloxx_exceptions.hpp" #include <boost/filesystem/path.hpp> #include <boost/optional.hpp> #include <memory> #include <set> #include <string> #include <unordered_map> namespace sqloxx { // Forward declarations namespace detail { class SQLiteDBConn; class SQLStatementImpl; } // namespace detail /** * @class DatabaseConnection * * Represents a SQLite3 database connection. Class can be extended to provide * representations of connections to application-specific databases. */ class DatabaseConnection { public: typedef std::unordered_map < std::string, std::shared_ptr<detail::SQLStatementImpl> > StatementCache; /** * Initializes SQLite3 if not already initialized, and creates a database * connection initially set to null, i.e. not connected to any file. * * @param p_cache_capacity indicates the number of SQLStatementImpl * instances to * be stored in a cache for reuse (via the class SQLStatement) * by the DatabaseConnection instance. * * @throws SQLiteInitializationError if initialization fails * for any reason. * * <b>Exception safety</b>: <em>strong guarantee</em>. */ explicit DatabaseConnection(StatementCache::size_type p_cache_capacity = 300); DatabaseConnection(DatabaseConnection const&) = delete; DatabaseConnection(DatabaseConnection&&) = delete; DatabaseConnection& operator=(DatabaseConnection const&) = delete; DatabaseConnection& operator=(DatabaseConnection&&) = delete; /** * <b>Exception safety</b>: <em>nothrow guarantee</em>. (Of course, the * exception safety of derived classes will depend on their own * destructors.) */ virtual ~DatabaseConnection(); /** * @returns \e true if and only if the DatabaseConnection is currently * connected to a database file. * * <b>Exception safety</b>: <em>nothrow guarantee</em>. */ virtual bool is_valid() const; /** * Opens the database connection to a specific file * given by \e filename. If the file * does not already exist it is created. Note the SQLite pragma * \e foreign_keys is always executed immediately the file is opened, to * enable foreign key constraints. * * As a final step in this function, \b do_setup() is called. * This is a private virtual function which by default does nothing. * Derived classes may override it to provide their own initialization * code. * * @param p_filepath File to connect to. The is in the form of a * \c boost::filesystem::path to facilitate portability. * * @throws sqloxx::InvalidFilename if filename is an empty string. * * @throws sqloxx::MultipleConnectionException if already connected to a * database (be it this or another database). * * @throws SQLiteException or an exception derived therefrom (likely, but * not guaranteed, to be SQLiteCantOpen) if for some other reason the * connection cannot be opened. * * <b>Exception safety</b>: appears to offer the <em>basic guarantee</em>, * <em>however</em> this has not been properly tested. This wraps * a SQLite function for which the error-safety is not clear. If the * derived class overrides \b do_setup(), then this may affect exception * safety, since \b do_setup() is called by the open() function. */ void open(boost::filesystem::path const& p_filepath); /** * Executes a string as an SQL command on the database connection. * This should be used only where the developer has complete * control of the string being passed, to prevent SQL injection * attacks. Generally, the functions provided by SQLStatement should * be the preferred means for building and executing SQL statements. * * @throws DatabaseException or some exception inheriting thereof, * whenever * there is any kind of error executing the statement. * * @throws InvalidConnection if the database connection is invalid. * * <b>Exception safety</b>: <em>basic guarantee</em>. (Possibly also offers * strong guarantee, but not certain.) */ void execute_sql(std::string const& str); /** * Creates table containing integers representing boolean values. * This might be used to provide foreign key constraints for other * tables where we wish a particular column to have boolean values * only. * * The table is called "booleans" and has one column, an integer * primary key field named "representation". There are * two rows, one with 0 in the "representation" column, representing * \e false, and the other with 1, representing \e true. * * @throws InvalidConnection if the database connection is invalid (e.g. * not connected to a file). * * @throws SQLiteException or an exception inheriting therefrom, if there * is some other error setting up the table (should be rare). For example, * if the table has been set up already. * * <b>Exception safety</b>: <em>strong guarantee</em>. */ void setup_boolean_table(); /** * @returns maximum level of transaction nesting. * * <b>Exception safety</b>: <em>nothrow guarantee</em>. */ static int max_nesting(); /** * @returns an absolute filepath corresponding to the filepath to * which the database connection was last opened. * * @throws InvalidConnection if the database connection * has not been opened to a file, or if the database connection * is otherwise invalid. */ boost::filesystem::path filepath() const; ///@cond /** * Controls access to DatabaseConnection::provide_sql_statement, * deliberately limiting this access to the class SQLStatement. */ class StatementAttorney { public: friend class SQLStatement; private: static std::shared_ptr<detail::SQLStatementImpl> provide_sql_statement ( DatabaseConnection& p_database_connection, std::string const& p_statement_text ); }; friend class StatementAttorney; /** * Controls access to the database transaction control facilities * of DatabaseConnection, deliberately * limiting this access to the class DatabaseTransaction. */ class TransactionAttorney { public: friend class DatabaseTransaction; private: static void begin_transaction ( DatabaseConnection& p_database_connection ); static void end_transaction ( DatabaseConnection& p_database_connection ); static void cancel_transaction ( DatabaseConnection& p_database_connection ); }; friend class TransactionAttorney; // Self-test function, returns a number indicating the number of // test failures. 0 means all pass. This is not intended to test // all functions - conventional unit tests take care of that - but // only to test aspects of DatabaseConnection that are difficult // to test without accessing private functions and data. int self_test(); ///@endcond private: /** * See documentation for open(). * * Note, do_setup \e is able to call filepath() if required, as * m_filepath is initialized with open(...) prior to do_setup() being * entered. */ virtual void do_setup(); /** * @returns a shared pointer to a SQLStatementImpl. This will * either point to an existing SQLStatementImpl that is cached within * the DatabaseConnection (if a SQLStatementImpl with \c * statement_text has already been created on this DatabaseConnection and * is not being used elsewhere), or * will be a pointer to a newly created and new cached SQLStatementImpl * (if a * SQLStatementImpl with \c statement_text has not yet been created * on this * DatabaseConnection, or it has been created but is being used * elsewhere). * * This function is only intended to be called by * during construction of an SQLStatement. It should not be called * elsewhere. * * @throws InvalidConnection if p_database_connection is an invalid * connection. * * @throws SQLiteException, or an exception derived therefrom, if there * is some other problem in preparing the statement, which results in a * SQLite error code (that is not SQLITE_OK) being returned. * * @throws TooManyStatements if the first purported SQL statement * in str is syntactically acceptable to SQLite, <em>but</em> there * are characters in str after this statement, other than ';' and ' '. * This includes the case where there are further syntactically * acceptable SQL statements after the first one - as each * SQLStatementImpl can encapsulate only one statement. * * @throws std::bad_alloc in the extremely unlikely event of memory * allocation failure in execution. * * <b>Exception safety</b>: <em>strong guarantee</em>. */ std::shared_ptr<detail::SQLStatementImpl> provide_sql_statement ( std::string const& statement_text ); /** * Begins a SQL transaction. Transactions may be nested. Only the * outermost call to begin_transaction causes the "begin transaction" * SQL command to be executed. Inner calls instead cause a * transaction savepoint to be set (see SQLite documentation * re. savepoints). * * SQL transactions should be controlled either solely through the * methods begin_transaction and end_transaction, \e or solely through * the direct execution of SQL statement strings "begin transaction" and * "end transaction". Mixing the two will result in undefined behaviour. * * @throws TransactionNestingException in the event that the maximum * level of nesting has been reached. The maximum level of nesting is * equal to the value returned by max_nesting(); * * @throws InvalidConnection if the database connection is invalid. * * @throws std::bad_alloc in the extremely unlikely event of a memory * allocation error in execution. * * <b>Exception safety</b>: the <em>strong guarantee</em> is provided, on * the condition that the control of SQL transactions is managed * entirely by calls to begin_transaction(), end_transaction() and * canced_transaction(), rather than by executing the corresponding * SQL commands directly. */ void begin_transaction(); /** * Ends a SQL transaction. Transactions may be nested. Only the outermost * call to end_transaction causes the "end transaction" SQL command * to be executed. Inner calls cause the previous savepoint to be * released (see SQLite documentation re. savepoints). * * @throws TransactionNestingException in the event that there are * more calls to end_transaction than there have been to * begin_transaction - in other words, there are no active * transactions. * * @throws InvalidConnection if the database connection is invalid. * * @throws std::bad_alloc in the extremely unlikely event of a memory * allocation error in execution. * * <b>Exception safety</b>: as per begin_transaction(). */ void end_transaction(); /** * Cancels a SQL transaction. If the active transaction is an * outermost transaction, i.e. there is no nesting in the current * transaction, then this causes the entire transaction to be rolled * back. Otherwise, it causes a rollback to the last savepoint, AND * the release of that savepoint. (See SQLite documentation for * explanation of rollbacks, savepoints and releases of savepoints.) * * @throws TransactionNestingException if there is no open active * transaction. * * @throws InvalidConnection if the database connection is invalid. * * @throws std::bad_alloc in the very unlikely event of a memory * allocation failure in execution. * * <b>Exception safety</b>: as per begin_transaction(). */ void cancel_transaction(); void unchecked_begin_transaction(); void unchecked_end_transaction(); void unchecked_set_savepoint(); void unchecked_release_savepoint(); void unchecked_rollback_transaction(); void unchecked_rollback_to_savepoint(); std::unique_ptr<detail::SQLiteDBConn> m_sqlite_dbconn; // s_max_nesting relies on m_transaction_nesting_level being an int int m_transaction_nesting_level; static int const s_max_nesting; StatementCache m_statement_cache; StatementCache::size_type m_cache_capacity; boost::optional<boost::filesystem::path> m_filepath; }; /// @cond inline std::shared_ptr<detail::SQLStatementImpl> DatabaseConnection::StatementAttorney::provide_sql_statement ( DatabaseConnection& p_database_connection, std::string const& p_statement_text ) { return p_database_connection.provide_sql_statement ( p_statement_text ); } inline void DatabaseConnection::TransactionAttorney::begin_transaction ( DatabaseConnection& p_database_connection ) { p_database_connection.begin_transaction(); return; } inline void DatabaseConnection::TransactionAttorney::end_transaction ( DatabaseConnection& p_database_connection ) { p_database_connection.end_transaction(); return; } inline void DatabaseConnection::TransactionAttorney::cancel_transaction ( DatabaseConnection& p_database_connection ) { p_database_connection.cancel_transaction(); return; } /// @endcond } // namespace sqloxx #endif // GUARD_database_connection_hpp_4041979952734886 <|endoftext|>
<commit_before>/** * \file * \brief FifoQueue class header * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2014-12-11 */ #ifndef INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ #define INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ #include "distortos/scheduler/FifoQueueBase.hpp" namespace distortos { /** * \brief FifoQueue class is a simple FIFO queue for thread-thread, thread-interrupt or interrupt-interrupt * communication. It supports multiple readers and multiple writers. It is implemented as a thin wrapper for * scheduler::FifoQueueBase. * * \param T is the type of data in queue */ template<typename T> class FifoQueue { public: /// type of uninitialized storage for data using Storage = scheduler::FifoQueueBase::Storage<T>; /** * \brief FifoQueue's constructor * * \param [in] storage is an array of Storage elements * \param [in] maxElements is the number of elements in storage array */ FifoQueue(Storage* const storage, const size_t maxElements) : fifoQueueBase_{storage, maxElements, scheduler::FifoQueueBase::TypeTag<T>{}} { } /** * \brief Pops the oldest (first) element from the queue. * * Wrapper for scheduler::FifoQueueBase::pop(T&) * * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int pop(T& value) { return fifoQueueBase_.pop(value); } /** * \brief Pushes the element to the queue. * * Wrapper for scheduler::FifoQueueBase::push(const T&) * * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int push(const T& value) { return fifoQueueBase_.push(value); } /** * \brief Pushes the element to the queue. * * Wrapper for scheduler::FifoQueueBase::push(T&&) * * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int push(T&& value) { return fifoQueueBase_.push(std::move(value)); } /** * \brief Tries to pop the oldest (first) element from the queue. * * Wrapper for scheduler::FifoQueueBase::tryPop(T&) * * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPop(T& value) { return fifoQueueBase_.tryPop(value); } /** * \brief Tries to pop the oldest (first) element from the queue for a given duration of time. * * Wrapper for scheduler::FifoQueueBase::tryPopFor(TickClock::duration, T&) * * \param [in] duration is the duration after which the call will be terminated without popping the element * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitFor(); * - error codes returned by Semaphore::post(); */ int tryPopFor(const TickClock::duration duration, T& value) { return fifoQueueBase_.tryPopFor(duration, value); } /** * \brief Tries to pop the oldest (first) element from the queue for a given duration of time. * * Template variant of tryPopFor(TickClock::duration, T&). * * \param Rep is type of tick counter * \param Period is std::ratio type representing the tick period of the clock, in seconds * * \param [in] duration is the duration after which the call will be terminated without popping the element * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitFor(); * - error codes returned by Semaphore::post(); */ template<typename Rep, typename Period> int tryPopFor(const std::chrono::duration<Rep, Period> duration, T& value) { return tryPopFor(std::chrono::duration_cast<TickClock::duration>(duration), value); } /** * \brief Tries to pop the oldest (first) element from the queue until a given time point. * * Wrapper for scheduler::FifoQueueBase::tryPopUntil(TickClock::time_point, T&) * * \param [in] timePoint is the time point at which the call will be terminated without popping the element * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitUntil(); * - error codes returned by Semaphore::post(); */ int tryPopUntil(const TickClock::time_point timePoint, T& value) { return fifoQueueBase_.tryPopUntil(timePoint, value); } /** * \brief Tries to push the element to the queue. * * Wrapper for scheduler::FifoQueueBase::tryPush(const T&) * * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPush(const T& value) { return fifoQueueBase_.tryPush(value); } /** * \brief Tries to push the element to the queue. * * Wrapper for scheduler::FifoQueueBase::tryPush(T&&) * * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPush(T&& value) { return fifoQueueBase_.tryPush(std::move(value)); } /** * \brief Tries to push the element to the queue for a given duration of time. * * Wrapper for scheduler::FifoQueueBase::tryPushFor(TickClock::duration, const T&) * * \param [in] duration is the duration after which the wait will be terminated without pushing the element * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitFor(); * - error codes returned by Semaphore::post(); */ int tryPushFor(const TickClock::duration duration, const T& value) { return fifoQueueBase_.tryPushFor(duration, value); } /** * \brief Tries to push the element to the queue for a given duration of time. * * Wrapper for scheduler::FifoQueueBase::tryPushFor(TickClock::duration, T&&) * * \param [in] duration is the duration after which the call will be terminated without pushing the element * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitFor(); * - error codes returned by Semaphore::post(); */ int tryPushFor(const TickClock::duration duration, T&& value) { return fifoQueueBase_.tryPushFor(duration, std::move(value)); } /** * \brief Tries to push the element to the queue until a given time point. * * Wrapper for scheduler::FifoQueueBase::tryPushUntil(TickClock::time_point, const T&) * * \param [in] timePoint is the time point at which the call will be terminated without pushing the element * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitUntil(); * - error codes returned by Semaphore::post(); */ int tryPushUntil(const TickClock::time_point timePoint, const T& value) { return fifoQueueBase_.tryPushUntil(timePoint, value); } /** * \brief Tries to push the element to the queue until a given time point. * * Wrapper for scheduler::FifoQueueBase::tryPushUntil(TickClock::time_point, T&&) * * \param [in] timePoint is the time point at which the call will be terminated without pushing the element * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitUntil(); * - error codes returned by Semaphore::post(); */ int tryPushUntil(const TickClock::time_point timePoint, T&& value) { return fifoQueueBase_.tryPushUntil(timePoint, std::move(value)); } private: /// contained scheduler::FifoQueueBase object which implements whole functionality scheduler::FifoQueueBase fifoQueueBase_; }; } // namespace distortos #endif // INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ <commit_msg>FifoQueue: add template variant of FifoQueue::tryPushFor(TickClock::duration, const T&)<commit_after>/** * \file * \brief FifoQueue class header * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2014-12-11 */ #ifndef INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ #define INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ #include "distortos/scheduler/FifoQueueBase.hpp" namespace distortos { /** * \brief FifoQueue class is a simple FIFO queue for thread-thread, thread-interrupt or interrupt-interrupt * communication. It supports multiple readers and multiple writers. It is implemented as a thin wrapper for * scheduler::FifoQueueBase. * * \param T is the type of data in queue */ template<typename T> class FifoQueue { public: /// type of uninitialized storage for data using Storage = scheduler::FifoQueueBase::Storage<T>; /** * \brief FifoQueue's constructor * * \param [in] storage is an array of Storage elements * \param [in] maxElements is the number of elements in storage array */ FifoQueue(Storage* const storage, const size_t maxElements) : fifoQueueBase_{storage, maxElements, scheduler::FifoQueueBase::TypeTag<T>{}} { } /** * \brief Pops the oldest (first) element from the queue. * * Wrapper for scheduler::FifoQueueBase::pop(T&) * * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int pop(T& value) { return fifoQueueBase_.pop(value); } /** * \brief Pushes the element to the queue. * * Wrapper for scheduler::FifoQueueBase::push(const T&) * * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int push(const T& value) { return fifoQueueBase_.push(value); } /** * \brief Pushes the element to the queue. * * Wrapper for scheduler::FifoQueueBase::push(T&&) * * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int push(T&& value) { return fifoQueueBase_.push(std::move(value)); } /** * \brief Tries to pop the oldest (first) element from the queue. * * Wrapper for scheduler::FifoQueueBase::tryPop(T&) * * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPop(T& value) { return fifoQueueBase_.tryPop(value); } /** * \brief Tries to pop the oldest (first) element from the queue for a given duration of time. * * Wrapper for scheduler::FifoQueueBase::tryPopFor(TickClock::duration, T&) * * \param [in] duration is the duration after which the call will be terminated without popping the element * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitFor(); * - error codes returned by Semaphore::post(); */ int tryPopFor(const TickClock::duration duration, T& value) { return fifoQueueBase_.tryPopFor(duration, value); } /** * \brief Tries to pop the oldest (first) element from the queue for a given duration of time. * * Template variant of tryPopFor(TickClock::duration, T&). * * \param Rep is type of tick counter * \param Period is std::ratio type representing the tick period of the clock, in seconds * * \param [in] duration is the duration after which the call will be terminated without popping the element * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitFor(); * - error codes returned by Semaphore::post(); */ template<typename Rep, typename Period> int tryPopFor(const std::chrono::duration<Rep, Period> duration, T& value) { return tryPopFor(std::chrono::duration_cast<TickClock::duration>(duration), value); } /** * \brief Tries to pop the oldest (first) element from the queue until a given time point. * * Wrapper for scheduler::FifoQueueBase::tryPopUntil(TickClock::time_point, T&) * * \param [in] timePoint is the time point at which the call will be terminated without popping the element * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitUntil(); * - error codes returned by Semaphore::post(); */ int tryPopUntil(const TickClock::time_point timePoint, T& value) { return fifoQueueBase_.tryPopUntil(timePoint, value); } /** * \brief Tries to push the element to the queue. * * Wrapper for scheduler::FifoQueueBase::tryPush(const T&) * * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPush(const T& value) { return fifoQueueBase_.tryPush(value); } /** * \brief Tries to push the element to the queue. * * Wrapper for scheduler::FifoQueueBase::tryPush(T&&) * * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPush(T&& value) { return fifoQueueBase_.tryPush(std::move(value)); } /** * \brief Tries to push the element to the queue for a given duration of time. * * Wrapper for scheduler::FifoQueueBase::tryPushFor(TickClock::duration, const T&) * * \param [in] duration is the duration after which the wait will be terminated without pushing the element * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitFor(); * - error codes returned by Semaphore::post(); */ int tryPushFor(const TickClock::duration duration, const T& value) { return fifoQueueBase_.tryPushFor(duration, value); } /** * \brief Tries to push the element to the queue for a given duration of time. * * Template variant of tryPushFor(TickClock::duration, const T&). * * \param Rep is type of tick counter * \param Period is std::ratio type representing the tick period of the clock, in seconds * * \param [in] duration is the duration after which the wait will be terminated without pushing the element * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitFor(); * - error codes returned by Semaphore::post(); */ template<typename Rep, typename Period> int tryPushFor(const std::chrono::duration<Rep, Period> duration, const T& value) { return tryPushFor(std::chrono::duration_cast<TickClock::duration>(duration), value); } /** * \brief Tries to push the element to the queue for a given duration of time. * * Wrapper for scheduler::FifoQueueBase::tryPushFor(TickClock::duration, T&&) * * \param [in] duration is the duration after which the call will be terminated without pushing the element * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitFor(); * - error codes returned by Semaphore::post(); */ int tryPushFor(const TickClock::duration duration, T&& value) { return fifoQueueBase_.tryPushFor(duration, std::move(value)); } /** * \brief Tries to push the element to the queue until a given time point. * * Wrapper for scheduler::FifoQueueBase::tryPushUntil(TickClock::time_point, const T&) * * \param [in] timePoint is the time point at which the call will be terminated without pushing the element * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitUntil(); * - error codes returned by Semaphore::post(); */ int tryPushUntil(const TickClock::time_point timePoint, const T& value) { return fifoQueueBase_.tryPushUntil(timePoint, value); } /** * \brief Tries to push the element to the queue until a given time point. * * Wrapper for scheduler::FifoQueueBase::tryPushUntil(TickClock::time_point, T&&) * * \param [in] timePoint is the time point at which the call will be terminated without pushing the element * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitUntil(); * - error codes returned by Semaphore::post(); */ int tryPushUntil(const TickClock::time_point timePoint, T&& value) { return fifoQueueBase_.tryPushUntil(timePoint, std::move(value)); } private: /// contained scheduler::FifoQueueBase object which implements whole functionality scheduler::FifoQueueBase fifoQueueBase_; }; } // namespace distortos #endif // INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ <|endoftext|>
<commit_before>#include <string> #include <map> namespace dota2 { const auto MATCHHISTORY_API = "IDOTA2Match_570/GetMatchHistory/V1/"; const auto MATCHDETAILS_API = "IDOTA2Match_570/GetMatchDetails/V1/"; const auto HEROES_API = "IEconDOTA2_570/GetHeroes/V1/"; const auto ITEMS_API = "IEconDOTA2_570/GetGameItems/V1/"; const auto API_SERVER = "https://api.steampowered.com"; typedef std::map<std::string, std::string> Query; class APIRequest { public: APIRequest(const std::string &request, const std::string &key, const Query &query = Query()); APIRequest(const std::string &url); void setUrl(const std::string &url); std::string getUrl(); std::string runRequest(); private: static std::string urlEncode(const std::string &value); std::string url; }; } <commit_msg>Add include guards to apirequest<commit_after>#ifndef APIREQUEST_HPP_R9YKDL8S #define APIREQUEST_HPP_R9YKDL8S #include <string> #include <map> namespace dota2 { const auto MATCHHISTORY_API = "IDOTA2Match_570/GetMatchHistory/V1/"; const auto MATCHDETAILS_API = "IDOTA2Match_570/GetMatchDetails/V1/"; const auto HEROES_API = "IEconDOTA2_570/GetHeroes/V1/"; const auto ITEMS_API = "IEconDOTA2_570/GetGameItems/V1/"; const auto API_SERVER = "https://api.steampowered.com"; typedef std::map<std::string, std::string> Query; class APIRequest { public: APIRequest(const std::string &request, const std::string &key, const Query &query = Query()); APIRequest(const std::string &url); void setUrl(const std::string &url); std::string getUrl(); std::string runRequest(); private: static std::string urlEncode(const std::string &value); std::string url; }; } #endif /* end of include guard: APIREQUEST_HPP_R9YKDL8S */ <|endoftext|>
<commit_before>/* Copyright (c) 2009-2011, Jack Poulson All rights reserved. This file is part of Elemental. 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 owner nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ELEMENTAL_UTILITIES_HPP #define ELEMENTAL_UTILITIES_HPP 1 namespace elemental { namespace utilities { // The 'Raw' versions of the below routines do not check for errors and can // be used within threaded regions. int GCD ( int a, int b ); int RawGCD ( int a, int b ); int LocalLength ( int n, int shift, int modulus ); int RawLocalLength ( int n, int shift, int modulus ); int LocalLength ( int n, int index, int alignment, int modulus ); int RawLocalLength ( int n, int index, int alignment, int modulus ); int MaxLocalLength ( int n, int modulus ); int RawMaxLocalLength ( int n, int modulus ); int Shift ( int index, int alignment, int modulus ); int RawShift ( int index, int alignment, int modulus ); } // utilities } // elemental //----------------------------------------------------------------------------// // Implementation begins here // //----------------------------------------------------------------------------// inline int elemental::utilities::GCD ( int a, int b ) { #ifndef RELEASE if( a < 0 || b < 0 ) throw std::logic_error( "GCD called with negative argument." ); #endif return elemental::utilities::RawGCD( a, b ); } inline int elemental::utilities::RawGCD( int a, int b ) { if( b == 0 ) return a; else return GCD( b, a-b*(a/b) ); } inline int elemental::utilities::LocalLength ( int n, int shift, int modulus ) { #ifndef RELEASE PushCallStack("utilities::LocalLength"); if( n < 0 ) throw std::logic_error( "n must be non-negative." ); if( shift < 0 || shift >= modulus ) { std::ostringstream msg; msg << "Invalid shift: " << "shift=" << shift << ", modulus=" << modulus; throw std::logic_error( msg.str() ); } if( modulus <= 0 ) throw std::logic_error( "Modulus must be positive." ); PopCallStack(); #endif return elemental::utilities::RawLocalLength( n, shift, modulus ); } inline int elemental::utilities::RawLocalLength ( int n, int shift, int modulus ) { return ( n > shift ? (n - shift - 1)/modulus + 1 : 0 ); } inline int elemental::utilities::LocalLength ( int n, int index, int alignment, int modulus ) { #ifndef RELEASE PushCallStack("utilities::LocalLength"); #endif int shift = Shift( index, alignment, modulus ); int localLength = LocalLength( n, shift, modulus ); #ifndef RELEASE PopCallStack(); #endif return localLength; } inline int elemental::utilities::RawLocalLength ( int n, int index, int alignment, int modulus ) { int shift = RawShift( index, alignment, modulus ); int localLength = RawLocalLength( n, shift, modulus ); return localLength; } inline int elemental::utilities::MaxLocalLength ( int n, int modulus ) { #ifndef RELEASE PushCallStack("utilities::MaxLocalLength"); if( n < 0 ) throw std::logic_error( "n must be non-negative." ); if( modulus <= 0 ) throw std::logic_error( "Modulus must be positive." ); PopCallStack(); #endif return elemental::utilities::RawMaxLocalLength( n, modulus ); } inline int elemental::utilities::RawMaxLocalLength ( int n, int modulus ) { return ( n > 0 ? (n - 1)/modulus + 1 : 0 ); } // For determining the first global element of process row/column // 'index', with distribution alignment 'alignment' and number of process // rows/cols 'modulus' inline int elemental::utilities::Shift ( int index, int alignment, int modulus ) { #ifndef RELEASE PushCallStack("utilities::Shift"); if( index < 0 || index >= modulus ) { std::ostringstream msg; msg << "Invalid index: " << "index=" << index << ", modulus=" << modulus; throw std::logic_error( msg.str() ); } if( alignment < 0 || alignment >= modulus ) { std::ostringstream msg; msg << "Invalid alignment: " << "alignment=" << alignment << ", modulus=" << modulus; throw std::logic_error( msg.str() ); } if( modulus <= 0 ) throw std::logic_error( "Modulus must be positive." ); PopCallStack(); #endif return elemental::utilities::RawShift( index, alignment, modulus ); } inline int elemental::utilities::RawShift ( int index, int alignment, int modulus ) { return (index + modulus - alignment) % modulus; } #endif /* ELEMENTAL_UTILITIES_HPP */ <commit_msg>Removing accidental recursive call to GCD within RawGCD.<commit_after>/* Copyright (c) 2009-2011, Jack Poulson All rights reserved. This file is part of Elemental. 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 owner nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ELEMENTAL_UTILITIES_HPP #define ELEMENTAL_UTILITIES_HPP 1 namespace elemental { namespace utilities { // The 'Raw' versions of the below routines do not check for errors and can // be used within threaded regions. int GCD ( int a, int b ); int RawGCD ( int a, int b ); int LocalLength ( int n, int shift, int modulus ); int RawLocalLength ( int n, int shift, int modulus ); int LocalLength ( int n, int index, int alignment, int modulus ); int RawLocalLength ( int n, int index, int alignment, int modulus ); int MaxLocalLength ( int n, int modulus ); int RawMaxLocalLength ( int n, int modulus ); int Shift ( int index, int alignment, int modulus ); int RawShift ( int index, int alignment, int modulus ); } // utilities } // elemental //----------------------------------------------------------------------------// // Implementation begins here // //----------------------------------------------------------------------------// inline int elemental::utilities::GCD ( int a, int b ) { #ifndef RELEASE if( a < 0 || b < 0 ) throw std::logic_error( "GCD called with negative argument." ); #endif return elemental::utilities::RawGCD( a, b ); } inline int elemental::utilities::RawGCD( int a, int b ) { if( b == 0 ) return a; else return RawGCD( b, a-b*(a/b) ); } inline int elemental::utilities::LocalLength ( int n, int shift, int modulus ) { #ifndef RELEASE PushCallStack("utilities::LocalLength"); if( n < 0 ) throw std::logic_error( "n must be non-negative." ); if( shift < 0 || shift >= modulus ) { std::ostringstream msg; msg << "Invalid shift: " << "shift=" << shift << ", modulus=" << modulus; throw std::logic_error( msg.str() ); } if( modulus <= 0 ) throw std::logic_error( "Modulus must be positive." ); PopCallStack(); #endif return elemental::utilities::RawLocalLength( n, shift, modulus ); } inline int elemental::utilities::RawLocalLength ( int n, int shift, int modulus ) { return ( n > shift ? (n - shift - 1)/modulus + 1 : 0 ); } inline int elemental::utilities::LocalLength ( int n, int index, int alignment, int modulus ) { #ifndef RELEASE PushCallStack("utilities::LocalLength"); #endif int shift = Shift( index, alignment, modulus ); int localLength = LocalLength( n, shift, modulus ); #ifndef RELEASE PopCallStack(); #endif return localLength; } inline int elemental::utilities::RawLocalLength ( int n, int index, int alignment, int modulus ) { int shift = RawShift( index, alignment, modulus ); int localLength = RawLocalLength( n, shift, modulus ); return localLength; } inline int elemental::utilities::MaxLocalLength ( int n, int modulus ) { #ifndef RELEASE PushCallStack("utilities::MaxLocalLength"); if( n < 0 ) throw std::logic_error( "n must be non-negative." ); if( modulus <= 0 ) throw std::logic_error( "Modulus must be positive." ); PopCallStack(); #endif return elemental::utilities::RawMaxLocalLength( n, modulus ); } inline int elemental::utilities::RawMaxLocalLength ( int n, int modulus ) { return ( n > 0 ? (n - 1)/modulus + 1 : 0 ); } // For determining the first global element of process row/column // 'index', with distribution alignment 'alignment' and number of process // rows/cols 'modulus' inline int elemental::utilities::Shift ( int index, int alignment, int modulus ) { #ifndef RELEASE PushCallStack("utilities::Shift"); if( index < 0 || index >= modulus ) { std::ostringstream msg; msg << "Invalid index: " << "index=" << index << ", modulus=" << modulus; throw std::logic_error( msg.str() ); } if( alignment < 0 || alignment >= modulus ) { std::ostringstream msg; msg << "Invalid alignment: " << "alignment=" << alignment << ", modulus=" << modulus; throw std::logic_error( msg.str() ); } if( modulus <= 0 ) throw std::logic_error( "Modulus must be positive." ); PopCallStack(); #endif return elemental::utilities::RawShift( index, alignment, modulus ); } inline int elemental::utilities::RawShift ( int index, int alignment, int modulus ) { return (index + modulus - alignment) % modulus; } #endif /* ELEMENTAL_UTILITIES_HPP */ <|endoftext|>
<commit_before>/* Copyright (c) 2016, Project OSRM contributors 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. */ #ifndef PHANTOM_NODES_H #define PHANTOM_NODES_H #include "extractor/travel_mode.hpp" #include "util/typedefs.hpp" #include "util/coordinate.hpp" #include <boost/assert.hpp> #include <iostream> #include <utility> #include <vector> namespace osrm { namespace engine { struct PhantomNode { PhantomNode() : forward_segment_id{SPECIAL_SEGMENTID, false}, reverse_segment_id{SPECIAL_SEGMENTID, false}, forward_weight(INVALID_EDGE_WEIGHT), reverse_weight(INVALID_EDGE_WEIGHT), forward_weight_offset(0), reverse_weight_offset(0), forward_duration(MAXIMAL_EDGE_DURATION), reverse_duration(MAXIMAL_EDGE_DURATION), forward_duration_offset(0), reverse_duration_offset(0), component{INVALID_COMPONENTID, false}, fwd_segment_position(0), is_valid_forward_source(false), is_valid_forward_target(false), is_valid_reverse_source(false), is_valid_reverse_target(false) { } EdgeWeight GetForwardWeightPlusOffset() const { BOOST_ASSERT(forward_segment_id.enabled); return forward_weight_offset + forward_weight; } EdgeWeight GetReverseWeightPlusOffset() const { BOOST_ASSERT(reverse_segment_id.enabled); return reverse_weight_offset + reverse_weight; } EdgeWeight GetForwardDuration() const { BOOST_ASSERT(forward_segment_id.enabled); return forward_duration + forward_duration_offset; } EdgeWeight GetReverseDuration() const { BOOST_ASSERT(reverse_segment_id.enabled); return reverse_duration + reverse_duration_offset; } bool IsBidirected() const { return forward_segment_id.enabled && reverse_segment_id.enabled; } bool IsValid(const unsigned number_of_nodes) const { return location.IsValid() && ((forward_segment_id.id < number_of_nodes) || (reverse_segment_id.id < number_of_nodes)) && ((forward_weight != INVALID_EDGE_WEIGHT) || (reverse_weight != INVALID_EDGE_WEIGHT)) && ((forward_duration != MAXIMAL_EDGE_DURATION) || (reverse_duration != MAXIMAL_EDGE_DURATION)) && (component.id != INVALID_COMPONENTID); } bool IsValid(const unsigned number_of_nodes, const util::Coordinate queried_coordinate) const { return queried_coordinate == input_location && IsValid(number_of_nodes); } bool IsValid() const { return location.IsValid(); } bool IsValidForwardSource() const { return forward_segment_id.enabled && is_valid_forward_source; } bool IsValidForwardTarget() const { return forward_segment_id.enabled && is_valid_forward_target; } bool IsValidReverseSource() const { return reverse_segment_id.enabled && is_valid_reverse_source; } bool IsValidReverseTarget() const { return reverse_segment_id.enabled && is_valid_reverse_target; } bool operator==(const PhantomNode &other) const { return location == other.location; } template <class OtherT> explicit PhantomNode(const OtherT &other, EdgeWeight forward_weight, EdgeWeight reverse_weight, EdgeWeight forward_weight_offset, EdgeWeight reverse_weight_offset, EdgeWeight forward_duration, EdgeWeight reverse_duration, EdgeWeight forward_duration_offset, EdgeWeight reverse_duration_offset, bool is_valid_forward_source, bool is_valid_forward_target, bool is_valid_reverse_source, bool is_valid_reverse_target, const util::Coordinate location, const util::Coordinate input_location) : forward_segment_id{other.forward_segment_id}, reverse_segment_id{other.reverse_segment_id}, forward_weight{forward_weight}, reverse_weight{reverse_weight}, forward_weight_offset{forward_weight_offset}, reverse_weight_offset{reverse_weight_offset}, forward_duration{forward_duration}, reverse_duration{reverse_duration}, forward_duration_offset{forward_duration_offset}, reverse_duration_offset{reverse_duration_offset}, component{other.component.id, other.component.is_tiny}, location{location}, input_location{input_location}, fwd_segment_position{other.fwd_segment_position}, is_valid_forward_source{is_valid_forward_source}, is_valid_forward_target{is_valid_forward_target}, is_valid_reverse_source{is_valid_reverse_source}, is_valid_reverse_target{is_valid_reverse_target} { } SegmentID forward_segment_id; SegmentID reverse_segment_id; EdgeWeight forward_weight; EdgeWeight reverse_weight; EdgeWeight forward_weight_offset; // TODO: try to remove -> requires path unpacking changes EdgeWeight reverse_weight_offset; // TODO: try to remove -> requires path unpacking changes EdgeWeight forward_duration; EdgeWeight reverse_duration; EdgeWeight forward_duration_offset; // TODO: try to remove -> requires path unpacking changes EdgeWeight reverse_duration_offset; // TODO: try to remove -> requires path unpacking changes struct ComponentType { std::uint32_t id : 31; std::uint32_t is_tiny : 1; } component; static_assert(sizeof(ComponentType) == 4, "ComponentType needs to be 4 bytes big"); util::Coordinate location; util::Coordinate input_location; unsigned short fwd_segment_position; // is phantom node valid to be used as source or target private: bool is_valid_forward_source : 1; bool is_valid_forward_target : 1; bool is_valid_reverse_source : 1; bool is_valid_reverse_target : 1; }; static_assert(sizeof(PhantomNode) == 64, "PhantomNode has more padding then expected"); using PhantomNodePair = std::pair<PhantomNode, PhantomNode>; struct PhantomNodeWithDistance { PhantomNode phantom_node; double distance; }; struct PhantomNodes { PhantomNode source_phantom; PhantomNode target_phantom; }; inline std::ostream &operator<<(std::ostream &out, const PhantomNodes &pn) { out << "source_coord: " << pn.source_phantom.location << "\n"; out << "target_coord: " << pn.target_phantom.location << std::endl; return out; } inline std::ostream &operator<<(std::ostream &out, const PhantomNode &pn) { out << "node1: " << pn.forward_segment_id.id << ", " << "node2: " << pn.reverse_segment_id.id << ", " << "fwd-w: " << pn.forward_weight << ", " << "rev-w: " << pn.reverse_weight << ", " << "fwd-o: " << pn.forward_weight_offset << ", " << "rev-o: " << pn.reverse_weight_offset << ", " << "fwd-d: " << pn.forward_duration << ", " << "rev-d: " << pn.reverse_duration << ", " << "fwd-do: " << pn.forward_duration_offset << ", " << "rev-do: " << pn.reverse_duration_offset << ", " << "comp: " << pn.component.is_tiny << " / " << pn.component.id << ", " << "pos: " << pn.fwd_segment_position << ", " << "loc: " << pn.location; return out; } } } #endif // PHANTOM_NODES_H <commit_msg>Initialize unused bits in PhantomNode<commit_after>/* Copyright (c) 2016, Project OSRM contributors 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. */ #ifndef PHANTOM_NODES_H #define PHANTOM_NODES_H #include "extractor/travel_mode.hpp" #include "util/typedefs.hpp" #include "util/coordinate.hpp" #include <boost/assert.hpp> #include <iostream> #include <utility> #include <vector> namespace osrm { namespace engine { struct PhantomNode { PhantomNode() : forward_segment_id{SPECIAL_SEGMENTID, false}, reverse_segment_id{SPECIAL_SEGMENTID, false}, forward_weight(INVALID_EDGE_WEIGHT), reverse_weight(INVALID_EDGE_WEIGHT), forward_weight_offset(0), reverse_weight_offset(0), forward_duration(MAXIMAL_EDGE_DURATION), reverse_duration(MAXIMAL_EDGE_DURATION), forward_duration_offset(0), reverse_duration_offset(0), component{INVALID_COMPONENTID, false}, fwd_segment_position(0), is_valid_forward_source{false}, is_valid_forward_target{false}, is_valid_reverse_source{false}, is_valid_reverse_target{false}, unused{0} { } EdgeWeight GetForwardWeightPlusOffset() const { BOOST_ASSERT(forward_segment_id.enabled); return forward_weight_offset + forward_weight; } EdgeWeight GetReverseWeightPlusOffset() const { BOOST_ASSERT(reverse_segment_id.enabled); return reverse_weight_offset + reverse_weight; } EdgeWeight GetForwardDuration() const { BOOST_ASSERT(forward_segment_id.enabled); return forward_duration + forward_duration_offset; } EdgeWeight GetReverseDuration() const { BOOST_ASSERT(reverse_segment_id.enabled); return reverse_duration + reverse_duration_offset; } bool IsBidirected() const { return forward_segment_id.enabled && reverse_segment_id.enabled; } bool IsValid(const unsigned number_of_nodes) const { return location.IsValid() && ((forward_segment_id.id < number_of_nodes) || (reverse_segment_id.id < number_of_nodes)) && ((forward_weight != INVALID_EDGE_WEIGHT) || (reverse_weight != INVALID_EDGE_WEIGHT)) && ((forward_duration != MAXIMAL_EDGE_DURATION) || (reverse_duration != MAXIMAL_EDGE_DURATION)) && (component.id != INVALID_COMPONENTID); } bool IsValid(const unsigned number_of_nodes, const util::Coordinate queried_coordinate) const { return queried_coordinate == input_location && IsValid(number_of_nodes); } bool IsValid() const { return location.IsValid(); } bool IsValidForwardSource() const { return forward_segment_id.enabled && is_valid_forward_source; } bool IsValidForwardTarget() const { return forward_segment_id.enabled && is_valid_forward_target; } bool IsValidReverseSource() const { return reverse_segment_id.enabled && is_valid_reverse_source; } bool IsValidReverseTarget() const { return reverse_segment_id.enabled && is_valid_reverse_target; } bool operator==(const PhantomNode &other) const { return location == other.location; } template <class OtherT> explicit PhantomNode(const OtherT &other, EdgeWeight forward_weight, EdgeWeight reverse_weight, EdgeWeight forward_weight_offset, EdgeWeight reverse_weight_offset, EdgeWeight forward_duration, EdgeWeight reverse_duration, EdgeWeight forward_duration_offset, EdgeWeight reverse_duration_offset, bool is_valid_forward_source, bool is_valid_forward_target, bool is_valid_reverse_source, bool is_valid_reverse_target, const util::Coordinate location, const util::Coordinate input_location) : forward_segment_id{other.forward_segment_id}, reverse_segment_id{other.reverse_segment_id}, forward_weight{forward_weight}, reverse_weight{reverse_weight}, forward_weight_offset{forward_weight_offset}, reverse_weight_offset{reverse_weight_offset}, forward_duration{forward_duration}, reverse_duration{reverse_duration}, forward_duration_offset{forward_duration_offset}, reverse_duration_offset{reverse_duration_offset}, component{other.component.id, other.component.is_tiny}, location{location}, input_location{input_location}, fwd_segment_position{other.fwd_segment_position}, is_valid_forward_source{is_valid_forward_source}, is_valid_forward_target{is_valid_forward_target}, is_valid_reverse_source{is_valid_reverse_source}, is_valid_reverse_target{is_valid_reverse_target}, unused{0} { } SegmentID forward_segment_id; SegmentID reverse_segment_id; EdgeWeight forward_weight; EdgeWeight reverse_weight; EdgeWeight forward_weight_offset; // TODO: try to remove -> requires path unpacking changes EdgeWeight reverse_weight_offset; // TODO: try to remove -> requires path unpacking changes EdgeWeight forward_duration; EdgeWeight reverse_duration; EdgeWeight forward_duration_offset; // TODO: try to remove -> requires path unpacking changes EdgeWeight reverse_duration_offset; // TODO: try to remove -> requires path unpacking changes struct ComponentType { std::uint32_t id : 31; std::uint32_t is_tiny : 1; } component; static_assert(sizeof(ComponentType) == 4, "ComponentType needs to be 4 bytes big"); util::Coordinate location; util::Coordinate input_location; unsigned short fwd_segment_position; // is phantom node valid to be used as source or target private: unsigned short is_valid_forward_source : 1; unsigned short is_valid_forward_target : 1; unsigned short is_valid_reverse_source : 1; unsigned short is_valid_reverse_target : 1; unsigned short unused : 12; }; static_assert(sizeof(PhantomNode) == 64, "PhantomNode has more padding then expected"); using PhantomNodePair = std::pair<PhantomNode, PhantomNode>; struct PhantomNodeWithDistance { PhantomNode phantom_node; double distance; }; struct PhantomNodes { PhantomNode source_phantom; PhantomNode target_phantom; }; inline std::ostream &operator<<(std::ostream &out, const PhantomNodes &pn) { out << "source_coord: " << pn.source_phantom.location << "\n"; out << "target_coord: " << pn.target_phantom.location << std::endl; return out; } inline std::ostream &operator<<(std::ostream &out, const PhantomNode &pn) { out << "node1: " << pn.forward_segment_id.id << ", " << "node2: " << pn.reverse_segment_id.id << ", " << "fwd-w: " << pn.forward_weight << ", " << "rev-w: " << pn.reverse_weight << ", " << "fwd-o: " << pn.forward_weight_offset << ", " << "rev-o: " << pn.reverse_weight_offset << ", " << "fwd-d: " << pn.forward_duration << ", " << "rev-d: " << pn.reverse_duration << ", " << "fwd-do: " << pn.forward_duration_offset << ", " << "rev-do: " << pn.reverse_duration_offset << ", " << "comp: " << pn.component.is_tiny << " / " << pn.component.id << ", " << "pos: " << pn.fwd_segment_position << ", " << "loc: " << pn.location; return out; } } } #endif // PHANTOM_NODES_H <|endoftext|>
<commit_before>/**** * unionfind : a data structure for efficiently performing unification for n terms in effectively O(n) time ****/ #ifndef HOBBES_UTIL_UNIONFIND_HPP_INCLUDED #define HOBBES_UTIL_UNIONFIND_HPP_INCLUDED #include <unordered_map> #include <stdexcept> #include <sstream> #include <memory> namespace hobbes { template <typename K, typename V> struct eqsetmem { eqsetmem(const K& key, const V& value) : key(key), value(value), rank(0) { representative = this; } K key; V value; size_t rank; eqsetmem<K, V>* representative; }; template <typename K, typename V, typename KVLift, typename VPlus> class equivalence_mapping { public: equivalence_mapping() : eqsz(0) { } // how many equivalence constraints have been recorded? size_t size() const { return this->eqsz; } // find the representative element for a set V& find(const K& k) { return findNode(k)->value; } // declare two values equal void join(const K& k0, const K& k1) { node_t* lhs = findNode(k0); node_t* rhs = findNode(k1); if (lhs->rank < rhs->rank) { lhs->representative = rhs; rhs->value = VPlus::apply(rhs->value, lhs->value); } else if (lhs->rank > rhs->rank) { rhs->representative = lhs; lhs->value = VPlus::apply(lhs->value, rhs->value); } else if (lhs == rhs) { // these are the same thing, don't pretend that we've added information return; } else { rhs->representative = lhs; lhs->rank += 1; lhs->value = VPlus::apply(lhs->value, rhs->value); } ++this->eqsz; } // merge another equivalence mapping with this one size_t merge(const equivalence_mapping<K, V, KVLift, VPlus>& rhs) { // count the number of extra bindings that we add size_t c = this->eqsz; // add new nodes to this set for (const auto& kn : rhs.nodes) { if (this->nodes.find(kn.first) == this->nodes.end()) { this->nodes[kn.first] = nodep(new node_t(kn.first, KVLift::apply(kn.first))); } } // now for these new nodes, apply the equivalence bindings from the input set for (const auto& kn : rhs.nodes) { node_t* rrep = findRepresentative(kn.second.get()); if (kn.first != rrep->key) { join(kn.first, rrep->key); } } return this->eqsz - c; } // get the universe of values std::vector<K> values() const { std::vector<K> vs; vs.reserve(nodes.size()); for (const auto& kn : this->nodes) { vs.push_back(kn.first); } return vs; } private: size_t eqsz; typedef eqsetmem<K, V> node_t; typedef std::unique_ptr<node_t> nodep; // allows multiple incremental extensions of unification sets typedef std::unordered_map<K, nodep> nodes_t; nodes_t nodes; static node_t* findRepresentative(node_t* n) { if (n != n->representative) { n->representative = findRepresentative(n->representative); } return n->representative; } node_t* findNode(const K& k) { typename nodes_t::const_iterator n = this->nodes.find(k); if (n != this->nodes.end()) { return findRepresentative(n->second.get()); } else { node_t* n = new node_t(k, KVLift::apply(k)); this->nodes[k] = nodep(n); return n; } } }; } #endif <commit_msg>use constant memory in unionfind path compression (tolerate deep chains)<commit_after>/**** * unionfind : a data structure for efficiently performing unification for n terms in effectively O(n) time ****/ #ifndef HOBBES_UTIL_UNIONFIND_HPP_INCLUDED #define HOBBES_UTIL_UNIONFIND_HPP_INCLUDED #include <unordered_map> #include <stdexcept> #include <sstream> #include <memory> namespace hobbes { template <typename K, typename V> struct eqsetmem { eqsetmem(const K& key, const V& value) : key(key), value(value), rank(0) { representative = this; } K key; V value; size_t rank; eqsetmem<K, V>* representative; }; template <typename K, typename V, typename KVLift, typename VPlus> class equivalence_mapping { public: equivalence_mapping() : eqsz(0) { } // how many equivalence constraints have been recorded? size_t size() const { return this->eqsz; } // find the representative element for a set V& find(const K& k) { return findNode(k)->value; } // declare two values equal void join(const K& k0, const K& k1) { node_t* lhs = findNode(k0); node_t* rhs = findNode(k1); if (lhs->rank < rhs->rank) { lhs->representative = rhs; rhs->value = VPlus::apply(rhs->value, lhs->value); } else if (lhs->rank > rhs->rank) { rhs->representative = lhs; lhs->value = VPlus::apply(lhs->value, rhs->value); } else if (lhs == rhs) { // these are the same thing, don't pretend that we've added information return; } else { rhs->representative = lhs; lhs->rank += 1; lhs->value = VPlus::apply(lhs->value, rhs->value); } ++this->eqsz; } // merge another equivalence mapping with this one size_t merge(const equivalence_mapping<K, V, KVLift, VPlus>& rhs) { // count the number of extra bindings that we add size_t c = this->eqsz; // add new nodes to this set for (const auto& kn : rhs.nodes) { if (this->nodes.find(kn.first) == this->nodes.end()) { this->nodes[kn.first] = nodep(new node_t(kn.first, KVLift::apply(kn.first))); } } // now for these new nodes, apply the equivalence bindings from the input set for (const auto& kn : rhs.nodes) { node_t* rrep = findRepresentative(kn.second.get()); if (kn.first != rrep->key) { join(kn.first, rrep->key); } } return this->eqsz - c; } // get the universe of values std::vector<K> values() const { std::vector<K> vs; vs.reserve(nodes.size()); for (const auto& kn : this->nodes) { vs.push_back(kn.first); } return vs; } private: size_t eqsz; typedef eqsetmem<K, V> node_t; typedef std::unique_ptr<node_t> nodep; // allows multiple incremental extensions of unification sets typedef std::unordered_map<K, nodep> nodes_t; nodes_t nodes; static node_t* findRepresentative(node_t* n) { // first find the root auto* root = n; while (root != root->representative) { root = root->representative; } // then update all nodes along the way (they all have the same representative) while (n != root) { auto* s = n->representative; n->representative = root; n = s; } return root; } node_t* findNode(const K& k) { typename nodes_t::const_iterator n = this->nodes.find(k); if (n != this->nodes.end()) { return findRepresentative(n->second.get()); } else { node_t* n = new node_t(k, KVLift::apply(k)); this->nodes[k] = nodep(n); return n; } } }; } #endif <|endoftext|>
<commit_before>// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // #include "chrono/ChConfig.h" #include "chrono/core/ChFileutils.h" #include "chrono/core/ChTimer.h" #include "chrono/solver/ChSolverMINRES.h" #include "chrono/physics/ChBodyEasy.h" #include "chrono/physics/ChSystem.h" #include "chrono/utils/ChUtilsInputOutput.h" #include "chrono_fea/ChElementShellANCF.h" #include "chrono_fea/ChLinkDirFrame.h" #include "chrono_fea/ChLinkPointFrame.h" #include "chrono_fea/ChMesh.h" #include "../BaseTest.h" #ifdef CHRONO_MKL #include "chrono_mkl/ChSolverMKL.h" ////#define USE_MKL #else #undef USE_MKL #endif #ifdef CHRONO_OPENMP_ENABLED #include <omp.h> #endif using namespace chrono; using namespace chrono::fea; int num_threads = 4; double step_size = 1e-3; int num_steps = 20; int numDiv_x = 50; int numDiv_y = 50; int numDiv_z = 1; /// A new test class that extends the BaseTest class so that it outputs proper JSON to be used in the metricsAPI <<<<<<< HEAD class test_FEA_shellANCF: public BaseTest { public: test_FEA_shellANCF(const std::string& testName, const std::string& testProjectName) : BaseTest(testName, testProjectName), m_execTime(-1) { std::cout << "Constructing Derived Test" << std::endl; } // Default destuctor ~test_FEA_shellANCF() { } // Override corresponding functions in BaseTest virtual bool execute() { return m_passed; } virtual double getExecutionTime() const { return m_execTime; } void setPassed(bool passed) { m_passed = passed; } void setExecTime(double time) { m_execTime = time; } private: /// Used to measure total test execution time for unit test double m_execTime; bool m_passed; }; int main(int argc, char* argv[]) { test_FEA_shellANCF t("test_FEA_shellANCF", "chrono"); // If no command line arguments, run in "performance" mode and only report run time. // Otherwise, generate output files to verify correctness. bool output = (argc > 1); if (output) { GetLog() << "Output file: ../TEST_SHELL_ANCF/tip_position.txt\n"; } else { GetLog() << "Running in performance test mode.\n"; } ======= class test_FEA_shellANCF : public BaseTest { public: test_FEA_shellANCF(const std::string& testName, const std::string& testProjectName) : BaseTest(testName, testProjectName), m_execTime(-1) { std::cout << "Constructing Derived Test" << std::endl; } ~test_FEA_shellANCF() {} // Override corresponding functions in BaseTest virtual bool execute() { return m_passed; } virtual double getExecutionTime() const { return m_execTime; } void setPassed(bool passed) { m_passed = passed; } void setExecTime(double time) { m_execTime = time; } private: /// Used to measure total test execution time for unit test double m_execTime; bool m_passed; }; int main(int argc, char* argv[]) { test_FEA_shellANCF t("test_FEA_shellANCF", "chrono"); // If no command line arguments, run in "performance" mode and only report run time. // Otherwise, generate output files to verify correctness. bool output = (argc > 1); if (output) { GetLog() << "Output file: ../TEST_SHELL_ANCF/tip_position.txt\n"; } else { GetLog() << "Running in performance test mode.\n"; } >>>>>>> 6e4fc966bfaa411a1040ffe3862eb7d84e6aee3b // -------------------------- // Set number of threads // -------------------------- #ifdef CHRONO_OPENMP_ENABLED int max_threads = CHOMPfunctions::GetNumProcs(); if (num_threads > max_threads) num_threads = max_threads; CHOMPfunctions::SetNumThreads(num_threads); GetLog() << "Using " << num_threads <<" thread(s)\n"; #else GetLog() << "No OpenMP\n"; #endif // -------------------------- // Create the physical system // -------------------------- ChSystem my_system; my_system.Set_G_acc(ChVector<>(0, 0, -9.81)); // Create a mesh, that is a container for groups // of elements and their referenced nodes. GetLog() << "Using " << numDiv_x << " x " << numDiv_y << " mesh divisions\n"; auto my_mesh = std::make_shared<ChMesh>(); // Geometry of the plate double plate_lenght_x = 1.0; double plate_lenght_y = 1.0; double plate_lenght_z = 0.04; // small thickness // Specification of the mesh int N_x = numDiv_x + 1; int N_y = numDiv_y + 1; int N_z = numDiv_z + 1; // Number of elements in the z direction is considered as 1 int TotalNumElements = numDiv_x * numDiv_y; //(1+1) is the number of nodes in the z direction int TotalNumNodes = (numDiv_x + 1) * (numDiv_y + 1); // Or *(numDiv_z+1) for multilayer // Element dimensions (uniform grid) double dx = plate_lenght_x / numDiv_x; double dy = plate_lenght_y / numDiv_y; double dz = plate_lenght_z / numDiv_z; // Create and add the nodes for (int i = 0; i < TotalNumNodes; i++) { // Parametric location and direction of nodal coordinates double loc_x = (i % (numDiv_x + 1)) * dx; double loc_y = (i / (numDiv_x + 1)) % (numDiv_y + 1) * dy; double loc_z = (i) / ((numDiv_x + 1) * (numDiv_y + 1)) * dz; double dir_x = 0; double dir_y = 0; double dir_z = 1; // Create the node auto node = std::make_shared < ChNodeFEAxyzD > (ChVector<>(loc_x, loc_y, loc_z), ChVector<>(dir_x, dir_y, dir_z)); node->SetMass(0); // Fix all nodes along the axis X=0 if (i % (numDiv_x + 1) == 0) node->SetFixed(true); // Add node to mesh my_mesh->AddNode(node); } // Create an isotropic material // Only one layer double rho = 500; double E = 2.1e7; double nu = 0.3; auto mat = std::make_shared < ChMaterialShellANCF > (rho, E, nu); // Create the elements for (int i = 0; i < TotalNumElements; i++) { // Definition of nodes forming an element int node0 = (i / (numDiv_x)) * (N_x) + i % numDiv_x; int node1 = (i / (numDiv_x)) * (N_x) + i % numDiv_x + 1; int node2 = (i / (numDiv_x)) * (N_x) + i % numDiv_x + 1 + N_x; int node3 = (i / (numDiv_x)) * (N_x) + i % numDiv_x + N_x; // Create the element and set its nodes. auto element = std::make_shared<ChElementShellANCF>(); element->SetNodes( std::dynamic_pointer_cast < ChNodeFEAxyzD > (my_mesh->GetNode(node0)), std::dynamic_pointer_cast < ChNodeFEAxyzD > (my_mesh->GetNode(node1)), std::dynamic_pointer_cast < ChNodeFEAxyzD > (my_mesh->GetNode(node2)), std::dynamic_pointer_cast < ChNodeFEAxyzD > (my_mesh->GetNode(node3))); // Element length is a fixed number in both direction. (uniform distribution of nodes in both directions) element->SetDimensions(dx, dy); // Single layer element->AddLayer(dz, 0 * CH_C_DEG_TO_RAD, mat); // Thickness: dy; Ply angle: 0. // Set other element properties element->SetAlphaDamp(0.0); // Structural damping for this element->SetGravityOn(true); // element calculates its own gravitational load // Add element to mesh my_mesh->AddElement(element); } // Switch off mesh class gravity (ANCF shell elements have a custom implementation) my_mesh->SetAutomaticGravity(false); // Remember to add the mesh to the system! my_system.Add(my_mesh); // Mark completion of system construction my_system.SetupInitial(); // Set up solver #ifdef USE_MKL GetLog() << "Using MKL solver\n"; ChSolverMKL* mkl_solver_stab = new ChSolverMKL; ChSolverMKL* mkl_solver_speed = new ChSolverMKL; my_system.ChangeSolverStab(mkl_solver_stab); my_system.ChangeSolverSpeed(mkl_solver_speed); mkl_solver_speed->SetSparsityPatternLock(true); mkl_solver_stab->SetSparsityPatternLock(true); #else GetLog() << "Using MINRES solver\n"; my_system.SetSolverType(ChSystem::SOLVER_MINRES); ChSolverMINRES* msolver = (ChSolverMINRES*) my_system.GetSolverSpeed(); msolver->SetDiagonalPreconditioning(true); my_system.SetMaxItersSolverSpeed(100); my_system.SetTolForce(1e-10); #endif // Set up integrator my_system.SetIntegrationType(ChSystem::INT_HHT); auto mystepper = std::static_pointer_cast < ChTimestepperHHT > (my_system.GetTimestepper()); mystepper->SetAlpha(-0.2); mystepper->SetMaxiters(100); mystepper->SetAbsTolerances(1e-5); mystepper->SetMode(ChTimestepperHHT::POSITION); mystepper->SetScaling(true); //// mystepper->SetVerbose(true); // --------------- // Simulation loop // --------------- if (output) { // Create output directory (if it does not already exist). if (ChFileutils::MakeDirectory("../TEST_SHELL_ANCF") < 0) { GetLog() << "Error creating directory ../TEST_SHELL_ANCF\n"; return 1; } // Initialize the output stream and set precision. utils::CSV_writer out("\t"); out.stream().setf(std::ios::scientific | std::ios::showpos); out.stream().precision(6); auto nodetip = std::dynamic_pointer_cast < ChNodeFEAxyzD > (my_mesh->GetNode(TotalNumNodes - 1)); // Simulate to final time, while saving position of tip node. for (int istep = 0; istep < num_steps; istep++) { my_system.DoStepDynamics(step_size); out << my_system.GetChTime() << nodetip->GetPos() << std::endl; } // Write results to output file. out.write_to_file("../TEST_SHELL_ANCF/tip_position.txt"); } else { // Initialize total number of iterations and timer. int num_iterations = 0; ChTimer<> timer; timer.start(); // Simulate to final time, while accumulating number of iterations. for (int istep = 0; istep < num_steps; istep++) { ////GetLog() << " step number: " << istep << " time: " << my_system.GetChTime() << "\n"; my_system.DoStepDynamics(step_size); num_iterations += mystepper->GetNumIterations(); } timer.stop(); // Report run time and total number of iterations. GetLog() << "Number of iterations: " << num_iterations << "\n"; t.addMetric("num_iterations", num_iterations); GetLog() << "Simulation time: " << timer() << "\n"; t.setExecTime(timer()); GetLog() << "Internal forces (" << my_mesh->GetNumCallsInternalForces() << "): " << my_mesh->GetTimingInternalForces() << "\n"; t.addMetric("internal_forces", my_mesh->GetTimingInternalForces()); GetLog() << "Jacobian (" << my_mesh->GetNumCallsJacobianLoad() << "): " << my_mesh->GetTimingJacobianLoad() << "\n"; t.addMetric("jacobian", my_mesh->GetTimingJacobianLoad()); GetLog() << "Extra time: " << timer() - my_mesh->GetTimingInternalForces() - my_mesh->GetTimingJacobianLoad() << "\n"; t.addMetric("extra_time", timer() - my_mesh->GetTimingInternalForces() - my_mesh->GetTimingJacobianLoad()); t.setPassed(true); } t.print(); t.run(); return 0; } <commit_msg>Fix conflicts from previous commit<commit_after>// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // #include "chrono/ChConfig.h" #include "chrono/core/ChFileutils.h" #include "chrono/core/ChTimer.h" #include "chrono/solver/ChSolverMINRES.h" #include "chrono/physics/ChBodyEasy.h" #include "chrono/physics/ChSystem.h" #include "chrono/utils/ChUtilsInputOutput.h" #include "chrono_fea/ChElementShellANCF.h" #include "chrono_fea/ChLinkDirFrame.h" #include "chrono_fea/ChLinkPointFrame.h" #include "chrono_fea/ChMesh.h" #include "../BaseTest.h" #ifdef CHRONO_MKL #include "chrono_mkl/ChSolverMKL.h" ////#define USE_MKL #else #undef USE_MKL #endif #ifdef CHRONO_OPENMP_ENABLED #include <omp.h> #endif using namespace chrono; using namespace chrono::fea; int num_threads = 4; double step_size = 1e-3; int num_steps = 20; int numDiv_x = 50; int numDiv_y = 50; int numDiv_z = 1; /// A new test class that extends the BaseTest class so that it outputs proper JSON to be used in the metricsAPI class test_FEA_shellANCF : public BaseTest { public: test_FEA_shellANCF(const std::string& testName, const std::string& testProjectName) : BaseTest(testName, testProjectName), m_execTime(-1) { std::cout << "Constructing Derived Test" << std::endl; } ~test_FEA_shellANCF() {} // Override corresponding functions in BaseTest virtual bool execute() { return m_passed; } virtual double getExecutionTime() const { return m_execTime; } void setPassed(bool passed) { m_passed = passed; } void setExecTime(double time) { m_execTime = time; } private: /// Used to measure total test execution time for unit test double m_execTime; bool m_passed; }; int main(int argc, char* argv[]) { test_FEA_shellANCF t("test_FEA_shellANCF", "chrono"); // If no command line arguments, run in "performance" mode and only report run time. // Otherwise, generate output files to verify correctness. bool output = (argc > 1); if (output) { GetLog() << "Output file: ../TEST_SHELL_ANCF/tip_position.txt\n"; } else { GetLog() << "Running in performance test mode.\n"; } // -------------------------- // Set number of threads // -------------------------- #ifdef CHRONO_OPENMP_ENABLED int max_threads = CHOMPfunctions::GetNumProcs(); if (num_threads > max_threads) num_threads = max_threads; CHOMPfunctions::SetNumThreads(num_threads); GetLog() << "Using " << num_threads << " thread(s)\n"; #else GetLog() << "No OpenMP\n"; #endif // -------------------------- // Create the physical system // -------------------------- ChSystem my_system; my_system.Set_G_acc(ChVector<>(0, 0, -9.81)); // Create a mesh, that is a container for groups // of elements and their referenced nodes. GetLog() << "Using " << numDiv_x << " x " << numDiv_y << " mesh divisions\n"; auto my_mesh = std::make_shared<ChMesh>(); // Geometry of the plate double plate_lenght_x = 1.0; double plate_lenght_y = 1.0; double plate_lenght_z = 0.04; // small thickness // Specification of the mesh int N_x = numDiv_x + 1; int N_y = numDiv_y + 1; int N_z = numDiv_z + 1; // Number of elements in the z direction is considered as 1 int TotalNumElements = numDiv_x * numDiv_y; //(1+1) is the number of nodes in the z direction int TotalNumNodes = (numDiv_x + 1) * (numDiv_y + 1); // Or *(numDiv_z+1) for multilayer // Element dimensions (uniform grid) double dx = plate_lenght_x / numDiv_x; double dy = plate_lenght_y / numDiv_y; double dz = plate_lenght_z / numDiv_z; // Create and add the nodes for (int i = 0; i < TotalNumNodes; i++) { // Parametric location and direction of nodal coordinates double loc_x = (i % (numDiv_x + 1)) * dx; double loc_y = (i / (numDiv_x + 1)) % (numDiv_y + 1) * dy; double loc_z = (i) / ((numDiv_x + 1) * (numDiv_y + 1)) * dz; double dir_x = 0; double dir_y = 0; double dir_z = 1; // Create the node auto node = std::make_shared<ChNodeFEAxyzD>(ChVector<>(loc_x, loc_y, loc_z), ChVector<>(dir_x, dir_y, dir_z)); node->SetMass(0); // Fix all nodes along the axis X=0 if (i % (numDiv_x + 1) == 0) node->SetFixed(true); // Add node to mesh my_mesh->AddNode(node); } // Create an isotropic material // Only one layer double rho = 500; double E = 2.1e7; double nu = 0.3; auto mat = std::make_shared<ChMaterialShellANCF>(rho, E, nu); // Create the elements for (int i = 0; i < TotalNumElements; i++) { // Definition of nodes forming an element int node0 = (i / (numDiv_x)) * (N_x) + i % numDiv_x; int node1 = (i / (numDiv_x)) * (N_x) + i % numDiv_x + 1; int node2 = (i / (numDiv_x)) * (N_x) + i % numDiv_x + 1 + N_x; int node3 = (i / (numDiv_x)) * (N_x) + i % numDiv_x + N_x; // Create the element and set its nodes. auto element = std::make_shared<ChElementShellANCF>(); element->SetNodes(std::dynamic_pointer_cast<ChNodeFEAxyzD>(my_mesh->GetNode(node0)), std::dynamic_pointer_cast<ChNodeFEAxyzD>(my_mesh->GetNode(node1)), std::dynamic_pointer_cast<ChNodeFEAxyzD>(my_mesh->GetNode(node2)), std::dynamic_pointer_cast<ChNodeFEAxyzD>(my_mesh->GetNode(node3))); // Element length is a fixed number in both direction. (uniform distribution of nodes in both directions) element->SetDimensions(dx, dy); // Single layer element->AddLayer(dz, 0 * CH_C_DEG_TO_RAD, mat); // Thickness: dy; Ply angle: 0. // Set other element properties element->SetAlphaDamp(0.0); // Structural damping for this element->SetGravityOn(true); // element calculates its own gravitational load // Add element to mesh my_mesh->AddElement(element); } // Switch off mesh class gravity (ANCF shell elements have a custom implementation) my_mesh->SetAutomaticGravity(false); // Remember to add the mesh to the system! my_system.Add(my_mesh); // Mark completion of system construction my_system.SetupInitial(); // Set up solver #ifdef USE_MKL GetLog() << "Using MKL solver\n"; ChSolverMKL* mkl_solver_stab = new ChSolverMKL; ChSolverMKL* mkl_solver_speed = new ChSolverMKL; my_system.ChangeSolverStab(mkl_solver_stab); my_system.ChangeSolverSpeed(mkl_solver_speed); mkl_solver_speed->SetSparsityPatternLock(true); mkl_solver_stab->SetSparsityPatternLock(true); #else GetLog() << "Using MINRES solver\n"; my_system.SetSolverType(ChSystem::SOLVER_MINRES); ChSolverMINRES* msolver = (ChSolverMINRES*)my_system.GetSolverSpeed(); msolver->SetDiagonalPreconditioning(true); my_system.SetMaxItersSolverSpeed(100); my_system.SetTolForce(1e-10); #endif // Set up integrator my_system.SetIntegrationType(ChSystem::INT_HHT); auto mystepper = std::static_pointer_cast<ChTimestepperHHT>(my_system.GetTimestepper()); mystepper->SetAlpha(-0.2); mystepper->SetMaxiters(100); mystepper->SetAbsTolerances(1e-5); mystepper->SetMode(ChTimestepperHHT::POSITION); mystepper->SetScaling(true); //// mystepper->SetVerbose(true); // --------------- // Simulation loop // --------------- if (output) { // Create output directory (if it does not already exist). if (ChFileutils::MakeDirectory("../TEST_SHELL_ANCF") < 0) { GetLog() << "Error creating directory ../TEST_SHELL_ANCF\n"; return 1; } // Initialize the output stream and set precision. utils::CSV_writer out("\t"); out.stream().setf(std::ios::scientific | std::ios::showpos); out.stream().precision(6); auto nodetip = std::dynamic_pointer_cast<ChNodeFEAxyzD>(my_mesh->GetNode(TotalNumNodes - 1)); // Simulate to final time, while saving position of tip node. for (int istep = 0; istep < num_steps; istep++) { my_system.DoStepDynamics(step_size); out << my_system.GetChTime() << nodetip->GetPos() << std::endl; } // Write results to output file. out.write_to_file("../TEST_SHELL_ANCF/tip_position.txt"); } else { // Initialize total number of iterations and timer. int num_iterations = 0; ChTimer<> timer; timer.start(); // Simulate to final time, while accumulating number of iterations. for (int istep = 0; istep < num_steps; istep++) { ////GetLog() << " step number: " << istep << " time: " << my_system.GetChTime() << "\n"; my_system.DoStepDynamics(step_size); num_iterations += mystepper->GetNumIterations(); } timer.stop(); // Report run time and total number of iterations. GetLog() << "Number of iterations: " << num_iterations << "\n"; t.addMetric("num_iterations", num_iterations); GetLog() << "Simulation time: " << timer() << "\n"; t.setExecTime(timer()); GetLog() << "Internal forces (" << my_mesh->GetNumCallsInternalForces() << "): " << my_mesh->GetTimingInternalForces() << "\n"; t.addMetric("internal_forces", my_mesh->GetTimingInternalForces()); GetLog() << "Jacobian (" << my_mesh->GetNumCallsJacobianLoad() << "): " << my_mesh->GetTimingJacobianLoad() << "\n"; t.addMetric("jacobian", my_mesh->GetTimingJacobianLoad()); GetLog() << "Extra time: " << timer() - my_mesh->GetTimingInternalForces() - my_mesh->GetTimingJacobianLoad() << "\n"; t.addMetric("extra_time", timer() - my_mesh->GetTimingInternalForces() - my_mesh->GetTimingJacobianLoad()); t.setPassed(true); } t.print(); t.run(); return 0; } <|endoftext|>
<commit_before>/** * Copyright (C) 2013 IIT - Istituto Italiano di Tecnologia - http://www.iit.it * Author: Silvio Traversaro * CopyPolicy: Released under the terms of the GNU LGPL v2.0 (or any later version) * * The development of this software was supported by the FP7 EU project * CoDyCo (No. 600716 ICT 2011.2.1 Cognitive Systems and Robotics (b)) * http://www.codyco.eu */ #ifndef _KDL_CODYCO_FT_SENSOR_ #define _KDL_CODYCO_FT_SENSOR_ #ifndef NDEBUG #include <iostream> #endif #include <sstream> namespace KDL { namespace CoDyCo { /** * * \todo fix copy operator * * Data structure for containing information about internal FT sensors * To properly describe an FT sensor, it is necessary: * * the fixed junction of the FT sensor in the TreeGraph (a name) * * the transformation from the *parent* KDL::Tree link to the the reference * frame of the FT measurement ( H_p_s ) such that given the measure f_s, the * wrench applied by the parent on the child expressed in the parent frame ( f_p ) * is given by f_p = H_p_s f_s * */ class FTSensor { private: const KDL::CoDyCo::TreeGraph * tree_graph; std::string fixed_joint_name; KDL::Frame H_parent_sensor; int parent; int child; int sensor_id; public: FTSensor(const KDL::CoDyCo::TreeGraph & _tree_graph, const std::string _fixed_joint_name, const int _parent, const int _child, const int _sensor_id) : tree_graph(&_tree_graph), fixed_joint_name(_fixed_joint_name), H_parent_sensor(KDL::Frame::Identity()), parent(_parent), child(_child), sensor_id(_sensor_id) {} FTSensor(const KDL::CoDyCo::TreeGraph & _tree_graph, const std::string _fixed_joint_name, const KDL::Frame _H_parent_sensor, const int _parent, const int _child, const int _sensor_id) : tree_graph(&_tree_graph), fixed_joint_name(_fixed_joint_name), H_parent_sensor(_H_parent_sensor), parent(_parent), child(_child), sensor_id(_sensor_id) {} ~FTSensor() {} std::string getName() const { return fixed_joint_name; } /** * For the given current_link, get the wrench excerted on the subgraph * as measured by the FT sensor */ KDL::Wrench getWrenchExcertedOnSubGraph(int current_link, const std::vector<KDL::Wrench> & measured_wrenches ) const { if( current_link == parent ) { return -(H_parent_sensor*measured_wrenches[sensor_id]); } else { //The junction connected to an F/T sensor should be one with 0 DOF assert(tree_graph->getLink(child)->getAdjacentJoint(tree_graph->getLink(parent))->joint.getType() == KDL::Joint::None ); KDL::Frame H_child_parent = tree_graph->getLink(parent)->pose(tree_graph->getLink(child),0.0); assert(current_link == child); return (H_child_parent*(H_parent_sensor*measured_wrenches[sensor_id])); } } KDL::Frame getH_parent_sensor() const { return H_parent_sensor; } KDL::Frame getH_child_sensor() const { assert(tree_graph->getLink(child)->getAdjacentJoint(tree_graph->getLink(parent))->joint.getType() == KDL::Joint::None ); assert(tree_graph->getLink(parent)->getAdjacentJoint(tree_graph->getLink(child))->joint.getType() == KDL::Joint::None ); KDL::Frame H_child_parent = tree_graph->getLink(parent)->pose(tree_graph->getLink(child),0.0); return H_child_parent*H_parent_sensor; } KDL::Frame getH_link_sensor(int link_id) const { assert(link_id == parent || link_id == child); if( link_id == parent ) { return getH_parent_sensor(); } else if ( link_id == child ) { return getH_child_sensor(); } else { assert(false); return KDL::Frame(); } } int getChild() const { return child; } int getParent() const { return parent; } int getID() const { return sensor_id; } }; class FTSensorList { private: std::vector< std::vector<const FTSensor *> > link_FT_sensors; std::vector< int > junction_id2ft_sensor_id; public: std::vector< FTSensor * > ft_sensors_vector; int getNrOfFTSensors() const { return ft_sensors_vector.size(); } FTSensorList() { ft_sensors_vector.clear(); link_FT_sensors.clear(); junction_id2ft_sensor_id.clear(); } FTSensorList(const KDL::CoDyCo::TreeGraph & tree_graph, const std::vector<std::string> & ft_names) { link_FT_sensors.clear(); link_FT_sensors.resize(tree_graph.getNrOfLinks(),std::vector<const FTSensor *>(0)); junction_id2ft_sensor_id.clear(); junction_id2ft_sensor_id.resize(tree_graph.getNrOfJunctions(),-1); for(int i=0; i < (int)ft_names.size(); i++ ) { KDL::CoDyCo::JunctionMap::const_iterator junction_it = tree_graph.getJunction(ft_names[i]); if( junction_it == tree_graph.getInvalidJunctionIterator() ) { link_FT_sensors.clear(); junction_id2ft_sensor_id.clear(); ft_sensors_vector.clear(); return; } int parent_id = junction_it->parent->link_nr; int child_id = junction_it->child->link_nr; int sensor_id = i; #ifndef NDEBUG //std::cout << "Adding FT sensor " << i << "That connects " << parent_id << " and " << child_id << std::endl; #endif ft_sensors_vector.push_back(new FTSensor(tree_graph,ft_names[i],parent_id,child_id,sensor_id)); #ifndef NDEBUG //std::cout << "that have name " << ft_sensors_vector[i]->getName() << std::endl; #endif link_FT_sensors[parent_id].push_back((ft_sensors_vector[i])); link_FT_sensors[child_id].push_back((ft_sensors_vector[i])); junction_id2ft_sensor_id[junction_it->getJunctionIndex()] = sensor_id; #ifndef NDEBUG //std::cout << toString() << std::endl; #endif } return; } KDL::Wrench getMeasuredWrench(int link_id, const std::vector< KDL::Wrench > & measured_wrenches) const { KDL::Wrench ret = KDL::Wrench::Zero(); for(int i = 0; i < (int)link_FT_sensors[link_id].size(); i++ ) { ret += link_FT_sensors[link_id][i]->getWrenchExcertedOnSubGraph(link_id,measured_wrenches); } return ret; } bool isFTSensor(int junction_index) const { return ( junction_id2ft_sensor_id[junction_index] >= 0); } int getFTSensorID(int junction_index) const { return junction_id2ft_sensor_id[junction_index]; } std::vector<const FTSensor *> getFTSensorsOnLink(int link_index) const { /* if( link_index < 0 || link_index >= tree_graph.getNrOfLinks() ) { /// \todo add verbose option #ifndef NDEBUG std::cerr << "FTSensorList::getFTSensorsOnLink error: link index out of bounds" << std::endl; #endif return std::vector<FTSensor *>(0); }*/ return link_FT_sensors[link_index]; } int getNrOfFTSensorsOnLink(int link_index) const { if( getNrOfFTSensors() == 0 ) { return 0; } /* if( link_index < 0 || link_index >= tree_graph->getNrOfLinks() ) { /// \todo add verbose option #ifndef NDEBUG std::cerr << "FTSensorList::getNrOfFTSensorsOnLink error: link index out of bounds" << std::endl; #endif return 0; }*/ return link_FT_sensors[link_index].size(); } /** * Given a std::vector<KDL::Wrench> calculate by the dynamic phase of the RNEA, and the corresponding * Traversal, get the consequent sensor wrench * */ KDL::Wrench estimateSensorWrenchFromRNEA(int ft_sensor_id, KDL::CoDyCo::Traversal & dynamic_traversal, std::vector<KDL::Wrench> f) { #ifndef NDEBUG //std::cerr << "estimateSensorWrenchFromRNEA ft_sensor_id " << ft_sensor_id << std::endl; //std::cerr << "is ft_sensor " << ft_sensors_vector[ft_sensor_id]->getName() << " ( " << ft_sensor_id << " ) that connects " //<< ft_sensors_vector[ft_sensor_id]->getParent() << " and " << ft_sensors_vector[ft_sensor_id]->getChild() << std::endl; #endif int child_id = ft_sensors_vector[ft_sensor_id]->getChild(); int parent_id = ft_sensors_vector[ft_sensor_id]->getParent(); if( parent_id == dynamic_traversal.parent[child_id]->getLinkIndex() ) { return ft_sensors_vector[ft_sensor_id]->getH_child_sensor().Inverse(f[child_id]); } else if (child_id == dynamic_traversal.parent[parent_id]->getLinkIndex() ) { return -ft_sensors_vector[ft_sensor_id]->getH_parent_sensor().Inverse(f[parent_id]); } else { assert(false); return KDL::Wrench::Zero(); } } std::string toString() const { std::stringstream ss; for(int i=0; i < ft_sensors_vector.size(); i++ ) { int parent_id = ft_sensors_vector[i]->getParent(); int child_id = ft_sensors_vector[i]->getChild(); ss << "FT sensor " << i << " ( " << ft_sensors_vector[i]->getName() << " ) " << " connects links " << parent_id << " and " << child_id << std::endl; ss << "Link " << parent_id << "has sensor " << link_FT_sensors[parent_id][0]->getID() << std::endl; ss << "Link " << child_id << "has sensor " << link_FT_sensors[child_id][0]->getID() << std::endl; } return ss.str(); } }; } } #endif <commit_msg>Update ftsensor.hpp<commit_after>/** * Copyright (C) 2013 IIT - Istituto Italiano di Tecnologia - http://www.iit.it * Author: Silvio Traversaro * CopyPolicy: Released under the terms of the GNU LGPL v2.0 (or any later version) * * The development of this software was supported by the FP7 EU project * CoDyCo (No. 600716 ICT 2011.2.1 Cognitive Systems and Robotics (b)) * http://www.codyco.eu */ #ifndef _KDL_CODYCO_FT_SENSOR_ #define _KDL_CODYCO_FT_SENSOR_ #ifndef NDEBUG #include <iostream> #endif #include <sstream> namespace KDL { namespace CoDyCo { /** * * \todo fix copy operator * * Data structure for containing information about internal FT sensors * To properly describe an FT sensor, it is necessary: * * the fixed junction of the FT sensor in the TreeGraph (a name) * * the transformation from the *parent* KDL::Tree link to the the reference * frame of the FT measurement ( H_p_s ) such that given the measure f_s, the * wrench applied by the parent on the child expressed in the parent frame ( f_p ) * is given by f_p = H_p_s f_s * */ class FTSensor { private: const KDL::CoDyCo::TreeGraph * tree_graph; std::string fixed_joint_name; KDL::Frame H_parent_sensor; int parent; int child; int sensor_id; public: FTSensor(const KDL::CoDyCo::TreeGraph & _tree_graph, const std::string _fixed_joint_name, const int _parent, const int _child, const int _sensor_id) : tree_graph(&_tree_graph), fixed_joint_name(_fixed_joint_name), H_parent_sensor(KDL::Frame::Identity()), parent(_parent), child(_child), sensor_id(_sensor_id) {} FTSensor(const KDL::CoDyCo::TreeGraph & _tree_graph, const std::string _fixed_joint_name, const KDL::Frame _H_parent_sensor, const int _parent, const int _child, const int _sensor_id) : tree_graph(&_tree_graph), fixed_joint_name(_fixed_joint_name), H_parent_sensor(_H_parent_sensor), parent(_parent), child(_child), sensor_id(_sensor_id) {} ~FTSensor() {} std::string getName() const { return fixed_joint_name; } /** * For the given current_link, get the wrench excerted on the subgraph * as measured by the FT sensor */ KDL::Wrench getWrenchExcertedOnSubGraph(int current_link, const std::vector<KDL::Wrench> & measured_wrenches ) const { if( current_link == parent ) { return -(H_parent_sensor*measured_wrenches[sensor_id]); } else { //The junction connected to an F/T sensor should be one with 0 DOF assert(tree_graph->getLink(child)->getAdjacentJoint(tree_graph->getLink(parent))->joint.getType() == KDL::Joint::None ); KDL::Frame H_child_parent = tree_graph->getLink(parent)->pose(tree_graph->getLink(child),0.0); assert(current_link == child); return (H_child_parent*(H_parent_sensor*measured_wrenches[sensor_id])); } } KDL::Frame getH_parent_sensor() const { return H_parent_sensor; } KDL::Frame getH_child_sensor() const { assert(tree_graph->getLink(child)->getAdjacentJoint(tree_graph->getLink(parent))->joint.getType() == KDL::Joint::None ); assert(tree_graph->getLink(parent)->getAdjacentJoint(tree_graph->getLink(child))->joint.getType() == KDL::Joint::None ); KDL::Frame H_child_parent = tree_graph->getLink(parent)->pose(tree_graph->getLink(child),0.0); return H_child_parent*H_parent_sensor; } KDL::Frame getH_link_sensor(int link_id) const { assert(link_id == parent || link_id == child); if( link_id == parent ) { return getH_parent_sensor(); } else if ( link_id == child ) { return getH_child_sensor(); } else { assert(false); return KDL::Frame(); } } int getChild() const { return child; } int getParent() const { return parent; } int getID() const { return sensor_id; } }; class FTSensorList { private: std::vector< std::vector<const FTSensor *> > link_FT_sensors; std::vector< int > junction_id2ft_sensor_id; public: std::vector< FTSensor * > ft_sensors_vector; int getNrOfFTSensors() const { return ft_sensors_vector.size(); } FTSensorList() { ft_sensors_vector.clear(); link_FT_sensors.clear(); junction_id2ft_sensor_id.clear(); } FTSensorList(const KDL::CoDyCo::TreeGraph & tree_graph, const std::vector<std::string> & ft_names) { link_FT_sensors.clear(); link_FT_sensors.resize(tree_graph.getNrOfLinks(),std::vector<const FTSensor *>(0)); junction_id2ft_sensor_id.clear(); junction_id2ft_sensor_id.resize(tree_graph.getNrOfJunctions(),-1); for(int i=0; i < (int)ft_names.size(); i++ ) { KDL::CoDyCo::JunctionMap::const_iterator junction_it = tree_graph.getJunction(ft_names[i]); if( junction_it == tree_graph.getInvalidJunctionIterator() ) { link_FT_sensors.clear(); junction_id2ft_sensor_id.clear(); ft_sensors_vector.clear(); return; } int parent_id = junction_it->parent->link_nr; int child_id = junction_it->child->link_nr; int sensor_id = i; #ifndef NDEBUG //std::cout << "Adding FT sensor " << i << "That connects " << parent_id << " and " << child_id << std::endl; #endif ft_sensors_vector.push_back(new FTSensor(tree_graph,ft_names[i],parent_id,child_id,sensor_id)); #ifndef NDEBUG //std::cout << "that have name " << ft_sensors_vector[i]->getName() << std::endl; #endif link_FT_sensors[parent_id].push_back((ft_sensors_vector[i])); link_FT_sensors[child_id].push_back((ft_sensors_vector[i])); junction_id2ft_sensor_id[junction_it->getJunctionIndex()] = sensor_id; #ifndef NDEBUG //std::cout << toString() << std::endl; #endif } return; } KDL::Wrench getMeasuredWrench(int link_id, const std::vector< KDL::Wrench > & measured_wrenches) const { KDL::Wrench ret = KDL::Wrench::Zero(); for(int i = 0; i < (int)link_FT_sensors[link_id].size(); i++ ) { ret += link_FT_sensors[link_id][i]->getWrenchExcertedOnSubGraph(link_id,measured_wrenches); } return ret; } bool isFTSensor(int junction_index) const { return ( junction_id2ft_sensor_id[junction_index] >= 0); } int getFTSensorID(int junction_index) const { return junction_id2ft_sensor_id[junction_index]; } std::vector<const FTSensor *> getFTSensorsOnLink(int link_index) const { /* if( link_index < 0 || link_index >= tree_graph.getNrOfLinks() ) { /// \todo add verbose option #ifndef NDEBUG std::cerr << "FTSensorList::getFTSensorsOnLink error: link index out of bounds" << std::endl; #endif return std::vector<FTSensor *>(0); }*/ return link_FT_sensors[link_index]; } int getNrOfFTSensorsOnLink(int link_index) const { if( getNrOfFTSensors() == 0 ) { return 0; } /* if( link_index < 0 || link_index >= tree_graph->getNrOfLinks() ) { /// \todo add verbose option #ifndef NDEBUG std::cerr << "FTSensorList::getNrOfFTSensorsOnLink error: link index out of bounds" << std::endl; #endif return 0; }*/ return link_FT_sensors[link_index].size(); } /** * Given a std::vector<KDL::Wrench> calculate by the dynamic phase of the RNEA, and the corresponding * Traversal, get the consequent sensor wrench * */ KDL::Wrench estimateSensorWrenchFromRNEA(int ft_sensor_id, KDL::CoDyCo::Traversal & dynamic_traversal, std::vector<KDL::Wrench> f) { #ifndef NDEBUG //std::cerr << "estimateSensorWrenchFromRNEA ft_sensor_id " << ft_sensor_id << std::endl; //std::cerr << "is ft_sensor " << ft_sensors_vector[ft_sensor_id]->getName() << " ( " << ft_sensor_id << " ) that connects " //<< ft_sensors_vector[ft_sensor_id]->getParent() << " and " << ft_sensors_vector[ft_sensor_id]->getChild() << std::endl; #endif int child_id = ft_sensors_vector[ft_sensor_id]->getChild(); int parent_id = ft_sensors_vector[ft_sensor_id]->getParent(); if( parent_id == dynamic_traversal.parent[child_id]->getLinkIndex() ) { return ft_sensors_vector[ft_sensor_id]->getH_child_sensor().Inverse(f[child_id]); } else if (child_id == dynamic_traversal.parent[parent_id]->getLinkIndex() ) { return -ft_sensors_vector[ft_sensor_id]->getH_parent_sensor().Inverse(f[parent_id]); } else { assert(false); return KDL::Wrench::Zero(); } } std::string toString() const { std::stringstream ss; for(int i=0; i < (int)ft_sensors_vector.size(); i++ ) { int parent_id = ft_sensors_vector[i]->getParent(); int child_id = ft_sensors_vector[i]->getChild(); ss << "FT sensor " << i << " ( " << ft_sensors_vector[i]->getName() << " ) " << " connects links " << parent_id << " and " << child_id << std::endl; ss << "Link " << parent_id << "has sensor " << link_FT_sensors[parent_id][0]->getID() << std::endl; ss << "Link " << child_id << "has sensor " << link_FT_sensors[child_id][0]->getID() << std::endl; } return ss.str(); } }; } } #endif <|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. */ #ifndef TORRENT_BITFIELD_HPP_INCLUDED #define TORRENT_BITFIELD_HPP_INCLUDED #include "libtorrent/assert.hpp" #include "libtorrent/config.hpp" #include <cstring> // for memset and memcpy #include <cstdlib> // for malloc, free and realloc namespace libtorrent { struct TORRENT_EXPORT bitfield { bitfield(): m_bytes(0), m_size(0), m_own(false) {} bitfield(int bits): m_bytes(0), m_size(0), m_own(false) { resize(bits); } bitfield(int bits, bool val): m_bytes(0), m_size(0), m_own(false) { resize(bits, val); } bitfield(char const* b, int bits): m_bytes(0), m_size(0), m_own(false) { assign(b, bits); } bitfield(bitfield const& rhs): m_bytes(0), m_size(0), m_own(false) { assign(rhs.bytes(), rhs.size()); } void borrow_bytes(char* b, int bits) { dealloc(); m_bytes = (unsigned char*)b; m_size = bits; m_own = false; } ~bitfield() { dealloc(); } void assign(char const* b, int bits) { resize(bits); std::memcpy(m_bytes, b, (bits + 7) / 8); clear_trailing_bits(); } bool operator[](int index) const { return get_bit(index); } bool get_bit(int index) const { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); return (m_bytes[index / 8] & (0x80 >> (index & 7))) != 0; } void clear_bit(int index) { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); m_bytes[index / 8] &= ~(0x80 >> (index & 7)); } void set_bit(int index) { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); m_bytes[index / 8] |= (0x80 >> (index & 7)); } std::size_t size() const { return m_size; } bool empty() const { return m_size == 0; } char const* bytes() const { return (char*)m_bytes; } bitfield& operator=(bitfield const& rhs) { assign(rhs.bytes(), rhs.size()); return *this; } int count() const { // 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, // 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111 const static char num_bits[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; int ret = 0; const int num_bytes = m_size / 8; for (int i = 0; i < num_bytes; ++i) { ret += num_bits[m_bytes[i] & 0xf] + num_bits[m_bytes[i] >> 4]; } int rest = m_size - num_bytes * 8; for (int i = 0; i < rest; ++i) { ret += (m_bytes[num_bytes] >> (7-i)) & 1; } TORRENT_ASSERT(ret <= m_size); TORRENT_ASSERT(ret >= 0); return ret; } struct const_iterator { friend struct bitfield; typedef bool value_type; typedef ptrdiff_t difference_type; typedef bool const* pointer; typedef bool& reference; typedef std::forward_iterator_tag iterator_category; bool operator*() { return (*byte & bit) != 0; } const_iterator& operator++() { inc(); return *this; } const_iterator operator++(int) { const_iterator ret(*this); inc(); return ret; } const_iterator& operator--() { dec(); return *this; } const_iterator operator--(int) { const_iterator ret(*this); dec(); return ret; } const_iterator(): byte(0), bit(0x80) {} bool operator==(const_iterator const& rhs) const { return byte == rhs.byte && bit == rhs.bit; } bool operator!=(const_iterator const& rhs) const { return byte != rhs.byte || bit != rhs.bit; } private: void inc() { TORRENT_ASSERT(byte); if (bit == 0x01) { bit = 0x80; ++byte; } else { bit >>= 1; } } void dec() { TORRENT_ASSERT(byte); if (bit == 0x80) { bit = 0x01; --byte; } else { bit <<= 1; } } const_iterator(unsigned char const* ptr, int offset) : byte(ptr), bit(0x80 >> offset) {} unsigned char const* byte; int bit; }; const_iterator begin() const { return const_iterator(m_bytes, 0); } const_iterator end() const { return const_iterator(m_bytes + m_size / 8, m_size & 7); } void resize(int bits, bool val) { int s = m_size; int b = m_size & 7; resize(bits); if (s >= m_size) return; int old_size_bytes = (s + 7) / 8; int new_size_bytes = (m_size + 7) / 8; if (val) { if (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b); if (old_size_bytes < new_size_bytes) std::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes); clear_trailing_bits(); } else { if (old_size_bytes < new_size_bytes) std::memset(m_bytes + old_size_bytes, 0x00, new_size_bytes - old_size_bytes); } } void set_all() { std::memset(m_bytes, 0xff, (m_size + 7) / 8); clear_trailing_bits(); } void clear_all() { std::memset(m_bytes, 0x00, (m_size + 7) / 8); } void resize(int bits) { const int b = (bits + 7) / 8; if (m_bytes) { if (m_own) { m_bytes = (unsigned char*)std::realloc(m_bytes, b); m_own = true; } else if (bits > m_size) { unsigned char* tmp = (unsigned char*)std::malloc(b); std::memcpy(tmp, m_bytes, (std::min)(int(m_size + 7)/ 8, b)); m_bytes = tmp; m_own = true; } } else { m_bytes = (unsigned char*)std::malloc(b); m_own = true; } m_size = bits; clear_trailing_bits(); } void free() { dealloc(); m_size = 0; } private: void clear_trailing_bits() { // clear the tail bits in the last byte if (m_size & 7) m_bytes[(m_size + 7) / 8 - 1] &= 0xff << (8 - (m_size & 7)); } void dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; } unsigned char* m_bytes; int m_size:31; // in bits bool m_own:1; }; } #endif // TORRENT_BITFIELD_HPP_INCLUDED <commit_msg>make electric fence happy by not allocating 0 bytes<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. */ #ifndef TORRENT_BITFIELD_HPP_INCLUDED #define TORRENT_BITFIELD_HPP_INCLUDED #include "libtorrent/assert.hpp" #include "libtorrent/config.hpp" #include <cstring> // for memset and memcpy #include <cstdlib> // for malloc, free and realloc namespace libtorrent { struct TORRENT_EXPORT bitfield { bitfield(): m_bytes(0), m_size(0), m_own(false) {} bitfield(int bits): m_bytes(0), m_size(0), m_own(false) { resize(bits); } bitfield(int bits, bool val): m_bytes(0), m_size(0), m_own(false) { resize(bits, val); } bitfield(char const* b, int bits): m_bytes(0), m_size(0), m_own(false) { assign(b, bits); } bitfield(bitfield const& rhs): m_bytes(0), m_size(0), m_own(false) { assign(rhs.bytes(), rhs.size()); } void borrow_bytes(char* b, int bits) { dealloc(); m_bytes = (unsigned char*)b; m_size = bits; m_own = false; } ~bitfield() { dealloc(); } void assign(char const* b, int bits) { resize(bits); std::memcpy(m_bytes, b, (bits + 7) / 8); clear_trailing_bits(); } bool operator[](int index) const { return get_bit(index); } bool get_bit(int index) const { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); return (m_bytes[index / 8] & (0x80 >> (index & 7))) != 0; } void clear_bit(int index) { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); m_bytes[index / 8] &= ~(0x80 >> (index & 7)); } void set_bit(int index) { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); m_bytes[index / 8] |= (0x80 >> (index & 7)); } std::size_t size() const { return m_size; } bool empty() const { return m_size == 0; } char const* bytes() const { return (char*)m_bytes; } bitfield& operator=(bitfield const& rhs) { assign(rhs.bytes(), rhs.size()); return *this; } int count() const { // 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, // 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111 const static char num_bits[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; int ret = 0; const int num_bytes = m_size / 8; for (int i = 0; i < num_bytes; ++i) { ret += num_bits[m_bytes[i] & 0xf] + num_bits[m_bytes[i] >> 4]; } int rest = m_size - num_bytes * 8; for (int i = 0; i < rest; ++i) { ret += (m_bytes[num_bytes] >> (7-i)) & 1; } TORRENT_ASSERT(ret <= m_size); TORRENT_ASSERT(ret >= 0); return ret; } struct const_iterator { friend struct bitfield; typedef bool value_type; typedef ptrdiff_t difference_type; typedef bool const* pointer; typedef bool& reference; typedef std::forward_iterator_tag iterator_category; bool operator*() { return (*byte & bit) != 0; } const_iterator& operator++() { inc(); return *this; } const_iterator operator++(int) { const_iterator ret(*this); inc(); return ret; } const_iterator& operator--() { dec(); return *this; } const_iterator operator--(int) { const_iterator ret(*this); dec(); return ret; } const_iterator(): byte(0), bit(0x80) {} bool operator==(const_iterator const& rhs) const { return byte == rhs.byte && bit == rhs.bit; } bool operator!=(const_iterator const& rhs) const { return byte != rhs.byte || bit != rhs.bit; } private: void inc() { TORRENT_ASSERT(byte); if (bit == 0x01) { bit = 0x80; ++byte; } else { bit >>= 1; } } void dec() { TORRENT_ASSERT(byte); if (bit == 0x80) { bit = 0x01; --byte; } else { bit <<= 1; } } const_iterator(unsigned char const* ptr, int offset) : byte(ptr), bit(0x80 >> offset) {} unsigned char const* byte; int bit; }; const_iterator begin() const { return const_iterator(m_bytes, 0); } const_iterator end() const { return const_iterator(m_bytes + m_size / 8, m_size & 7); } void resize(int bits, bool val) { int s = m_size; int b = m_size & 7; resize(bits); if (s >= m_size) return; int old_size_bytes = (s + 7) / 8; int new_size_bytes = (m_size + 7) / 8; if (val) { if (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b); if (old_size_bytes < new_size_bytes) std::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes); clear_trailing_bits(); } else { if (old_size_bytes < new_size_bytes) std::memset(m_bytes + old_size_bytes, 0x00, new_size_bytes - old_size_bytes); } } void set_all() { std::memset(m_bytes, 0xff, (m_size + 7) / 8); clear_trailing_bits(); } void clear_all() { std::memset(m_bytes, 0x00, (m_size + 7) / 8); } void resize(int bits) { TORRENT_ASSERT(bits >= 0); const int b = (bits + 7) / 8; if (m_bytes) { if (m_own) { m_bytes = (unsigned char*)std::realloc(m_bytes, b); m_own = true; } else if (bits > m_size) { unsigned char* tmp = (unsigned char*)std::malloc(b); std::memcpy(tmp, m_bytes, (std::min)(int(m_size + 7)/ 8, b)); m_bytes = tmp; m_own = true; } } else if (bits > 0) { m_bytes = (unsigned char*)std::malloc(b); m_own = true; } m_size = bits; clear_trailing_bits(); } void free() { dealloc(); m_size = 0; } private: void clear_trailing_bits() { // clear the tail bits in the last byte if (m_size & 7) m_bytes[(m_size + 7) / 8 - 1] &= 0xff << (8 - (m_size & 7)); } void dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; } unsigned char* m_bytes; int m_size:31; // in bits bool m_own:1; }; } #endif // TORRENT_BITFIELD_HPP_INCLUDED <|endoftext|>
<commit_before>/***************************************************************************** (c) 2013 Hobu, Inc. hobu.inc@gmail.com Author: Uday Verma uday dot karan at gmail dot com This is free software; you can redistribute and/or modify it under the terms of the GNU Lesser General Licence as published by the Free Software Foundation. See the COPYING file for more information. This software is distributed WITHOUT ANY WARRANTY and without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *****************************************************************************/ #ifndef INCLUDED_HEXER_LASFILE_HPP #define INCLUDED_HEXER_LASFILE_HPP #include <boost/noncopyable.hpp> #include <boost/interprocess/file_mapping.hpp> #include <boost/interprocess/mapped_region.hpp> #include <boost/shared_ptr.hpp> #include <boost/algorithm/string.hpp> #include <algorithm> #include <stdexcept> class las_file : public boost::noncopyable { public: las_file() : is_open_(false) { } ~las_file() { close(); } void open(const std::string& filename, int offset = 0, int count = -1) { using namespace boost::interprocess; start_offset_ = offset; count_ = count; pmapping_.reset(new file_mapping(filename.c_str(), read_only)); pregion_.reset(new mapped_region(*pmapping_, read_only)); void *addr = pregion_->get_address(); std::string magic((char *)addr, (char *)addr + 4); if (!boost::iequals(magic, "LASF")) { throw std::runtime_error("Not a las file"); } char versionMajor = readAs<char>(24); char versionMinor = readAs<char>(25); if ((int)(versionMajor * 10 + versionMinor) >= 13) { throw std::runtime_error("Only version 1.0-1.2 files are supported"); } points_offset_ = readAs<unsigned int>(32*3); points_format_id_ = readAs<unsigned char>(32*3 + 8); points_struct_size_ = readAs<unsigned short>(32*3 + 8 + 1); points_count_ = readAs<unsigned int>(32*3 + 11); // std::cerr << "points count: " << points_count_ << std::endl; size_t start = 32*3 + 35; readN(start, scale_, 3); start += sizeof(double) * 3; readN(start, offset_, 3); start += sizeof(double) * 3; maxs_[0] = readAs<double>(start); mins_[0] = readAs<double>(start + sizeof(double)); start += 2*sizeof(double); maxs_[1] = readAs<double>(start); mins_[1] = readAs<double>(start + sizeof(double)); start += 2*sizeof(double); maxs_[2] = readAs<double>(start); mins_[2] = readAs<double>(start + sizeof(double)); start += 2*sizeof(double); // std::cerr << "region size: " << pregion_->get_size() << std::endl; // std::cerr << "points offset: " << points_offset_ << std::endl; uint64_t diff = pregion_->get_size() - points_offset_; if (diff % stride() != 0) throw std::runtime_error("Point record data size is inconsistent"); if (diff / stride() != points_count_) throw std::runtime_error("Point record count is inconsistent with computed point records size"); updateMinsMaxes(); is_open_ = true; } size_t size() { return pregion_->get_size(); } void *points_offset() { return (char *)pregion_->get_address() + points_offset_ + start_offset_; } void close() { pregion_.reset(); pmapping_.reset(); is_open_ = false; } size_t stride() { if (points_struct_size_ != 0) return points_struct_size_; switch(points_format_id_) { case 2: return 26; case 3: return 26+2; default: break; } throw std::runtime_error("Unknown point format"); } size_t points_count() const { if (count_ == -1) return points_count_; return std::min(points_count_, (unsigned int)count_); } double* minimums() { return mins_; } double* maximums() { return maxs_; } double *scale() { return scale_; } double *offset() { return offset_; } bool is_open() { return is_open_; } inline double getX(size_t point) { char *position = (char*)points_offset() + stride()* point; int *xi = (int *)position; double x = *xi * scale_[0] + offset_[0]; return x; } inline double getY(size_t point) { char *position = (char *)points_offset() + stride() * point + sizeof(int); int *yi = (int *)position; double y = *yi * scale_[1] + offset_[1]; return y; } inline double getZ(size_t point) { char *position = (char *)points_offset() + stride() * point + sizeof(int) + sizeof(int); int *zi = (int *)position; double z = *zi * scale_[2] + offset_[2]; return z; } private: void updateMinsMaxes() { if (start_offset_ == 0 && count_ == -1) return; // no update required if no subrange is requested int largest = std::numeric_limits<int>::max(); int smallest = std::numeric_limits<int>::min(); int n[3] = { largest, largest, largest }; int x[3] = { smallest, smallest, smallest }; char *ip = (char *)points_offset(); for (size_t i = 0 ; i < points_count() ; i ++) { int *p = (int *)ip; for (int j = 0 ; j < 3 ; j ++) { n[j] = std::min(n[j], p[j]); x[j] = std::max(x[j], p[j]); } ip += stride(); } for (int i = 0 ; i < 3 ; i++) { mins_[i] = n[i] * scale_[i] + offset_[i]; maxs_[i] = x[i] * scale_[i] + offset_[i]; } } template<typename T> T readAs(size_t offset) { return *((T*)((char*)pregion_->get_address() + offset)); } template<typename T> void readN(size_t offset, T* dest, size_t n) { char *buf = (char *)pregion_->get_address() + offset; for(size_t i = 0 ; i < n ; i ++) { dest[i] = *((T*)(buf + sizeof(T) * i)); } } private: boost::shared_ptr<boost::interprocess::file_mapping> pmapping_; boost::shared_ptr<boost::interprocess::mapped_region> pregion_; unsigned int start_offset_; int count_; unsigned int points_offset_; unsigned char points_format_id_; unsigned int points_count_; unsigned short points_struct_size_; double scale_[3], offset_[3], mins_[3], maxs_[3]; bool is_open_; }; #endif // __HEXER_LAS_H__ <commit_msg>handle some other LAS point format types if record length isn't specified<commit_after>/***************************************************************************** (c) 2013 Hobu, Inc. hobu.inc@gmail.com Author: Uday Verma uday dot karan at gmail dot com This is free software; you can redistribute and/or modify it under the terms of the GNU Lesser General Licence as published by the Free Software Foundation. See the COPYING file for more information. This software is distributed WITHOUT ANY WARRANTY and without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *****************************************************************************/ #ifndef INCLUDED_P2G_LASFILE_HPP #define INCLUDED_P2G_LASFILE_HPP #include <boost/noncopyable.hpp> #include <boost/interprocess/file_mapping.hpp> #include <boost/interprocess/mapped_region.hpp> #include <boost/shared_ptr.hpp> #include <boost/algorithm/string.hpp> #include <algorithm> #include <stdexcept> class las_file : public boost::noncopyable { public: las_file() : is_open_(false) { } ~las_file() { close(); } void open(const std::string& filename, int offset = 0, int count = -1) { using namespace boost::interprocess; start_offset_ = offset; count_ = count; pmapping_.reset(new file_mapping(filename.c_str(), read_only)); pregion_.reset(new mapped_region(*pmapping_, read_only)); void *addr = pregion_->get_address(); std::string magic((char *)addr, (char *)addr + 4); if (!boost::iequals(magic, "LASF")) { throw std::runtime_error("Not a las file"); } char versionMajor = readAs<char>(24); char versionMinor = readAs<char>(25); if ((int)(versionMajor * 10 + versionMinor) >= 13) { throw std::runtime_error("Only version 1.0-1.2 files are supported"); } points_offset_ = readAs<unsigned int>(32*3); points_format_id_ = readAs<unsigned char>(32*3 + 8); points_struct_size_ = readAs<unsigned short>(32*3 + 8 + 1); points_count_ = readAs<unsigned int>(32*3 + 11); // std::cerr << "points count: " << points_count_ << std::endl; size_t start = 32*3 + 35; readN(start, scale_, 3); start += sizeof(double) * 3; readN(start, offset_, 3); start += sizeof(double) * 3; maxs_[0] = readAs<double>(start); mins_[0] = readAs<double>(start + sizeof(double)); start += 2*sizeof(double); maxs_[1] = readAs<double>(start); mins_[1] = readAs<double>(start + sizeof(double)); start += 2*sizeof(double); maxs_[2] = readAs<double>(start); mins_[2] = readAs<double>(start + sizeof(double)); start += 2*sizeof(double); // std::cerr << "region size: " << pregion_->get_size() << std::endl; // std::cerr << "points offset: " << points_offset_ << std::endl; uint64_t diff = pregion_->get_size() - points_offset_; if (diff % stride() != 0) throw std::runtime_error("Point record data size is inconsistent"); if (diff / stride() != points_count_) throw std::runtime_error("Point record count is inconsistent with computed point records size"); updateMinsMaxes(); is_open_ = true; } size_t size() { return pregion_->get_size(); } void *points_offset() { return (char *)pregion_->get_address() + points_offset_ + start_offset_; } void close() { pregion_.reset(); pmapping_.reset(); is_open_ = false; } size_t stride() { if (points_struct_size_ != 0) return points_struct_size_; switch(points_format_id_) { case 0: return 20; case 1: return 28; case 2: return 26; case 3: return 28+6; default: break; } throw std::runtime_error("Unknown point format"); } size_t points_count() const { if (count_ == -1) return points_count_; return std::min(points_count_, (unsigned int)count_); } double* minimums() { return mins_; } double* maximums() { return maxs_; } double *scale() { return scale_; } double *offset() { return offset_; } bool is_open() { return is_open_; } inline double getX(size_t point) { char *position = (char*)points_offset() + stride()* point; int *xi = (int *)position; double x = *xi * scale_[0] + offset_[0]; return x; } inline double getY(size_t point) { char *position = (char *)points_offset() + stride() * point + sizeof(int); int *yi = (int *)position; double y = *yi * scale_[1] + offset_[1]; return y; } inline double getZ(size_t point) { char *position = (char *)points_offset() + stride() * point + sizeof(int) + sizeof(int); int *zi = (int *)position; double z = *zi * scale_[2] + offset_[2]; return z; } private: void updateMinsMaxes() { if (start_offset_ == 0 && count_ == -1) return; // no update required if no subrange is requested int largest = std::numeric_limits<int>::max(); int smallest = std::numeric_limits<int>::min(); int n[3] = { largest, largest, largest }; int x[3] = { smallest, smallest, smallest }; char *ip = (char *)points_offset(); for (size_t i = 0 ; i < points_count() ; i ++) { int *p = (int *)ip; for (int j = 0 ; j < 3 ; j ++) { n[j] = std::min(n[j], p[j]); x[j] = std::max(x[j], p[j]); } ip += stride(); } for (int i = 0 ; i < 3 ; i++) { mins_[i] = n[i] * scale_[i] + offset_[i]; maxs_[i] = x[i] * scale_[i] + offset_[i]; } } template<typename T> T readAs(size_t offset) { return *((T*)((char*)pregion_->get_address() + offset)); } template<typename T> void readN(size_t offset, T* dest, size_t n) { char *buf = (char *)pregion_->get_address() + offset; for(size_t i = 0 ; i < n ; i ++) { dest[i] = *((T*)(buf + sizeof(T) * i)); } } private: boost::shared_ptr<boost::interprocess::file_mapping> pmapping_; boost::shared_ptr<boost::interprocess::mapped_region> pregion_; unsigned int start_offset_; int count_; unsigned int points_offset_; unsigned char points_format_id_; unsigned int points_count_; unsigned short points_struct_size_; double scale_[3], offset_[3], mins_[3], maxs_[3]; bool is_open_; }; #endif // __HEXER_LAS_H__ <|endoftext|>
<commit_before>/* ************************************************************************* */ /* This file is part of Shard. */ /* */ /* Shard is free software: you can redistribute it and/or modify */ /* it under the terms of the GNU Affero General Public License as */ /* published by the Free Software Foundation. */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU Affero General Public License for more details. */ /* */ /* You should have received a copy of the GNU Affero General Public License */ /* along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ************************************************************************* */ #pragma once /* ************************************************************************* */ // Shard #include "shard/UniquePtr.hpp" #include "shard/tokenizer/Tokenizer.hpp" #include "shard/tokenizer/TokenType.hpp" #include "shard/ast/Module.hpp" #include "shard/ast/Stmt.hpp" #include "shard/ast/Expr.hpp" #include "shard/ast/Decl.hpp" /* ************************************************************************* */ namespace shard { inline namespace v1 { namespace parser { using namespace tokenizer; using namespace ast; /* ************************************************************************* */ /** * @brief Shard syntax analyzer. */ class Parser { private: Tokenizer m_tokenizer; /* ************************************************************************* */ public: /** * @brief constructs Parser which reads from file. */ explicit Parser(const Path& path): m_tokenizer(path){} /** * @brief constructs Parser which reads from String. */ explicit Parser(const String& source): m_tokenizer(source){} /* ************************************************************************* */ public: /** * @brief initiates syntax analysis on given source. */ UniquePtr<Module> parseModule(); /* ************************************************************************* */ private: /** * @brief parse statement. */ UniquePtr<Stmt> parseStmt(); /** * @brief parse If statement. */ UniquePtr<IfStmt> parseIfStmt(); /** * @brief parse For statement. */ UniquePtr<ForStmt> parseForStmt(); /** * @brief parse While statement. */ UniquePtr<WhileStmt> parseWhileStmt(); /** * @brief parse Switch statement. */ UniquePtr<SwitchStmt> parseSwitchStmt(); /** * @brief parse Do-While statement. */ UniquePtr<DoWhileStmt> parseDoWhileStmt(); /** * @brief parse Compound statement. */ UniquePtr<CompoundStmt> parseCompoundStmt(); /* ************************************************************************* */ private: /** * @brief parse declaration. */ UniquePtr<Decl> parseDecl(); /** * @brief parse Variable declaration. */ UniquePtr<VariableDecl> parseVariableDecl(); /** * @brief parse Function declaration. */ UniquePtr<FunctionDecl> parseFunctionDecl(); /** * @brief parse Class declaration. */ UniquePtr<ClassDecl> parseClassDecl(); /* ************************************************************************* */ private: /** * @brief parse expression. */ UniquePtr<Expr> parseExpr(); /** * @brief parse relational expression. */ UniquePtr<Expr> parseRelationalExpr(); /** * @brief parse additive expression. */ UniquePtr<Expr> parseAdditiveExpr(); /** * @brief parse multiplicative expression. */ UniquePtr<Expr> parseMultiplicativeExpr(); /** * @brief parse prefix unary expression. */ UniquePtr<Expr> parsePrefixUnaryExpr(); /** * @brief parse postfix unary expression. */ UniquePtr<Expr> parsePostfixUnaryExpr(); /** * @brief parse primary expression. */ UniquePtr<Expr> parsePrimaryExpr(); /** * @brief parse parenthesis expression. */ UniquePtr<Expr> parseParenExpr(); /* ************************************************************************* */ private: /* * @brief returns if current TokenType is tested TokenTypeType. */ inline bool is(TokenType type) noexcept { return m_tokenizer.get().getType() == type; } /** * @brief returns if current TokenType is one of tested TokenTypes. */ template<typename... Types> inline bool is(Types... options) noexcept { TokenType types[] {options...}; for (const TokenType option : types) { if (is(option)) { return true; } } return false; } /** * @brief returns if current TokenType is tested TokenType. * If so, moves to next token. */ inline bool match(TokenType type) noexcept { if (is(type)) { m_tokenizer.toss(); return true; } return false; } /** * @brief returns if current TokenType is one of tested TokenTypes. * If so, moves to next token. */ template<typename... Types> inline bool match(Types... options) noexcept { TokenType types[] {options...}; for (const TokenType option : types) { if (is(option)) { m_tokenizer.toss(); return true; } } return false; } }; /* ************************************************************************* */ } } } /* ************************************************************************* */<commit_msg>added function for checking keyword type<commit_after>/* ************************************************************************* */ /* This file is part of Shard. */ /* */ /* Shard is free software: you can redistribute it and/or modify */ /* it under the terms of the GNU Affero General Public License as */ /* published by the Free Software Foundation. */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU Affero General Public License for more details. */ /* */ /* You should have received a copy of the GNU Affero General Public License */ /* along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ************************************************************************* */ #pragma once /* ************************************************************************* */ // Shard #include "shard/UniquePtr.hpp" #include "shard/tokenizer/Tokenizer.hpp" #include "shard/tokenizer/TokenType.hpp" #include "shard/ast/Module.hpp" #include "shard/ast/Stmt.hpp" #include "shard/ast/Expr.hpp" #include "shard/ast/Decl.hpp" /* ************************************************************************* */ namespace shard { inline namespace v1 { namespace parser { using namespace tokenizer; using namespace ast; /* ************************************************************************* */ /** * @brief Shard syntax analyzer. */ class Parser { private: Tokenizer m_tokenizer; /* ************************************************************************* */ public: /** * @brief constructs Parser which reads from file. */ explicit Parser(const Path& path): m_tokenizer(path){} /** * @brief constructs Parser which reads from String. */ explicit Parser(const String& source): m_tokenizer(source){} /* ************************************************************************* */ public: /** * @brief initiates syntax analysis on given source. */ UniquePtr<Module> parseModule(); /* ************************************************************************* */ private: /** * @brief parse statement. */ UniquePtr<Stmt> parseStmt(); /** * @brief parse If statement. */ UniquePtr<IfStmt> parseIfStmt(); /** * @brief parse For statement. */ UniquePtr<ForStmt> parseForStmt(); /** * @brief parse While statement. */ UniquePtr<WhileStmt> parseWhileStmt(); /** * @brief parse Switch statement. */ UniquePtr<SwitchStmt> parseSwitchStmt(); /** * @brief parse Do-While statement. */ UniquePtr<DoWhileStmt> parseDoWhileStmt(); /** * @brief parse Compound statement. */ UniquePtr<CompoundStmt> parseCompoundStmt(); /* ************************************************************************* */ private: /** * @brief parse declaration. */ UniquePtr<Decl> parseDecl(); /** * @brief parse Variable declaration. */ UniquePtr<VariableDecl> parseVariableDecl(); /** * @brief parse Function declaration. */ UniquePtr<FunctionDecl> parseFunctionDecl(); /** * @brief parse Class declaration. */ UniquePtr<ClassDecl> parseClassDecl(); /* ************************************************************************* */ private: /** * @brief parse expression. */ UniquePtr<Expr> parseExpr(); /** * @brief parse relational expression. */ UniquePtr<Expr> parseRelationalExpr(); /** * @brief parse additive expression. */ UniquePtr<Expr> parseAdditiveExpr(); /** * @brief parse multiplicative expression. */ UniquePtr<Expr> parseMultiplicativeExpr(); /** * @brief parse prefix unary expression. */ UniquePtr<Expr> parsePrefixUnaryExpr(); /** * @brief parse postfix unary expression. */ UniquePtr<Expr> parsePostfixUnaryExpr(); /** * @brief parse primary expression. */ UniquePtr<Expr> parsePrimaryExpr(); /** * @brief parse parenthesis expression. */ UniquePtr<Expr> parseParenExpr(); /* ************************************************************************* */ private: /* * @brief returns if current TokenType is tested TokenType. */ inline bool is(TokenType type) const noexcept { return m_tokenizer.get().getType() == type; } /* * @brief returns if current TokenType is tested TokenType. */ inline bool is(KeywordType type) const noexcept { return is(TokenType::Keyword) && m_tokenizer.get().getKeywordType() == type; } /** * @brief returns if current TokenType is one of tested TokenTypes. */ template<typename... Types> inline bool is(Types... options) const noexcept { TokenType types[] {options...}; for (const TokenType option : types) { if (is(option)) { return true; } } return false; } /** * @brief returns if current TokenType is tested TokenType. * If so, moves to next token. */ inline bool match(TokenType type) noexcept { if (is(type)) { m_tokenizer.toss(); return true; } return false; } /** * @brief returns if current TokenType is one of tested TokenTypes. * If so, moves to next token. */ template<typename... Types> inline bool match(Types... options) noexcept { TokenType types[] {options...}; for (const TokenType option : types) { if (is(option)) { m_tokenizer.toss(); return true; } } return false; } }; /* ************************************************************************* */ } } } /* ************************************************************************* */<|endoftext|>
<commit_before>/* * Copyright 2016 Ivan Ryabov * * 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. */ /******************************************************************************* * libSolace: A OOP view for a heterogenious collection of variable sized elements * @file solace/variableSpan.hpp ******************************************************************************/ #pragma once #ifndef SOLACE_VARIABLESPAN_HPP #define SOLACE_VARIABLESPAN_HPP #include "solace/types.hpp" #include "solace/memoryView.hpp" #include "solace/byteReader.hpp" namespace Solace { enum class EncoderType { Natural, LittleEndian, BigEndian }; template<typename DatumSizeType, EncoderType E> struct TypedChunkReader; template<typename DatumSizeType, EncoderType E> struct TypedChunkReader { static MemoryView readChunk(MemoryView src, DatumSizeType& chunkSize) { ByteReader reader{src}; reader.read(&chunkSize); return reader.viewRemaining(); } }; template<typename DatumSizeType> struct TypedChunkReader<DatumSizeType, EncoderType::BigEndian> { static MemoryView readChunk(MemoryView src, DatumSizeType& chunkSize) { ByteReader reader{src}; reader.readBE(&chunkSize); return reader.viewRemaining(); } }; template<typename DatumSizeType> struct TypedChunkReader<DatumSizeType, EncoderType::LittleEndian> { static MemoryView readChunk(MemoryView src, DatumSizeType& chunkSize) { ByteReader reader{src}; reader.readLE(&chunkSize); return reader.viewRemaining(); } }; template<typename T, typename DatumSizeType = uint16, EncoderType E = EncoderType::Natural> struct VariableSpan { static_assert(std::is_constructible_v<T, MemoryView>, "Type must be contructable from MemoryView"); using value_type = T; using size_type = uint16; using datum_size = DatumSizeType; using reference = T&; using const_reference = T const&; using pointer_type = T*; using const_pointer = T const*; struct Iterator { Iterator(size_type nElements, MemoryView dataView) : _nElements{nElements} , _data{dataView} {} constexpr Iterator(Iterator const& rhs) noexcept = default; constexpr Iterator(Iterator&& rhs) noexcept = default; Iterator& operator= (Iterator const& rhs) noexcept = default; Iterator& operator= (Iterator&& rhs) noexcept { return swap(rhs); } constexpr bool operator!= (Iterator const& other) const noexcept { return !(operator==(other)); } constexpr bool operator== (Iterator const& other) const noexcept { return (_nElements == other._nElements); } Iterator& operator++ () { if (0 == _nElements) { return *this; // Nowhere to go } datum_size datumSize = 0; auto tail = TypedChunkReader<datum_size, E>::readChunk(_data, datumSize); _data = tail.slice(datumSize, tail.size()); // skip datumSize _nElements -= 1; return *this; } value_type operator-> () const { assertTrue(0 < _nElements, "Index out of bounds"); datum_size datumSize = 0; auto tail = TypedChunkReader<datum_size, E>::readChunk(_data, datumSize); auto data = tail.slice(0, datumSize); return value_type{data}; } value_type operator* () const { return operator ->(); } private: size_type _nElements; MemoryView _data; }; using const_iterator = Iterator const; constexpr VariableSpan() noexcept = default; VariableSpan(size_type nElements, MemoryView data) noexcept : _nElements{nElements} , _data{mv(data)} {} /** * Check if this collection is empty. * @return True is this is an empty collection. */ constexpr bool empty() const noexcept { return (_nElements == 0); } /** * Get the number of elements in this collection. * @return number of elements in this collection. */ constexpr size_type size() const noexcept { return _nElements; } Iterator begin() noexcept { return Iterator{_nElements, _data}; } Iterator end() noexcept { return Iterator{0, _data}; } const_iterator begin() const noexcept { return Iterator{_nElements, _data}; } const_iterator end() const noexcept { return Iterator{0, _data}; } private: /// Number of elements in the span size_type _nElements; /// Start of the data MemoryView _data; }; } // namespace Solace #endif // SOLACE_VARIABLESPAN_HPP <commit_msg>Fixed varSpan endianness specializations<commit_after>/* * Copyright 2016 Ivan Ryabov * * 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. */ /******************************************************************************* * libSolace: A OOP view for a heterogenious collection of variable sized elements * @file solace/variableSpan.hpp ******************************************************************************/ #pragma once #ifndef SOLACE_VARIABLESPAN_HPP #define SOLACE_VARIABLESPAN_HPP #include "solace/types.hpp" #include "solace/memoryView.hpp" #include "solace/byteReader.hpp" namespace Solace { enum class EncoderType { Natural, LittleEndian, BigEndian }; template<typename DatumSizeType, EncoderType E> struct TypedChunkReader; template<typename DatumSizeType, EncoderType E> struct TypedChunkReader { static MemoryView readChunk(MemoryView src, DatumSizeType& chunkSize) { ByteReader reader{src}; reader.read(&chunkSize); return reader.viewRemaining(); } }; template<typename DatumSizeType> struct TypedChunkReader<DatumSizeType, EncoderType::BigEndian> { static MemoryView readChunk(MemoryView src, DatumSizeType& chunkSize) { ByteReader reader{src}; reader.readBE(chunkSize); return reader.viewRemaining(); } }; template<typename DatumSizeType> struct TypedChunkReader<DatumSizeType, EncoderType::LittleEndian> { static MemoryView readChunk(MemoryView src, DatumSizeType& chunkSize) { ByteReader reader{src}; reader.readLE(chunkSize); return reader.viewRemaining(); } }; template<typename T, typename DatumSizeType = uint16, EncoderType EncType = EncoderType::Natural> struct VariableSpan { static_assert(std::is_constructible_v<T, MemoryView>, "Type must be contructable from MemoryView"); using value_type = T; using size_type = uint16; using datum_size = DatumSizeType; using reference = T&; using const_reference = T const&; using pointer_type = T*; using const_pointer = T const*; struct Iterator { Iterator(size_type nElements, MemoryView dataView) : _nElements{nElements} , _data{dataView} {} constexpr Iterator(Iterator const& rhs) noexcept = default; constexpr Iterator(Iterator&& rhs) noexcept = default; Iterator& operator= (Iterator const& rhs) noexcept = default; Iterator& operator= (Iterator&& rhs) noexcept { return swap(rhs); } constexpr bool operator!= (Iterator const& other) const noexcept { return !(operator==(other)); } constexpr bool operator== (Iterator const& other) const noexcept { return (_nElements == other._nElements); } Iterator& operator++ () { if (0 == _nElements) { return *this; // Nowhere to go } datum_size datumSize = 0; auto tail = TypedChunkReader<datum_size, EncType>::readChunk(_data, datumSize); _data = tail.slice(datumSize, tail.size()); // skip datumSize _nElements -= 1; return *this; } value_type operator-> () const { assertTrue(0 < _nElements, "Index out of bounds"); datum_size datumSize = 0; auto tail = TypedChunkReader<datum_size, EncType>::readChunk(_data, datumSize); auto data = tail.slice(0, datumSize); return value_type{data}; } value_type operator* () const { return operator ->(); } private: size_type _nElements; MemoryView _data; }; using const_iterator = Iterator const; constexpr VariableSpan() noexcept = default; VariableSpan(size_type nElements, MemoryView data) noexcept : _nElements{nElements} , _data{mv(data)} {} /** * Check if this collection is empty. * @return True is this is an empty collection. */ constexpr bool empty() const noexcept { return (_nElements == 0); } /** * Get the number of elements in this collection. * @return number of elements in this collection. */ constexpr size_type size() const noexcept { return _nElements; } Iterator begin() noexcept { return Iterator{_nElements, _data}; } Iterator end() noexcept { return Iterator{0, _data}; } const_iterator begin() const noexcept { return Iterator{_nElements, _data}; } const_iterator end() const noexcept { return Iterator{0, _data}; } private: /// Number of elements in the span size_type _nElements; /// Start of the data MemoryView _data; }; } // namespace Solace #endif // SOLACE_VARIABLESPAN_HPP <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file QContractDefinition.cpp * @author Yann yann@ethdev.com * @date 2014 */ #include <QObject> #include <libsolidity/CompilerStack.h> #include <libsolidity/AST.h> #include <libsolidity/Scanner.h> #include <libsolidity/Parser.h> #include <libsolidity/Scanner.h> #include <libsolidity/NameAndTypeResolver.h> #include "AppContext.h" #include "QContractDefinition.h" using namespace dev::solidity; using namespace dev::mix; QContractDefinition::QContractDefinition(dev::solidity::ContractDefinition const* _contract): QBasicNodeDefinition(_contract) { std::vector<FunctionDefinition const*> functions = _contract->getInterfaceFunctions(); for (unsigned i = 0; i < functions.size(); i++) { FunctionDefinition const* func = functions.at(i); m_functions.append(new QFunctionDefinition(func, i)); } } <commit_msg>mix uses new getInterfaceFunctions()<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file QContractDefinition.cpp * @author Yann yann@ethdev.com * @date 2014 */ #include <QObject> #include <libsolidity/CompilerStack.h> #include <libsolidity/AST.h> #include <libsolidity/Scanner.h> #include <libsolidity/Parser.h> #include <libsolidity/Scanner.h> #include <libsolidity/NameAndTypeResolver.h> #include "AppContext.h" #include "QContractDefinition.h" using namespace dev::solidity; using namespace dev::mix; QContractDefinition::QContractDefinition(dev::solidity::ContractDefinition const* _contract): QBasicNodeDefinition(_contract) { auto interfaceFunctions = _contract->getInterfaceFunctions(); unsigned i = 0; for (auto it = interfaceFunctions.cbegin(); it != interfaceFunctions.cend(); ++it, ++i) m_functions.append(new QFunctionDefinition(it->second, i)); } <|endoftext|>
<commit_before>#pragma once #include <cassert> #include <cstring> #include <cwchar> #include <stack> #include <deque> #include <atomic> #include <thread> //! 32bitの4文字チャンクを生成 #define MAKECHUNK(c0,c1,c2,c3) ((c3<<24) | (c2<<16) | (c1<<8) | c0) namespace spn { //! スピンロックによるmutex class Synchro { private: using AThID = std::atomic<std::thread::id>; std::atomic_bool _abLock; //!< 誰かロックしてるか AThID _idTh; //!< ロック中のスレッド番号 int _iLockNum; //!< 再帰的なロック用カウンタ template <bool Block> bool _lock() { auto thid = std::this_thread::get_id(); do { bool b = false; if(_abLock.compare_exchange_weak(b, true, std::memory_order_acquire)) { _iLockNum = 1; _idTh.store(thid, std::memory_order_relaxed); return true; } if(_idTh.compare_exchange_weak(thid, thid, std::memory_order_acquire)) { ++_iLockNum; return true; } } while(Block); return false; } public: Synchro(): _abLock(false) {} void lock() { _lock<true>(); } bool try_lock() { return _lock<false>(); } void unlock() { if(--_iLockNum == 0) _abLock.store(false, std::memory_order_relaxed); } }; //! 何もしないダミーmutex class PseudoSynch { public: void lock() {} bool try_lock() { return true; } void unlock() {} }; //! 4つの8bit値から32bitチャンクを生成 inline static long MakeChunk(uint8_t c0, uint8_t c1, uint8_t c2, uint8_t c3) { return (c3 << 24) | (c2 << 16) | (c1 << 8) | c0; } inline uint64_t U64FromU32(uint32_t hv, uint32_t lv) { uint64_t ret(hv); ret <<= 32; ret |= lv; return ret; } struct Text { // エンコードタイプ enum class CODETYPE { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ANSI }; //! SJISコードか判定する static bool sjis_isMBChar(char c); //! SJISコードにおける文字数判定 static int sjis_strlen(const char* str); //! エンコードタイプと判定に使った文字数を返す static std::pair<CODETYPE, int> GetEncodeType(const void* ptr); //! 文字列の先頭4文字から32bitチャンクを生成 inline static long MakeChunk(const char* str) { return ::spn::MakeChunk(str[0], str[1], str[2], str[3]); } }; //! フリーリストでオブジェクト管理 template <class T> class FreeList { private: T _maxV, _curV; std::stack<T,std::deque<T>> _stk; public: FreeList(T maxV, T startV): _maxV(maxV), _curV(startV) {} FreeList(FreeList&& fl): _maxV(fl._maxV), _curV(fl._curV), _stk(fl._stk) {} T get() { if(_stk.empty()) { int ret = _curV++; assert(_curV != _maxV); return ret; } T val = _stk.top(); _stk.pop(); return val; } void put(T val) { _stk.push(val); } void swap(FreeList& f) noexcept { std::swap(_maxV, f._maxV); std::swap(_curV, f._curV); std::swap(_stk, f._stk); } }; //! ポインタ読み替え変換 template <class T0, class T1> inline T1 RePret(const T0& val) { static_assert(sizeof(T0) == sizeof(T1), "invalid reinterpret value"); return *reinterpret_cast<const T1*>(&val); } //! 値飽和 template <class T> T Saturate(const T& val, const T& minV, const T& maxV) { if(val > maxV) return maxV; if(val < minV) return minV; return val; } template <class T> T Saturate(const T& val, const T& range) { return Saturate(val, -range, range); } //! 値補間 template <class T> T Lerp(const T& v0, const T& v1, float r) { return (v1-v0)*r + v0; } //! 値が範囲内に入っているか template <class T> bool IsInRange(const T& val, const T& vMin, const T& vMax) { return val>=vMin && val<=vMax; } //! 汎用シングルトン template <typename T> class Singleton { private: static T* ms_singleton; public: Singleton() { assert(!ms_singleton || !"initializing error - already initialized"); int offset = (int)(T*)1 - (int)(Singleton<T>*)(T*)1; ms_singleton = (T*)((int)this + offset); } virtual ~Singleton() { assert(ms_singleton || !"destructor error"); ms_singleton = 0; } static T& _ref() { assert(ms_singleton || !"reference error"); return *ms_singleton; } }; template <typename T> T* Singleton<T>::ms_singleton = nullptr; //! 固定長文字列 template <class CT> struct FixStrF; template <> struct FixStrF<char> { static void copy(char* dst, int n, const char* src) { std::strncpy(dst, src, n); } static int cmp(const char* v0, const char* v1) { return std::strcmp(v0, v1); } }; template <> struct FixStrF<wchar_t> { static void copy(wchar_t* dst, int n, const wchar_t* src) { std::wcsncpy(dst, src, n); } static int cmp(const wchar_t* v0, const wchar_t* v1) { return std::wcscmp(v0, v1); } }; template <class CT, int N> struct FixStr { typedef FixStrF<CT> FS; typedef CT value_type; enum {length=N}; CT str[N]; FixStr(const CT* src=(const CT*)L"") { FS::copy(str, N, src); } FixStr(const CT* src_b, const CT* src_e) { int nC = src_e-src_b; assert(nC <= sizeof(CT)*(N-1)); std::memcpy(str, src_b, nC); str[nC] = '\0'; } operator const CT* () const { return str; } bool operator < (const CT* s) const { return FS::cmp(str, s) < 0; } bool operator == (const CT* s) const { return !FS::cmp(str, s); } bool operator != (const CT* s) const { return !(*this == s); } FixStr& operator = (const FixStr& s) { FS::copy(str, N, s); return *this; } CT& operator [] (int n) { return str[n]; } bool operator < (const FixStr& s) const { return FS::cmp(str, s) < 0; } bool operator == (const FixStr& s) const { return !FS::cmp(str, s); } bool operator != (const FixStr& s) const { return !(*this == s); } bool empty() const { return str[0] == '\0'; } void clear() { str[0] = '\0'; } }; } <commit_msg>値比較のIsNear()を追加<commit_after>#pragma once #include <cassert> #include <cstring> #include <cwchar> #include <stack> #include <deque> #include <atomic> #include <thread> //! 32bitの4文字チャンクを生成 #define MAKECHUNK(c0,c1,c2,c3) ((c3<<24) | (c2<<16) | (c1<<8) | c0) namespace spn { //! スピンロックによるmutex class Synchro { private: using AThID = std::atomic<std::thread::id>; std::atomic_bool _abLock; //!< 誰かロックしてるか AThID _idTh; //!< ロック中のスレッド番号 int _iLockNum; //!< 再帰的なロック用カウンタ template <bool Block> bool _lock() { auto thid = std::this_thread::get_id(); do { bool b = false; if(_abLock.compare_exchange_weak(b, true, std::memory_order_acquire)) { _iLockNum = 1; _idTh.store(thid, std::memory_order_relaxed); return true; } if(_idTh.compare_exchange_weak(thid, thid, std::memory_order_acquire)) { ++_iLockNum; return true; } } while(Block); return false; } public: Synchro(): _abLock(false) {} void lock() { _lock<true>(); } bool try_lock() { return _lock<false>(); } void unlock() { if(--_iLockNum == 0) _abLock.store(false, std::memory_order_relaxed); } }; //! 何もしないダミーmutex class PseudoSynch { public: void lock() {} bool try_lock() { return true; } void unlock() {} }; //! 4つの8bit値から32bitチャンクを生成 inline static long MakeChunk(uint8_t c0, uint8_t c1, uint8_t c2, uint8_t c3) { return (c3 << 24) | (c2 << 16) | (c1 << 8) | c0; } inline uint64_t U64FromU32(uint32_t hv, uint32_t lv) { uint64_t ret(hv); ret <<= 32; ret |= lv; return ret; } struct Text { // エンコードタイプ enum class CODETYPE { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ANSI }; //! SJISコードか判定する static bool sjis_isMBChar(char c); //! SJISコードにおける文字数判定 static int sjis_strlen(const char* str); //! エンコードタイプと判定に使った文字数を返す static std::pair<CODETYPE, int> GetEncodeType(const void* ptr); //! 文字列の先頭4文字から32bitチャンクを生成 inline static long MakeChunk(const char* str) { return ::spn::MakeChunk(str[0], str[1], str[2], str[3]); } }; //! フリーリストでオブジェクト管理 template <class T> class FreeList { private: T _maxV, _curV; std::stack<T,std::deque<T>> _stk; public: FreeList(T maxV, T startV): _maxV(maxV), _curV(startV) {} FreeList(FreeList&& fl): _maxV(fl._maxV), _curV(fl._curV), _stk(fl._stk) {} T get() { if(_stk.empty()) { int ret = _curV++; assert(_curV != _maxV); return ret; } T val = _stk.top(); _stk.pop(); return val; } void put(T val) { _stk.push(val); } void swap(FreeList& f) noexcept { std::swap(_maxV, f._maxV); std::swap(_curV, f._curV); std::swap(_stk, f._stk); } }; //! ポインタ読み替え変換 template <class T0, class T1> inline T1 RePret(const T0& val) { static_assert(sizeof(T0) == sizeof(T1), "invalid reinterpret value"); return *reinterpret_cast<const T1*>(&val); } //! 値飽和 template <class T> T Saturate(const T& val, const T& minV, const T& maxV) { if(val > maxV) return maxV; if(val < minV) return minV; return val; } template <class T> T Saturate(const T& val, const T& range) { return Saturate(val, -range, range); } //! 値補間 template <class T> T Lerp(const T& v0, const T& v1, float r) { return (v1-v0)*r + v0; } //! 値が範囲内に入っているか template <class T> bool IsInRange(const T& val, const T& vMin, const T& vMax) { return val>=vMin && val<=vMax; } template <class T> bool IsInRange(const T& val, const T& vMin, const T& vMax, const T& vEps) { return IsInRange(val, vMin-vEps, vMax+vEps); } //! 値が近いか /*! \param[in] val value to check \param[in] vExcept target value \param[in] vEps value threshold */ template <class T> bool IsNear(const T& val, const T& vExcept, const T& vEps) { return IsInRange(val, vExcept-vEps, vExcept+vEps); } //! 汎用シングルトン template <typename T> class Singleton { private: static T* ms_singleton; public: Singleton() { assert(!ms_singleton || !"initializing error - already initialized"); int offset = (int)(T*)1 - (int)(Singleton<T>*)(T*)1; ms_singleton = (T*)((int)this + offset); } virtual ~Singleton() { assert(ms_singleton || !"destructor error"); ms_singleton = 0; } static T& _ref() { assert(ms_singleton || !"reference error"); return *ms_singleton; } }; template <typename T> T* Singleton<T>::ms_singleton = nullptr; //! 固定長文字列 template <class CT> struct FixStrF; template <> struct FixStrF<char> { static void copy(char* dst, int n, const char* src) { std::strncpy(dst, src, n); } static int cmp(const char* v0, const char* v1) { return std::strcmp(v0, v1); } }; template <> struct FixStrF<wchar_t> { static void copy(wchar_t* dst, int n, const wchar_t* src) { std::wcsncpy(dst, src, n); } static int cmp(const wchar_t* v0, const wchar_t* v1) { return std::wcscmp(v0, v1); } }; template <class CT, int N> struct FixStr { typedef FixStrF<CT> FS; typedef CT value_type; enum {length=N}; CT str[N]; FixStr(const CT* src=(const CT*)L"") { FS::copy(str, N, src); } FixStr(const CT* src_b, const CT* src_e) { int nC = src_e-src_b; assert(nC <= sizeof(CT)*(N-1)); std::memcpy(str, src_b, nC); str[nC] = '\0'; } operator const CT* () const { return str; } bool operator < (const CT* s) const { return FS::cmp(str, s) < 0; } bool operator == (const CT* s) const { return !FS::cmp(str, s); } bool operator != (const CT* s) const { return !(*this == s); } FixStr& operator = (const FixStr& s) { FS::copy(str, N, s); return *this; } CT& operator [] (int n) { return str[n]; } bool operator < (const FixStr& s) const { return FS::cmp(str, s) < 0; } bool operator == (const FixStr& s) const { return !FS::cmp(str, s); } bool operator != (const FixStr& s) const { return !(*this == s); } bool empty() const { return str[0] == '\0'; } void clear() { str[0] = '\0'; } }; } <|endoftext|>
<commit_before>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011-2015 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "PipeFile.h" #include "../stringtools.h" #include "../Interface/Server.h" #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <signal.h> #include <sys/wait.h> #include <stdlib.h> PipeFile::PipeFile(const std::string& pCmd) : PipeFileBase(pCmd), hStderr(0), hStdout(0) { int stdout_pipe[2]; if(pipe(stdout_pipe) == -1) { Server->Log("Error creating stdout pipe: " + convert(errno), LL_ERROR); has_error=true; return; } int stderr_pipe[2]; if(pipe(stderr_pipe) == -1) { Server->Log("Error creating stderr pipe: " + convert(errno), LL_ERROR); has_error=true; return; } child_pid = fork(); if(child_pid==-1) { Server->Log("Error forking to execute command: " + convert(errno), LL_ERROR); has_error=true; return; } else if(child_pid==0) { while ((dup2(stdout_pipe[1], STDOUT_FILENO) == -1) && (errno == EINTR)) {} while ((dup2(stderr_pipe[1], STDERR_FILENO) == -1) && (errno == EINTR)) {} close(stdout_pipe[0]); close(stdout_pipe[1]); close(stderr_pipe[0]); close(stderr_pipe[1]); int rc = system((pCmd).c_str()); _exit(rc); } else { close(stdout_pipe[1]); close(stderr_pipe[1]); hStdout = stdout_pipe[0]; hStderr = stderr_pipe[0]; init(); } } PipeFile::~PipeFile() { } void PipeFile::forceExitWait() { if(child_pid!=-1) { kill(child_pid, SIGKILL); int status; waitpid(child_pid, &status, 0); } close(hStdout); close(hStderr); waitForExit(); } bool PipeFile::readIntoBuffer(int hStd, char* buf, size_t buf_avail, size_t& read_bytes) { ssize_t rc = read(hStd, buf, buf_avail); if(rc==0 && errno==EINTR) { return readIntoBuffer(hStd, buf, buf_avail, read_bytes); } else if(rc<=0) { return false; } else { read_bytes = static_cast<size_t>(rc); return true; } } bool PipeFile::readStdoutIntoBuffer(char* buf, size_t buf_avail, size_t& read_bytes) { return readIntoBuffer(hStdout, buf, buf_avail, read_bytes); } bool PipeFile::readStderrIntoBuffer(char* buf, size_t buf_avail, size_t& read_bytes) { return readIntoBuffer(hStderr, buf, buf_avail, read_bytes); } bool PipeFile::getExitCode(int& exit_code) { int status; int rc = waitpid(child_pid, &status, 0); if(rc==-1) { Server->Log("Error while waiting for exit code: " + convert(errno), LL_ERROR); return false; } else { if(WIFEXITED(status)) { exit_code = WEXITSTATUS(status); return true; } else if(WIFSIGNALED(status)) { Server->Log("Script was terminated by signal " + convert(WTERMSIG(status)), LL_ERROR); return false; } else if(WCOREDUMP(status)) { Server->Log("Script crashed", LL_ERROR); return false; } else if(WIFSTOPPED(status)) { Server->Log("Script was stopped by signal " + convert(WSTOPSIG(status)), LL_ERROR); return false; } else { Server->Log("Unknown process status change", LL_ERROR); return false; } } } <commit_msg>Fix killing process if requested by client<commit_after>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011-2015 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "PipeFile.h" #include "../stringtools.h" #include "../Interface/Server.h" #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <signal.h> #include <sys/wait.h> #include <stdlib.h> PipeFile::PipeFile(const std::string& pCmd) : PipeFileBase(pCmd), hStderr(0), hStdout(0) { int stdout_pipe[2]; if(pipe(stdout_pipe) == -1) { Server->Log("Error creating stdout pipe: " + convert(errno), LL_ERROR); has_error=true; return; } int stderr_pipe[2]; if(pipe(stderr_pipe) == -1) { Server->Log("Error creating stderr pipe: " + convert(errno), LL_ERROR); has_error=true; return; } child_pid = fork(); if(child_pid==-1) { Server->Log("Error forking to execute command: " + convert(errno), LL_ERROR); has_error=true; return; } else if(child_pid==0) { while ((dup2(stdout_pipe[1], STDOUT_FILENO) == -1) && (errno == EINTR)) {} while ((dup2(stderr_pipe[1], STDERR_FILENO) == -1) && (errno == EINTR)) {} close(stdout_pipe[0]); close(stdout_pipe[1]); close(stderr_pipe[0]); close(stderr_pipe[1]); int rc = system(pCmd.c_str()); _exit(rc); } else { close(stdout_pipe[1]); close(stderr_pipe[1]); hStdout = stdout_pipe[0]; hStderr = stderr_pipe[0]; init(); } } PipeFile::~PipeFile() { } void PipeFile::forceExitWait() { if(child_pid!=-1) { kill(child_pid, SIGKILL); int status; waitpid(child_pid, &status, 0); } close(hStdout); close(hStderr); waitForExit(); } bool PipeFile::readIntoBuffer(int hStd, char* buf, size_t buf_avail, size_t& read_bytes) { ssize_t rc = read(hStd, buf, buf_avail); if(rc==0 && errno==EINTR) { return readIntoBuffer(hStd, buf, buf_avail, read_bytes); } else if(rc<=0) { return false; } else { read_bytes = static_cast<size_t>(rc); return true; } } bool PipeFile::readStdoutIntoBuffer(char* buf, size_t buf_avail, size_t& read_bytes) { return readIntoBuffer(hStdout, buf, buf_avail, read_bytes); } bool PipeFile::readStderrIntoBuffer(char* buf, size_t buf_avail, size_t& read_bytes) { return readIntoBuffer(hStderr, buf, buf_avail, read_bytes); } bool PipeFile::getExitCode(int& exit_code) { int status; int rc = waitpid(child_pid, &status, WNOHANG); if(rc==-1) { Server->Log("Error while waiting for exit code: " + convert(errno), LL_ERROR); return false; } else if(rc==0) { Server->Log("Process is still active", LL_ERROR); return false; } else { child_pid=-1; if(WIFEXITED(status)) { exit_code = WEXITSTATUS(status); return true; } else if(WIFSIGNALED(status)) { Server->Log("Script was terminated by signal " + convert(WTERMSIG(status)), LL_ERROR); return false; } else if(WCOREDUMP(status)) { Server->Log("Script crashed", LL_ERROR); return false; } else if(WIFSTOPPED(status)) { Server->Log("Script was stopped by signal " + convert(WSTOPSIG(status)), LL_ERROR); return false; } else { Server->Log("Unknown process status change", LL_ERROR); return false; } } } <|endoftext|>
<commit_before>#pragma once #include <cassert> #include <cstring> #include <cwchar> #include <stack> #include <deque> #include <atomic> #include <thread> //! 32bitの4文字チャンクを生成 #define MAKECHUNK(c0,c1,c2,c3) ((c3<<24) | (c2<<16) | (c1<<8) | c0) namespace spn { //! スピンロックによるmutex class Synchro { private: using AThID = std::atomic<std::thread::id>; std::atomic_bool _abLock; //!< 誰かロックしてるか AThID _idTh; //!< ロック中のスレッド番号 int _iLockNum; //!< 再帰的なロック用カウンタ template <bool Block> bool _lock() { auto thid = std::this_thread::get_id(); do { bool b = false; if(_abLock.compare_exchange_weak(b, true, std::memory_order_acquire)) { _iLockNum = 1; _idTh.store(thid, std::memory_order_relaxed); return true; } if(_idTh.compare_exchange_weak(thid, thid, std::memory_order_acquire)) { ++_iLockNum; return true; } } while(Block); return false; } public: Synchro(): _abLock(false) {} void lock() { _lock<true>(); } bool try_lock() { return _lock<false>(); } void unlock() { if(--_iLockNum == 0) _abLock.store(false, std::memory_order_relaxed); } }; //! 何もしないダミーmutex class PseudoSynch { public: void lock() {} bool try_lock() { return true; } void unlock() {} }; //! 4つの8bit値から32bitチャンクを生成 inline static long MakeChunk(uint8_t c0, uint8_t c1, uint8_t c2, uint8_t c3) { return (c3 << 24) | (c2 << 16) | (c1 << 8) | c0; } inline uint64_t U64FromU32(uint32_t hv, uint32_t lv) { uint64_t ret(hv); ret <<= 32; ret |= lv; return ret; } struct Text { // エンコードタイプ enum class CODETYPE { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ANSI }; //! SJISコードか判定する static bool sjis_isMBChar(char c); //! SJISコードにおける文字数判定 static int sjis_strlen(const char* str); //! エンコードタイプと判定に使った文字数を返す static std::pair<CODETYPE, int> GetEncodeType(const void* ptr); //! 文字列の先頭4文字から32bitチャンクを生成 inline static long MakeChunk(const char* str) { return ::spn::MakeChunk(str[0], str[1], str[2], str[3]); } }; //! フリーリストでオブジェクト管理 template <class T> class FreeList { private: T _maxV, _curV; std::stack<T,std::deque<T>> _stk; public: FreeList(T maxV, T startV): _maxV(maxV), _curV(startV) {} FreeList(FreeList&& fl): _maxV(fl._maxV), _curV(fl._curV), _stk(fl._stk) {} T get() { if(_stk.empty()) { int ret = _curV++; assert(_curV != _maxV); return ret; } T val = _stk.top(); _stk.pop(); return val; } void put(T val) { _stk.push(val); } void swap(FreeList& f) noexcept { std::swap(_maxV, f._maxV); std::swap(_curV, f._curV); std::swap(_stk, f._stk); } }; //! ポインタ読み替え変換 template <class T0, class T1> inline T1 RePret(const T0& val) { static_assert(sizeof(T0) == sizeof(T1), "invalid reinterpret value"); return *reinterpret_cast<const T1*>(&val); } //! 値飽和 template <class T> T Saturate(const T& val, const T& minV, const T& maxV) { if(val > maxV) return maxV; if(val < minV) return minV; return val; } template <class T> T Saturate(const T& val, const T& range) { return Saturate(val, -range, range); } //! 値補間 template <class T> T Lerp(const T& v0, const T& v1, float r) { return (v1-v0)*r + v0; } //! 値が範囲内に入っているか template <class T> bool IsInRange(const T& val, const T& vMin, const T& vMax) { return val>=vMin && val<=vMax; } template <class T> bool IsInRange(const T& val, const T& vMin, const T& vMax, const T& vEps) { return IsInRange(val, vMin-vEps, vMax+vEps); } //! aがbより大きかったらaからsizeを引いた値を返す inline int CndSub(int a, int b, int size) { return a - (size & ((b - a) >> 31)); } //! aがbより大きかったらaからbを引いた値を返す inline int CndSub(int a, int b) { return CndSub(a, b, b); } //! aがbより小さかったらaにsizeを足した値を返す inline int CndAdd(int a, int b, int size) { return a + (size & ((a - b) >> 31)); } //! aが0より小さかったらaにsizeを足した値を返す inline int CndAdd(int a, int size) { return CndAdd(a, 0, size); } //! aがlowerより小さかったらsizeを足し、upperより大きかったらsizeを引く inline int CndRange(int a, int lower, int upper, int size) { return a + (size & ((a - lower) >> 31)) - (size & ((upper - a) >> 31)); } //! aが0より小さかったらsizeを足し、sizeより大きかったらsizeを引く inline int CndRange(int a, int size) { return CndRange(a, 0, size, size); } //! ポインタの読み替え template <class T, class T2> T* ReinterpretPtr(T2* ptr) { using TD = typename std::decay<T2>::type; static_assert(std::is_integral<TD>::value || std::is_floating_point<TD>::value, "typename T must number"); return reinterpret_cast<T*>(ptr); } //! リファレンスの読み替え template <class T, class T2> T& ReinterpretRef(T2& val) { return *reinterpret_cast<T*>(&val); } //! 値の読み替え template <class T, class T2> T ReinterpretValue(const T2& val) { return *reinterpret_cast<const T*>(&val); } //! 値が近いか /*! \param[in] val value to check \param[in] vExcept target value \param[in] vEps value threshold */ template <class T> bool IsNear(const T& val, const T& vExcept, const T& vEps) { return IsInRange(val, vExcept-vEps, vExcept+vEps); } //! 汎用シングルトン template <typename T> class Singleton { private: static T* ms_singleton; public: Singleton() { assert(!ms_singleton || !"initializing error - already initialized"); int offset = (int)(T*)1 - (int)(Singleton<T>*)(T*)1; ms_singleton = (T*)((int)this + offset); } virtual ~Singleton() { assert(ms_singleton || !"destructor error"); ms_singleton = 0; } static T& _ref() { assert(ms_singleton || !"reference error"); return *ms_singleton; } }; template <typename T> T* Singleton<T>::ms_singleton = nullptr; //! 固定長文字列 template <class CT> struct FixStrF; template <> struct FixStrF<char> { static void copy(char* dst, int n, const char* src) { std::strncpy(dst, src, n); } static int cmp(const char* v0, const char* v1) { return std::strcmp(v0, v1); } }; template <> struct FixStrF<wchar_t> { static void copy(wchar_t* dst, int n, const wchar_t* src) { std::wcsncpy(dst, src, n); } static int cmp(const wchar_t* v0, const wchar_t* v1) { return std::wcscmp(v0, v1); } }; template <class CT, int N> struct FixStr { typedef FixStrF<CT> FS; typedef CT value_type; enum {length=N}; CT str[N]; FixStr(const CT* src=(const CT*)L"") { FS::copy(str, N, src); } FixStr(const CT* src_b, const CT* src_e) { int nC = src_e-src_b; assert(nC <= sizeof(CT)*(N-1)); std::memcpy(str, src_b, nC); str[nC] = '\0'; } operator const CT* () const { return str; } bool operator < (const CT* s) const { return FS::cmp(str, s) < 0; } bool operator == (const CT* s) const { return !FS::cmp(str, s); } bool operator != (const CT* s) const { return !(*this == s); } FixStr& operator = (const FixStr& s) { FS::copy(str, N, s); return *this; } CT& operator [] (int n) { return str[n]; } bool operator < (const FixStr& s) const { return FS::cmp(str, s) < 0; } bool operator == (const FixStr& s) const { return !FS::cmp(str, s); } bool operator != (const FixStr& s) const { return !(*this == s); } bool empty() const { return str[0] == '\0'; } void clear() { str[0] = '\0'; } }; } <commit_msg>CndAdd / CndSub系関数は「値より大きかったら」を「値以上だったら」に変更<commit_after>#pragma once #include <cassert> #include <cstring> #include <cwchar> #include <stack> #include <deque> #include <atomic> #include <thread> //! 32bitの4文字チャンクを生成 #define MAKECHUNK(c0,c1,c2,c3) ((c3<<24) | (c2<<16) | (c1<<8) | c0) namespace spn { //! スピンロックによるmutex class Synchro { private: using AThID = std::atomic<std::thread::id>; std::atomic_bool _abLock; //!< 誰かロックしてるか AThID _idTh; //!< ロック中のスレッド番号 int _iLockNum; //!< 再帰的なロック用カウンタ template <bool Block> bool _lock() { auto thid = std::this_thread::get_id(); do { bool b = false; if(_abLock.compare_exchange_weak(b, true, std::memory_order_acquire)) { _iLockNum = 1; _idTh.store(thid, std::memory_order_relaxed); return true; } if(_idTh.compare_exchange_weak(thid, thid, std::memory_order_acquire)) { ++_iLockNum; return true; } } while(Block); return false; } public: Synchro(): _abLock(false) {} void lock() { _lock<true>(); } bool try_lock() { return _lock<false>(); } void unlock() { if(--_iLockNum == 0) _abLock.store(false, std::memory_order_relaxed); } }; //! 何もしないダミーmutex class PseudoSynch { public: void lock() {} bool try_lock() { return true; } void unlock() {} }; //! 4つの8bit値から32bitチャンクを生成 inline static long MakeChunk(uint8_t c0, uint8_t c1, uint8_t c2, uint8_t c3) { return (c3 << 24) | (c2 << 16) | (c1 << 8) | c0; } inline uint64_t U64FromU32(uint32_t hv, uint32_t lv) { uint64_t ret(hv); ret <<= 32; ret |= lv; return ret; } struct Text { // エンコードタイプ enum class CODETYPE { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ANSI }; //! SJISコードか判定する static bool sjis_isMBChar(char c); //! SJISコードにおける文字数判定 static int sjis_strlen(const char* str); //! エンコードタイプと判定に使った文字数を返す static std::pair<CODETYPE, int> GetEncodeType(const void* ptr); //! 文字列の先頭4文字から32bitチャンクを生成 inline static long MakeChunk(const char* str) { return ::spn::MakeChunk(str[0], str[1], str[2], str[3]); } }; //! フリーリストでオブジェクト管理 template <class T> class FreeList { private: T _maxV, _curV; std::stack<T,std::deque<T>> _stk; public: FreeList(T maxV, T startV): _maxV(maxV), _curV(startV) {} FreeList(FreeList&& fl): _maxV(fl._maxV), _curV(fl._curV), _stk(fl._stk) {} T get() { if(_stk.empty()) { int ret = _curV++; assert(_curV != _maxV); return ret; } T val = _stk.top(); _stk.pop(); return val; } void put(T val) { _stk.push(val); } void swap(FreeList& f) noexcept { std::swap(_maxV, f._maxV); std::swap(_curV, f._curV); std::swap(_stk, f._stk); } }; //! ポインタ読み替え変換 template <class T0, class T1> inline T1 RePret(const T0& val) { static_assert(sizeof(T0) == sizeof(T1), "invalid reinterpret value"); return *reinterpret_cast<const T1*>(&val); } //! 値飽和 template <class T> T Saturate(const T& val, const T& minV, const T& maxV) { if(val > maxV) return maxV; if(val < minV) return minV; return val; } template <class T> T Saturate(const T& val, const T& range) { return Saturate(val, -range, range); } //! 値補間 template <class T> T Lerp(const T& v0, const T& v1, float r) { return (v1-v0)*r + v0; } //! 値が範囲内に入っているか template <class T> bool IsInRange(const T& val, const T& vMin, const T& vMax) { return val>=vMin && val<=vMax; } template <class T> bool IsInRange(const T& val, const T& vMin, const T& vMax, const T& vEps) { return IsInRange(val, vMin-vEps, vMax+vEps); } //! aがb以上だったらaからsizeを引いた値を返す inline int CndSub(int a, int b, int size) { return a - (size & ((b - a - 1) >> 31)); } //! aがb以上だったらaからbを引いた値を返す inline int CndSub(int a, int b) { return CndSub(a, b, b); } //! aがbより小さかったらaにsizeを足した値を返す inline int CndAdd(int a, int b, int size) { return a + (size & ((a - b) >> 31)); } //! aが0より小さかったらaにsizeを足した値を返す inline int CndAdd(int a, int size) { return CndAdd(a, 0, size); } //! aがlowerより小さかったらsizeを足し、upper以上だったらsizeを引く inline int CndRange(int a, int lower, int upper, int size) { return a + (size & ((a - lower) >> 31)) - (size & ((upper - a - 1) >> 31)); } //! aが0より小さかったらsizeを足し、size以上だったらsizeを引く inline int CndRange(int a, int size) { return CndRange(a, 0, size, size); } //! ポインタの読み替え template <class T, class T2> T* ReinterpretPtr(T2* ptr) { using TD = typename std::decay<T2>::type; static_assert(std::is_integral<TD>::value || std::is_floating_point<TD>::value, "typename T must number"); return reinterpret_cast<T*>(ptr); } //! リファレンスの読み替え template <class T, class T2> T& ReinterpretRef(T2& val) { return *reinterpret_cast<T*>(&val); } //! 値の読み替え template <class T, class T2> T ReinterpretValue(const T2& val) { return *reinterpret_cast<const T*>(&val); } //! 値が近いか /*! \param[in] val value to check \param[in] vExcept target value \param[in] vEps value threshold */ template <class T> bool IsNear(const T& val, const T& vExcept, const T& vEps) { return IsInRange(val, vExcept-vEps, vExcept+vEps); } //! 汎用シングルトン template <typename T> class Singleton { private: static T* ms_singleton; public: Singleton() { assert(!ms_singleton || !"initializing error - already initialized"); int offset = (int)(T*)1 - (int)(Singleton<T>*)(T*)1; ms_singleton = (T*)((int)this + offset); } virtual ~Singleton() { assert(ms_singleton || !"destructor error"); ms_singleton = 0; } static T& _ref() { assert(ms_singleton || !"reference error"); return *ms_singleton; } }; template <typename T> T* Singleton<T>::ms_singleton = nullptr; //! 固定長文字列 template <class CT> struct FixStrF; template <> struct FixStrF<char> { static void copy(char* dst, int n, const char* src) { std::strncpy(dst, src, n); } static int cmp(const char* v0, const char* v1) { return std::strcmp(v0, v1); } }; template <> struct FixStrF<wchar_t> { static void copy(wchar_t* dst, int n, const wchar_t* src) { std::wcsncpy(dst, src, n); } static int cmp(const wchar_t* v0, const wchar_t* v1) { return std::wcscmp(v0, v1); } }; template <class CT, int N> struct FixStr { typedef FixStrF<CT> FS; typedef CT value_type; enum {length=N}; CT str[N]; FixStr(const CT* src=(const CT*)L"") { FS::copy(str, N, src); } FixStr(const CT* src_b, const CT* src_e) { int nC = src_e-src_b; assert(nC <= sizeof(CT)*(N-1)); std::memcpy(str, src_b, nC); str[nC] = '\0'; } operator const CT* () const { return str; } bool operator < (const CT* s) const { return FS::cmp(str, s) < 0; } bool operator == (const CT* s) const { return !FS::cmp(str, s); } bool operator != (const CT* s) const { return !(*this == s); } FixStr& operator = (const FixStr& s) { FS::copy(str, N, s); return *this; } CT& operator [] (int n) { return str[n]; } bool operator < (const FixStr& s) const { return FS::cmp(str, s) < 0; } bool operator == (const FixStr& s) const { return !FS::cmp(str, s); } bool operator != (const FixStr& s) const { return !(*this == s); } bool empty() const { return str[0] == '\0'; } void clear() { str[0] = '\0'; } }; } <|endoftext|>
<commit_before>// Copyright (2015) Gustav #include "finans/core/commandline.h" #include "gtest/gtest.h" #include "gmock/gmock.h" using namespace testing; struct CommandlineTest : public Test { std::ostringstream output; std::ostringstream error; argparse::Parser parser; std::string animal; std::string another; CommandlineTest() : parser("description") { parser("pos", animal)("-op", another); } }; #define GTEST(x) TEST_F(CommandlineTest, x) GTEST(TestEmpty) { const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); } GTEST(TestError) { const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .ParseArgs(argparse::Arguments("app.exe", { "hello", "world" }), output, error); EXPECT_EQ(false, ok); } GTEST(TestOptionalDefault) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-op", op) .ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ(2, op); } GTEST(TestOptionalValue) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-op", op) .ParseArgs(argparse::Arguments("app.exe", {"-op", "42"}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ(42, op); } GTEST(TestPositionalValue) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("op", op) .ParseArgs(argparse::Arguments("app.exe", { "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ(42, op); } GTEST(TestPositionalValueErr) { int op = 42; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("op", op) .ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("error: too few arguments.\n", error.str()); EXPECT_EQ(42, op); // not touched } GTEST(TestStdVector) { std::vector<std::string> strings; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .AddGreedy("-strings", strings, "string") .ParseArgs(argparse::Arguments("app.exe", {"-strings", "cat", "dog", "fish"}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish")); } GTEST(TestStdVectorInts) { std::vector<int> ints; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .AddGreedy("-ints", ints, "string") .ParseArgs(argparse::Arguments("app.exe", { "-ints", "2", "3", "-5", "4" }), output, error); EXPECT_EQ(true, ok); EXPECT_THAT(ints, ElementsAre(2, 3, -5, 4)); } GTEST(TestNonGreedyVector) { std::vector<std::string> strings; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-s", strings) .ParseArgs(argparse::Arguments("app.exe", { "-s", "cat", "-s", "dog", "-s", "fish" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish")); } enum class Day { TODAY, YESTERDAY, TOMORROW }; ARGPARSE_DEFINE_ENUM(Day, "day", ("Today", Day::TODAY)("Tomorrow", Day::TOMORROW)("Yesterday", Day::YESTERDAY) ) GTEST(TestEnum) { Day op = Day::TOMORROW; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("op", op) .ParseArgs(argparse::Arguments("app.exe", { "tod" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ(Day::TODAY, op); } GTEST(TestCommaOp) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-int,-i", op) .ParseArgs(argparse::Arguments("app.exe", { "-int", "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ(42, op); } GTEST(TestSpecifyTwice) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-int,-i", op) .ParseArgs(argparse::Arguments("app.exe", { "-int", "42", "-i", "50" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("error: All positional arguments have been consumed: -i\n", error.str()); EXPECT_EQ(42, op); } GTEST(TestPrecedencePos) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", {"dog"}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("dog", animal); EXPECT_EQ("", another); } GTEST(TestPrecedencePosOp) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-dog", "-op", "cat" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("-dog", animal); EXPECT_EQ("cat", another); } GTEST(TestPrecedenceOpPos) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("dog", animal); EXPECT_EQ("cat", another); } GTEST(TestStoreConstInt) { int op = 12; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .StoreConst("-store", op, 42) .ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ(42, op); } GTEST(TestStoreConstString) { std::string op = ""; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .StoreConst<std::string>("-store", op, "dog") .ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("dog", op); } <commit_msg>added output to the test<commit_after>// Copyright (2015) Gustav #include "finans/core/commandline.h" #include "gtest/gtest.h" #include "gmock/gmock.h" using namespace testing; struct CommandlineTest : public Test { std::ostringstream output; std::ostringstream error; argparse::Parser parser; std::string animal; std::string another; CommandlineTest() : parser("description") { parser("pos", animal)("-op", another); } }; #define GTEST(x) TEST_F(CommandlineTest, x) GTEST(TestEmpty) { const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); } GTEST(TestError) { const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .ParseArgs(argparse::Arguments("app.exe", { "hello", "world" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h]\n", output.str()); EXPECT_EQ("error: All positionals have been consumed: hello", error.str()); } GTEST(TestOptionalDefault) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-op", op) .ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(2, op); } GTEST(TestOptionalValue) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-op", op) .ParseArgs(argparse::Arguments("app.exe", {"-op", "42"}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestPositionalValue) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("op", op) .ParseArgs(argparse::Arguments("app.exe", { "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestPositionalValueErr) { int op = 42; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("op", op) .ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("error: too few arguments.\n", error.str()); EXPECT_EQ("Usage: [-h] [op]\n", output.str()); EXPECT_EQ(42, op); // not touched } GTEST(TestStdVector) { std::vector<std::string> strings; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .AddGreedy("-strings", strings, "string") .ParseArgs(argparse::Arguments("app.exe", {"-strings", "cat", "dog", "fish"}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish")); } GTEST(TestStdVectorInts) { std::vector<int> ints; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .AddGreedy("-ints", ints, "string") .ParseArgs(argparse::Arguments("app.exe", { "-ints", "2", "3", "-5", "4" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(ints, ElementsAre(2, 3, -5, 4)); } GTEST(TestNonGreedyVector) { std::vector<std::string> strings; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-s", strings) .ParseArgs(argparse::Arguments("app.exe", { "-s", "cat", "-s", "dog", "-s", "fish" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish")); } enum class Day { TODAY, YESTERDAY, TOMORROW }; ARGPARSE_DEFINE_ENUM(Day, "day", ("Today", Day::TODAY)("Tomorrow", Day::TOMORROW)("Yesterday", Day::YESTERDAY) ) GTEST(TestEnum) { Day op = Day::TOMORROW; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("op", op) .ParseArgs(argparse::Arguments("app.exe", { "tod" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(Day::TODAY, op); } GTEST(TestCommaOp) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-int,-i", op) .ParseArgs(argparse::Arguments("app.exe", { "-int", "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestSpecifyTwice) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-int,-i", op) .ParseArgs(argparse::Arguments("app.exe", { "-int", "42", "-i", "50" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("error: All positional arguments have been consumed: -i\n", error.str()); EXPECT_EQ("Usage: [h] [-int,-i [INT]]\n", output.str()); EXPECT_EQ(42, op); } GTEST(TestPrecedencePos) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", {"dog"}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ("dog", animal); EXPECT_EQ("", another); } GTEST(TestPrecedencePosOp) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-dog", "-op", "cat" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("-dog", animal); EXPECT_EQ("cat", another); } GTEST(TestPrecedenceOpPos) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ("dog", animal); EXPECT_EQ("cat", another); } GTEST(TestStoreConstInt) { int op = 12; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .StoreConst("-store", op, 42) .ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ(42, op); } GTEST(TestStoreConstString) { std::string op = ""; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .StoreConst<std::string>("-store", op, "dog") .ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("dog", op); } <|endoftext|>
<commit_before>#include <iostream> #include <functional> #include <memory> #include <future> #include "integration_test_helper.h" #include "dronecore.h" using namespace dronecore; using namespace std::placeholders; // for `_1` static std::shared_ptr<MissionItem> add_mission_item(double latitude_deg, double longitude_deg, float relative_altitude_m, float speed_m_s, bool is_fly_through, float gimbal_pitch_deg, float gimbal_yaw_deg, MissionItem::CameraAction camera_action); static void receive_mission_progress(int current, int total, Device *device); static bool _break_done = false; TEST_F(SitlTest, MissionAddWaypointsAndFly) { DroneCore dc; DroneCore::ConnectionResult ret = dc.add_udp_connection(); ASSERT_EQ(ret, DroneCore::ConnectionResult::SUCCESS); // Wait for device to connect via heartbeat. std::this_thread::sleep_for(std::chrono::seconds(2)); Device &device = dc.device(); while (!device.telemetry().health_all_ok()) { LogInfo() << "Waiting for device to be ready"; std::this_thread::sleep_for(std::chrono::seconds(1)); } LogInfo() << "Device ready"; LogInfo() << "Creating and uploading mission"; std::vector<std::shared_ptr<MissionItem>> mission_items; mission_items.push_back( add_mission_item(47.398170327054473, 8.5456490218639658, 10.0f, 5.0f, false, 20.0f, 60.0f, MissionItem::CameraAction::NONE)); mission_items.push_back( add_mission_item(47.398241338125118, 8.5455360114574432, 10.0f, 2.0f, true, 0.0f, -60.0f, MissionItem::CameraAction::TAKE_PHOTO)); mission_items.push_back( add_mission_item(47.398139363821485, 8.5453846156597137, 10.0f, 5.0f, true, -46.0f, 0.0f, MissionItem::CameraAction::START_VIDEO)); mission_items.push_back( add_mission_item(47.398058617228855, 8.5454618036746979, 10.0f, 2.0f, false, -90.0f, 30.0f, MissionItem::CameraAction::STOP_VIDEO)); mission_items.push_back( add_mission_item(47.398100366082858, 8.5456969141960144, 10.0f, 5.0f, false, -45.0f, -30.0f, MissionItem::CameraAction::START_PHOTO_INTERVAL)); mission_items.push_back( add_mission_item(47.398001890458097, 8.5455576181411743, 10.0f, 5.0f, false, 0.0f, 0.0f, MissionItem::CameraAction::STOP_PHOTO_INTERVAL)); { LogInfo() << "Uploading mission..."; // We only have the send_mission function asynchronous for now, so we wrap it using // std::future. auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device.mission().send_mission_async( mission_items, [prom](Mission::Result result) { ASSERT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); LogInfo() << "Mission uploaded."; }); future_result.get(); } LogInfo() << "Arming..."; const Action::Result arm_result = device.action().arm(); EXPECT_EQ(arm_result, Action::Result::SUCCESS); LogInfo() << "Armed."; // Before starting the mission, we want to be sure to subscribe to the mission progress. // We pass on device to receive_mission_progress because we need it in the callback. device.mission().subscribe_progress(std::bind(&receive_mission_progress, _1, _2, &device)); { LogInfo() << "Starting mission."; auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device.mission().start_mission_async( [prom](Mission::Result result) { ASSERT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); LogInfo() << "Started mission."; }); future_result.get(); } while (device.telemetry().armed()) { // Wait until we're done. std::this_thread::sleep_for(std::chrono::seconds(1)); } LogInfo() << "Disarmed, exiting."; } std::shared_ptr<MissionItem> add_mission_item(double latitude_deg, double longitude_deg, float relative_altitude_m, float speed_m_s, bool is_fly_through, float gimbal_pitch_deg, float gimbal_yaw_deg, MissionItem::CameraAction camera_action) { std::shared_ptr<MissionItem> new_item(new MissionItem()); new_item->set_position(latitude_deg, longitude_deg); new_item->set_relative_altitude(relative_altitude_m); new_item->set_speed(speed_m_s); new_item->set_fly_through(is_fly_through); new_item->set_gimbal_pitch_and_yaw(gimbal_pitch_deg, gimbal_yaw_deg); new_item->set_camera_action(camera_action); return new_item; } void receive_mission_progress(int current, int total, Device *device) { LogInfo() << "Mission status update: " << current << " / " << total; if (current == 2 && !_break_done) { // Some time after the mission item 2, we take a quick break. std::this_thread::sleep_for(std::chrono::seconds(2)); { auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device->mission().pause_mission_async( [prom](Mission::Result result) { EXPECT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); }); future_result.get(); } // We don't want to pause muptiple times in case we get the progress notification // several times. _break_done = true; // Pause for 5 seconds. std::this_thread::sleep_for(std::chrono::seconds(5)); // Then continue. { auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device->mission().start_mission_async( [prom](Mission::Result result) { EXPECT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); }); future_result.get(); } } if (current == total) { // We are done, and can do RTL to go home. const Action::Result result = device->action().return_to_launch(); EXPECT_EQ(result, Action::Result::SUCCESS); } } <commit_msg>integration_tests: fixed edge cases, added printfs<commit_after>#include <iostream> #include <functional> #include <memory> #include <future> #include "integration_test_helper.h" #include "dronecore.h" using namespace dronecore; using namespace std::placeholders; // for `_1` static std::shared_ptr<MissionItem> add_mission_item(double latitude_deg, double longitude_deg, float relative_altitude_m, float speed_m_s, bool is_fly_through, float gimbal_pitch_deg, float gimbal_yaw_deg, MissionItem::CameraAction camera_action); static void receive_mission_progress(int current, int total, Device *device); static bool _break_done = false; TEST_F(SitlTest, MissionAddWaypointsAndFly) { DroneCore dc; { auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); LogInfo() << "Waiting to discover device..."; dc.register_on_discover([prom](uint64_t uuid) { LogInfo() << "Discovered device with UUID: " << uuid; prom->set_value(); }); DroneCore::ConnectionResult ret = dc.add_udp_connection(); ASSERT_EQ(ret, DroneCore::ConnectionResult::SUCCESS); future_result.get(); } Device &device = dc.device(); while (!device.telemetry().health_all_ok()) { LogInfo() << "Waiting for device to be ready"; std::this_thread::sleep_for(std::chrono::seconds(1)); } LogInfo() << "Device ready"; LogInfo() << "Creating and uploading mission"; std::vector<std::shared_ptr<MissionItem>> mission_items; mission_items.push_back( add_mission_item(47.398170327054473, 8.5456490218639658, 10.0f, 5.0f, false, 20.0f, 60.0f, MissionItem::CameraAction::NONE)); mission_items.push_back( add_mission_item(47.398241338125118, 8.5455360114574432, 10.0f, 2.0f, true, 0.0f, -60.0f, MissionItem::CameraAction::TAKE_PHOTO)); mission_items.push_back( add_mission_item(47.398139363821485, 8.5453846156597137, 10.0f, 5.0f, true, -46.0f, 0.0f, MissionItem::CameraAction::START_VIDEO)); mission_items.push_back( add_mission_item(47.398058617228855, 8.5454618036746979, 10.0f, 2.0f, false, -90.0f, 30.0f, MissionItem::CameraAction::STOP_VIDEO)); mission_items.push_back( add_mission_item(47.398100366082858, 8.5456969141960144, 10.0f, 5.0f, false, -45.0f, -30.0f, MissionItem::CameraAction::START_PHOTO_INTERVAL)); mission_items.push_back( add_mission_item(47.398001890458097, 8.5455576181411743, 10.0f, 5.0f, false, 0.0f, 0.0f, MissionItem::CameraAction::STOP_PHOTO_INTERVAL)); { LogInfo() << "Uploading mission..."; // We only have the send_mission function asynchronous for now, so we wrap it using // std::future. auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device.mission().send_mission_async( mission_items, [prom](Mission::Result result) { ASSERT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); LogInfo() << "Mission uploaded."; }); future_result.get(); } LogInfo() << "Arming..."; const Action::Result arm_result = device.action().arm(); EXPECT_EQ(arm_result, Action::Result::SUCCESS); LogInfo() << "Armed."; // Before starting the mission, we want to be sure to subscribe to the mission progress. // We pass on device to receive_mission_progress because we need it in the callback. device.mission().subscribe_progress(std::bind(&receive_mission_progress, _1, _2, &device)); { LogInfo() << "Starting mission."; auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device.mission().start_mission_async( [prom](Mission::Result result) { ASSERT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); LogInfo() << "Started mission."; }); future_result.get(); } // We need to wait a bit, otherwise the armed state might not be correct yet. std::this_thread::sleep_for(std::chrono::seconds(2)); while (device.telemetry().armed()) { // Wait until we're done. std::this_thread::sleep_for(std::chrono::seconds(1)); } LogInfo() << "Disarmed, exiting."; } std::shared_ptr<MissionItem> add_mission_item(double latitude_deg, double longitude_deg, float relative_altitude_m, float speed_m_s, bool is_fly_through, float gimbal_pitch_deg, float gimbal_yaw_deg, MissionItem::CameraAction camera_action) { std::shared_ptr<MissionItem> new_item(new MissionItem()); new_item->set_position(latitude_deg, longitude_deg); new_item->set_relative_altitude(relative_altitude_m); new_item->set_speed(speed_m_s); new_item->set_fly_through(is_fly_through); new_item->set_gimbal_pitch_and_yaw(gimbal_pitch_deg, gimbal_yaw_deg); new_item->set_camera_action(camera_action); return new_item; } void receive_mission_progress(int current, int total, Device *device) { LogInfo() << "Mission status update: " << current << " / " << total; if (current == 2 && !_break_done) { // Some time after the mission item 2, we take a quick break. std::this_thread::sleep_for(std::chrono::seconds(2)); { auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); LogInfo() << "Pausing mission..."; device->mission().pause_mission_async( [prom](Mission::Result result) { EXPECT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); }); future_result.get(); LogInfo() << "Mission paused."; } // We don't want to pause muptiple times in case we get the progress notification // several times. _break_done = true; // Pause for 5 seconds. std::this_thread::sleep_for(std::chrono::seconds(5)); // Then continue. { auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); LogInfo() << "Resuming mission..."; device->mission().start_mission_async( [prom](Mission::Result result) { EXPECT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); }); future_result.get(); LogInfo() << "Mission resumed."; } } if (current == total) { // We are done, and can do RTL to go home. LogInfo() << "Commanding RTL..."; const Action::Result result = device->action().return_to_launch(); EXPECT_EQ(result, Action::Result::SUCCESS); LogInfo() << "Commanded RTL."; } } <|endoftext|>
<commit_before>#define DEBUG #include <iostream> #include <cstdlib> #include <cstdio> #include <cmath> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/epoll.h> //for connection to server #include "../sockets/SocketW.h" bool ready4data = false;//set to true when streaming starts bool inited = false; bool stopparsing = false; timeval lastrec; int CONN_fd = 0; FILE * CONN = 0; #include "parsechunks.cpp" //chunkstream parsing #include "handshake.cpp" //handshaking #include "../util/flv_sock.cpp" //FLV parsing with SocketW #include "../util/ddv_socket.cpp" //DDVTech Socket wrapper int main(){ int server_socket = DDV_Listen(1935); int status; while (server_socket > 0){ waitpid((pid_t)-1, &status, WNOHANG); CONN_fd = DDV_Accept(server_socket); CONN = fdopen(CONN_fd, "r+"); pid_t myid = fork(); if (myid == 0){ break; }else{ printf("Spawned new process %i for incoming client\n", (int)myid); } } if (server_socket <= 0){ return 0; } unsigned int ts; unsigned int fts = 0; unsigned int ftst; SWUnixSocket ss; //first timestamp set firsttime = getNowMS(); int now = getNowMS(); int lastcheck = now; #ifdef DEBUG fprintf(stderr, "Doing handshake...\n"); #endif if (doHandshake()){ #ifdef DEBUG fprintf(stderr, "Handshake succcess!\n"); #endif }else{ #ifdef DEBUG fprintf(stderr, "Handshake fail!\n"); #endif return 0; } #ifdef DEBUG fprintf(stderr, "Starting processing...\n"); #endif int retval; int poller = epoll_create(1); struct epoll_event ev; ev.events = EPOLLIN; ev.data.fd = CONN_fd; epoll_ctl(poller, EPOLL_CTL_ADD, CONN_fd, &ev); struct epoll_event events[1]; while (!ferror(CONN) && !feof(CONN)){ //only parse input if available or not yet init'ed //rightnow = getNowMS(); retval = epoll_wait(poller, events, 1, 100); now = getNowMS(); if ((retval > 0) || ((now - lastcheck > 1) && (!ready4data || (snd_cnt - snd_window_at >= snd_window_size)))){ lastcheck = now; parseChunk(); fflush(CONN); } if (ready4data){ if (!inited){ //we are ready, connect the socket! if (!ss.connect(streamname.c_str())){ #ifdef DEBUG fprintf(stderr, "Could not connect to server!\n"); #endif return 0; } FLV_Readheader(ss);//read the header, we don't want it #ifdef DEBUG fprintf(stderr, "Header read, starting to send video data...\n"); #endif inited = true; } //only send data if previous data has been ACK'ed... if (snd_cnt - snd_window_at < snd_window_size){ if (FLV_GetPacket(ss)){//able to read a full packet? ts = FLVbuffer[7] * 256*256*256; ts += FLVbuffer[4] * 256*256; ts += FLVbuffer[5] * 256; ts += FLVbuffer[6]; if (ts != 0){ if (fts == 0){fts = ts;ftst = getNowMS();} ts -= fts; FLVbuffer[7] = ts / (256*256*256); FLVbuffer[4] = ts / (256*256); FLVbuffer[5] = ts / 256; FLVbuffer[6] = ts % 256; ts += ftst; }else{ ftst = getNowMS(); FLVbuffer[7] = ftst / (256*256*256); FLVbuffer[4] = ftst / (256*256); FLVbuffer[5] = ftst / 256; FLVbuffer[6] = ftst % 256; } SendMedia((unsigned char)FLVbuffer[0], (unsigned char *)FLVbuffer+11, FLV_len-15, ts); FLV_Dump();//dump packet and get ready for next } if ((SWBerr != SWBaseSocket::ok) && (SWBerr != SWBaseSocket::notReady)){ #ifdef DEBUG fprintf(stderr, "No more data! :-( (%s)\n", SWBerr.get_error().c_str()); #endif return 0;//no more input possible! Fail immediately. } } } //send ACK if we received a whole window if (rec_cnt - rec_window_at > rec_window_size){ rec_window_at = rec_cnt; SendCTL(3, rec_cnt);//send ack (msg 3) } } #ifdef DEBUG fprintf(stderr, "User disconnected.\n"); #endif return 0; }//main <commit_msg>Nog een poging...<commit_after>#define DEBUG #include <iostream> #include <cstdlib> #include <cstdio> #include <cmath> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/epoll.h> //for connection to server #include "../sockets/SocketW.h" bool ready4data = false;//set to true when streaming starts bool inited = false; bool stopparsing = false; timeval lastrec; int CONN_fd = 0; FILE * CONN = 0; #include "parsechunks.cpp" //chunkstream parsing #include "handshake.cpp" //handshaking #include "../util/flv_sock.cpp" //FLV parsing with SocketW #include "../util/ddv_socket.cpp" //DDVTech Socket wrapper int main(){ int server_socket = DDV_Listen(1935); int status; while (server_socket > 0){ waitpid((pid_t)-1, &status, WNOHANG); CONN_fd = DDV_Accept(server_socket); CONN = fdopen(CONN_fd, "r+"); pid_t myid = fork(); if (myid == 0){ break; }else{ printf("Spawned new process %i for incoming client\n", (int)myid); } } if (server_socket <= 0){ return 0; } unsigned int ts; unsigned int fts = 0; unsigned int ftst; SWUnixSocket ss; //first timestamp set firsttime = getNowMS(); int now = getNowMS(); int lastcheck = now; #ifdef DEBUG fprintf(stderr, "Doing handshake...\n"); #endif if (doHandshake()){ #ifdef DEBUG fprintf(stderr, "Handshake succcess!\n"); #endif }else{ #ifdef DEBUG fprintf(stderr, "Handshake fail!\n"); #endif return 0; } #ifdef DEBUG fprintf(stderr, "Starting processing...\n"); #endif int retval; int poller = epoll_create(1); struct epoll_event ev; ev.events = EPOLLIN; ev.data.fd = CONN_fd; epoll_ctl(poller, EPOLL_CTL_ADD, CONN_fd, &ev); struct epoll_event events[1]; while (!ferror(CONN) && !feof(CONN)){ //only parse input if available or not yet init'ed //rightnow = getNowMS(); retval = epoll_wait(poller, events, 1, 100); now = getNowMS(); if ((retval > 0) || ((now - lastcheck > 1) && (!ready4data || (snd_cnt - snd_window_at >= snd_window_size)))){ lastcheck = now; parseChunk(); fflush(CONN); } if (ready4data){ if (!inited){ //we are ready, connect the socket! if (!ss.connect(streamname.c_str())){ #ifdef DEBUG fprintf(stderr, "Could not connect to server!\n"); #endif return 0; } FLV_Readheader(ss);//read the header, we don't want it #ifdef DEBUG fprintf(stderr, "Header read, starting to send video data...\n"); #endif inited = true; } //only send data if previous data has been ACK'ed... if (snd_cnt - snd_window_at < snd_window_size){ if (FLV_GetPacket(ss)){//able to read a full packet? ts = FLVbuffer[7] * 256*256*256; ts += FLVbuffer[4] * 256*256; ts += FLVbuffer[5] * 256; ts += FLVbuffer[6]; if (ts != 0){ if (fts == 0){fts = ts;ftst = getNowMS();} ts -= fts; FLVbuffer[7] = ts / (256*256*256); FLVbuffer[4] = ts / (256*256); FLVbuffer[5] = ts / 256; FLVbuffer[6] = ts % 256; ts += ftst; }else{ ftst = getNowMS(); FLVbuffer[7] = ftst / (256*256*256); FLVbuffer[4] = ftst / (256*256); FLVbuffer[5] = ftst / 256; FLVbuffer[6] = ftst % 256; } SendMedia((unsigned char)FLVbuffer[0], (unsigned char *)FLVbuffer+11, FLV_len-15, ts); #ifdef DEBUG fprintf(stderr, "Sent a tag.\n"); #endif FLV_Dump();//dump packet and get ready for next } if ((SWBerr != SWBaseSocket::ok) && (SWBerr != SWBaseSocket::notReady)){ #ifdef DEBUG fprintf(stderr, "No more data! :-( (%s)\n", SWBerr.get_error().c_str()); #endif return 0;//no more input possible! Fail immediately. } } } //send ACK if we received a whole window if (rec_cnt - rec_window_at > rec_window_size){ rec_window_at = rec_cnt; SendCTL(3, rec_cnt);//send ack (msg 3) } } #ifdef DEBUG fprintf(stderr, "User disconnected.\n"); #endif return 0; }//main <|endoftext|>
<commit_before>#include "TextureCube.hpp" #include "Error.hpp" #include "InvalidObject.hpp" #include "Buffer.hpp" #include "InlineMethods.hpp" PyObject * MGLTextureCube_tp_new(PyTypeObject * type, PyObject * args, PyObject * kwargs) { MGLTextureCube * self = (MGLTextureCube *)type->tp_alloc(type, 0); #ifdef MGL_VERBOSE printf("MGLTextureCube_tp_new %p\n", self); #endif if (self) { } return (PyObject *)self; } void MGLTextureCube_tp_dealloc(MGLTextureCube * self) { #ifdef MGL_VERBOSE printf("MGLTextureCube_tp_dealloc %p\n", self); #endif MGLTextureCube_Type.tp_free((PyObject *)self); } int MGLTextureCube_tp_init(MGLTextureCube * self, PyObject * args, PyObject * kwargs) { MGLError_Set("cannot create mgl.TextureCube manually"); return -1; } PyObject * MGLTextureCube_use(MGLTextureCube * self, PyObject * args) { int index; int args_ok = PyArg_ParseTuple( args, "I", &index ); if (!args_ok) { return 0; } const GLMethods & gl = self->context->gl; gl.ActiveTexture(GL_TEXTURE0 + index); gl.BindTexture(GL_TEXTURE_CUBE_MAP, self->texture_obj); Py_RETURN_NONE; } PyObject * MGLTextureCube_release(MGLTextureCube * self) { MGLTextureCube_Invalidate(self); Py_RETURN_NONE; } PyMethodDef MGLTextureCube_tp_methods[] = { {"use", (PyCFunction)MGLTextureCube_use, METH_VARARGS, 0}, {"release", (PyCFunction)MGLTextureCube_release, METH_NOARGS, 0}, {0}, }; MGLContext * MGLTextureCube_get_context(MGLTextureCube * self, void * closure) { Py_INCREF(self->context); return self->context; } PyObject * MGLTextureCube_get_glo(MGLTextureCube * self, void * closure) { return PyLong_FromLong(self->texture_obj); } PyGetSetDef MGLTextureCube_tp_getseters[] = { {(char *)"context", (getter)MGLTextureCube_get_context, 0, 0, 0}, {(char *)"glo", (getter)MGLTextureCube_get_glo, 0, 0, 0}, {0}, }; PyTypeObject MGLTextureCube_Type = { PyVarObject_HEAD_INIT(0, 0) "mgl.TextureCube", // tp_name sizeof(MGLTextureCube), // tp_basicsize 0, // tp_itemsize (destructor)MGLTextureCube_tp_dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_reserved 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags 0, // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext MGLTextureCube_tp_methods, // tp_methods 0, // tp_members MGLTextureCube_tp_getseters, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset (initproc)MGLTextureCube_tp_init, // tp_init 0, // tp_alloc MGLTextureCube_tp_new, // tp_new }; MGLTextureCube * MGLTextureCube_New() { MGLTextureCube * self = (MGLTextureCube *)MGLTextureCube_tp_new(&MGLTextureCube_Type, 0, 0); return self; } void MGLTextureCube_Invalidate(MGLTextureCube * texture) { if (Py_TYPE(texture) == &MGLInvalidObject_Type) { #ifdef MGL_VERBOSE printf("MGLTextureCube_Invalidate %p already released\n", texture); #endif return; } #ifdef MGL_VERBOSE printf("MGLTextureCube_Invalidate %p\n", texture); #endif texture->context->gl.DeleteTextures(1, (GLuint *)&texture->texture_obj); Py_DECREF(texture->context); Py_TYPE(texture) = &MGLInvalidObject_Type; Py_DECREF(texture); } <commit_msg>read and read_into in C<commit_after>#include "TextureCube.hpp" #include "Error.hpp" #include "InvalidObject.hpp" #include "Buffer.hpp" #include "InlineMethods.hpp" PyObject * MGLTextureCube_tp_new(PyTypeObject * type, PyObject * args, PyObject * kwargs) { MGLTextureCube * self = (MGLTextureCube *)type->tp_alloc(type, 0); #ifdef MGL_VERBOSE printf("MGLTextureCube_tp_new %p\n", self); #endif if (self) { } return (PyObject *)self; } void MGLTextureCube_tp_dealloc(MGLTextureCube * self) { #ifdef MGL_VERBOSE printf("MGLTextureCube_tp_dealloc %p\n", self); #endif MGLTextureCube_Type.tp_free((PyObject *)self); } int MGLTextureCube_tp_init(MGLTextureCube * self, PyObject * args, PyObject * kwargs) { MGLError_Set("cannot create mgl.TextureCube manually"); return -1; } PyObject * MGLTextureCube_read(MGLTextureCube * self, PyObject * args) { int alignment; int args_ok = PyArg_ParseTuple( args, "I", &alignment ); if (!args_ok) { return 0; } if (alignment != 1 && alignment != 2 && alignment != 4 && alignment != 8) { MGLError_Set("the alignment must be 1, 2, 4 or 8"); return 0; } int expected_size = self->width * self->components * (self->floats ? 4 : 1); expected_size = (expected_size + alignment - 1) / alignment * alignment; expected_size = expected_size * self->height * 6; PyObject * result = PyBytes_FromStringAndSize(0, expected_size); char * data = PyBytes_AS_STRING(result); const int formats[] = {0, GL_RED, GL_RG, GL_RGB, GL_RGBA}; int pixel_type = self->floats ? GL_FLOAT : GL_UNSIGNED_BYTE; int format = formats[self->components]; const GLMethods & gl = self->context->gl; gl.ActiveTexture(GL_TEXTURE0 + self->context->default_texture_unit); gl.BindTexture(GL_TEXTURE_CUBE_MAP, self->texture_obj); gl.PixelStorei(GL_PACK_ALIGNMENT, alignment); gl.PixelStorei(GL_UNPACK_ALIGNMENT, alignment); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, format, pixel_type, data + expected_size * 0 / 6); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, format, pixel_type, data + expected_size * 1 / 6); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, format, pixel_type, data + expected_size * 2 / 6); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, format, pixel_type, data + expected_size * 3 / 6); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, format, pixel_type, data + expected_size * 4 / 6); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, format, pixel_type, data + expected_size * 5 / 6); return result; } PyObject * MGLTextureCube_read_into(MGLTextureCube * self, PyObject * args) { PyObject * data; int alignment; Py_ssize_t write_offset; int args_ok = PyArg_ParseTuple( args, "OIn", &data, &alignment, &write_offset ); if (!args_ok) { return 0; } if (alignment != 1 && alignment != 2 && alignment != 4 && alignment != 8) { MGLError_Set("the alignment must be 1, 2, 4 or 8"); return 0; } int expected_size = self->width * self->components * (self->floats ? 4 : 1); expected_size = (expected_size + alignment - 1) / alignment * alignment; expected_size = expected_size * self->height * 6; const int formats[] = {0, GL_RED, GL_RG, GL_RGB, GL_RGBA}; int pixel_type = self->floats ? GL_FLOAT : GL_UNSIGNED_BYTE; int format = formats[self->components]; if (Py_TYPE(data) == &MGLBuffer_Type) { MGLBuffer * buffer = (MGLBuffer *)data; const GLMethods & gl = self->context->gl; gl.BindBuffer(GL_PIXEL_PACK_BUFFER, buffer->buffer_obj); gl.ActiveTexture(GL_TEXTURE0 + self->context->default_texture_unit); gl.BindTexture(GL_TEXTURE_CUBE_MAP, self->texture_obj); gl.PixelStorei(GL_PACK_ALIGNMENT, alignment); gl.PixelStorei(GL_UNPACK_ALIGNMENT, alignment); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, format, pixel_type, (char *)write_offset + expected_size * 0 / 6); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, format, pixel_type, (char *)write_offset + expected_size * 1 / 6); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, format, pixel_type, (char *)write_offset + expected_size * 2 / 6); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, format, pixel_type, (char *)write_offset + expected_size * 3 / 6); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, format, pixel_type, (char *)write_offset + expected_size * 4 / 6); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, format, pixel_type, (char *)write_offset + expected_size * 5 / 6); gl.BindBuffer(GL_PIXEL_PACK_BUFFER, 0); } else { Py_buffer buffer_view; int get_buffer = PyObject_GetBuffer(data, &buffer_view, PyBUF_WRITABLE); if (get_buffer < 0) { MGLError_Set("the buffer (%s) does not support buffer interface", Py_TYPE(data)->tp_name); return 0; } if (buffer_view.len < write_offset + expected_size) { MGLError_Set("the buffer is too small"); PyBuffer_Release(&buffer_view); return 0; } char * ptr = (char *)buffer_view.buf + write_offset; const GLMethods & gl = self->context->gl; gl.ActiveTexture(GL_TEXTURE0 + self->context->default_texture_unit); gl.BindTexture(GL_TEXTURE_CUBE_MAP, self->texture_obj); gl.PixelStorei(GL_PACK_ALIGNMENT, alignment); gl.PixelStorei(GL_UNPACK_ALIGNMENT, alignment); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, format, pixel_type, ptr + expected_size * 0 / 6); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, format, pixel_type, ptr + expected_size * 1 / 6); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, format, pixel_type, ptr + expected_size * 2 / 6); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, format, pixel_type, ptr + expected_size * 3 / 6); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, format, pixel_type, ptr + expected_size * 4 / 6); gl.GetTexImage(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, format, pixel_type, ptr + expected_size * 5 / 6); PyBuffer_Release(&buffer_view); } Py_RETURN_NONE; } PyObject * MGLTextureCube_use(MGLTextureCube * self, PyObject * args) { int index; int args_ok = PyArg_ParseTuple( args, "I", &index ); if (!args_ok) { return 0; } const GLMethods & gl = self->context->gl; gl.ActiveTexture(GL_TEXTURE0 + index); gl.BindTexture(GL_TEXTURE_CUBE_MAP, self->texture_obj); Py_RETURN_NONE; } PyObject * MGLTextureCube_release(MGLTextureCube * self) { MGLTextureCube_Invalidate(self); Py_RETURN_NONE; } PyMethodDef MGLTextureCube_tp_methods[] = { {"use", (PyCFunction)MGLTextureCube_use, METH_VARARGS, 0}, {"release", (PyCFunction)MGLTextureCube_release, METH_NOARGS, 0}, {0}, }; MGLContext * MGLTextureCube_get_context(MGLTextureCube * self, void * closure) { Py_INCREF(self->context); return self->context; } PyObject * MGLTextureCube_get_glo(MGLTextureCube * self, void * closure) { return PyLong_FromLong(self->texture_obj); } PyGetSetDef MGLTextureCube_tp_getseters[] = { {(char *)"context", (getter)MGLTextureCube_get_context, 0, 0, 0}, {(char *)"glo", (getter)MGLTextureCube_get_glo, 0, 0, 0}, {0}, }; PyTypeObject MGLTextureCube_Type = { PyVarObject_HEAD_INIT(0, 0) "mgl.TextureCube", // tp_name sizeof(MGLTextureCube), // tp_basicsize 0, // tp_itemsize (destructor)MGLTextureCube_tp_dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_reserved 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags 0, // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext MGLTextureCube_tp_methods, // tp_methods 0, // tp_members MGLTextureCube_tp_getseters, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset (initproc)MGLTextureCube_tp_init, // tp_init 0, // tp_alloc MGLTextureCube_tp_new, // tp_new }; MGLTextureCube * MGLTextureCube_New() { MGLTextureCube * self = (MGLTextureCube *)MGLTextureCube_tp_new(&MGLTextureCube_Type, 0, 0); return self; } void MGLTextureCube_Invalidate(MGLTextureCube * texture) { if (Py_TYPE(texture) == &MGLInvalidObject_Type) { #ifdef MGL_VERBOSE printf("MGLTextureCube_Invalidate %p already released\n", texture); #endif return; } #ifdef MGL_VERBOSE printf("MGLTextureCube_Invalidate %p\n", texture); #endif texture->context->gl.DeleteTextures(1, (GLuint *)&texture->texture_obj); Py_DECREF(texture->context); Py_TYPE(texture) = &MGLInvalidObject_Type; Py_DECREF(texture); } <|endoftext|>
<commit_before>/*************************************************** Copyright (c) 2017 Luis Llamas (www.luisllamas.es) 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 "TimeoutTask.h" void TimeoutTask::Run() const { Run(_timeout, _conditionFunc, _okCallback, _timeoutCallback); } void TimeoutTask::Run(unsigned long timeout, ConditionFunc cond, CallbackAction okCallback, CallbackAction timeoutCallback) { unsigned long starttime; bool timeExceed = true; starttime = micros(); while (timeExceed == true && (micros() - starttime) < timeout) { if (cond()) timeExceed = false; } if (timeExceed) timeoutCallback(); else okCallback(); }<commit_msg>Update TimeoutTask.cpp<commit_after>/*************************************************** Copyright (c) 2017 Luis Llamas (www.luisllamas.es) 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 "TimeoutTask.h" void TimeoutTask::Run() const { Run(_timeout, _conditionFunc, _okCallback, _timeoutCallback); } void TimeoutTask::Run(unsigned long timeout, ConditionFunc conditionFunc, CallbackAction okCallback, CallbackAction timeoutCallback) { unsigned long starttime; bool timeExceed = true; starttime = micros(); while (timeExceed == true && (micros() - starttime) < timeout) { if (conditionFunc()) timeExceed = false; } if (timeExceed) timeoutCallback(); else okCallback(); } <|endoftext|>
<commit_before>//Copyright (c) 2017 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/intpoint.h" //To normalize vectors. #include "utils/math.h" //For round_up_divide. #include "utils/MinimumSpanningTree.h" //For the #include "utils/polygonUtils.h" //For moveInside. #include "TreeSupport.h" #define SQRT_2 1.4142135623730950488 //Square root of 2. namespace cura { TreeSupport::TreeSupport() { } void TreeSupport::generateSupportAreas(SliceDataStorage& storage) { std::vector<std::unordered_set<Point>> contact_points; contact_points.reserve(storage.support.supportLayers.size()); for (size_t layer_nr = 0; layer_nr < storage.support.supportLayers.size(); layer_nr++) //Generate empty layers to store the points in. { contact_points.emplace_back(); } for (SliceMeshStorage& mesh : storage.meshes) { if (!mesh.getSettingBoolean("support_tree_enable")) { return; } generateContactPoints(mesh, contact_points); } //Use Minimum Spanning Tree to connect the points on each layer and move them while dropping them down. const coord_t layer_height = storage.getSettingInMicrons("layer_height"); const double angle = storage.getSettingInAngleRadians("support_tree_angle"); const coord_t maximum_move_distance = tan(angle) * layer_height; for (size_t layer_nr = contact_points.size() - 1; layer_nr > 0; layer_nr--) //Skip layer 0, since we can't drop down the vertices there. { MinimumSpanningTree mst(contact_points[layer_nr]); for (Point vertex : contact_points[layer_nr]) { std::vector<Point> neighbours = mst.adjacentNodes(vertex); if (neighbours.size() == 1) //This is a leaf. { Point direction = neighbours[0] - vertex; if (vSize2(direction) < maximum_move_distance * maximum_move_distance) //Smaller than one step. Leave this one out. { continue; } Point motion = normal(direction, maximum_move_distance); contact_points[layer_nr - 1].insert(vertex + motion); } else //Not a leaf or just a single vertex. { contact_points[layer_nr - 1].insert(vertex); //Just drop the leaves directly down. //TODO: Avoid collisions. } } } //TODO: Create a pyramid out of the mesh and move points away from that. //TODO: When reaching the bottom, cut away all edges of the MST that are still not contracted. //TODO: Do a second pass of dropping down but with leftover edges removed. //Placeholder to test with that generates a simple diamond at each contact point (without generating any trees yet). for (size_t layer_nr = 0; layer_nr < contact_points.size(); layer_nr++) { for (Point point : contact_points[layer_nr]) { PolygonsPart outline; Polygon diamond; diamond.add(point + Point(0, 1000)); diamond.add(point + Point(-1000, 0)); diamond.add(point + Point(0, -1000)); diamond.add(point + Point(1000, 0)); outline.add(diamond); storage.support.supportLayers[layer_nr].support_infill_parts.emplace_back(outline, 350); } if (!contact_points[layer_nr].empty()) { storage.support.layer_nr_max_filled_layer = layer_nr; } } //TODO: Apply some diameter to the tree branches. storage.support.generated = true; } void TreeSupport::generateContactPoints(const SliceMeshStorage& mesh, std::vector<std::unordered_set<Point>>& contact_points) { const coord_t layer_height = mesh.getSettingInMicrons("layer_height"); const coord_t z_distance_top = mesh.getSettingInMicrons("support_top_distance"); const size_t z_distance_top_layers = std::max(0U, round_up_divide(z_distance_top, layer_height)) + 1; //Support must always be 1 layer below overhang. for (size_t layer_nr = 0; layer_nr < mesh.overhang_areas.size() - z_distance_top_layers; layer_nr++) { const Polygons& overhang = mesh.overhang_areas[layer_nr + z_distance_top_layers]; if (overhang.empty()) { continue; } //First generate a lot of points in a grid pattern. Polygons outside_polygons = overhang.getOutsidePolygons(); AABB bounding_box(outside_polygons); //To know how far we should generate points. coord_t point_spread = mesh.getSettingInMicrons("support_tree_branch_distance"); point_spread *= SQRT_2; //We'll rotate these points 45 degrees, so this is the point distance when axis-aligned. bounding_box.round(point_spread); for (PolygonRef overhang_part : outside_polygons) { AABB bounding_box(outside_polygons); bounding_box.round(point_spread); bool added = false; //Did we add a point this way? for (coord_t x = bounding_box.min.X; x <= bounding_box.max.X; x += point_spread << 1) { for (coord_t y = bounding_box.min.Y + (point_spread << 1) * (x % 2); y <= bounding_box.max.Y; y += point_spread) //This produces points in a 45-degree rotated grid. { Point candidate(x, y); constexpr bool border_is_inside = true; if (overhang_part.inside(candidate, border_is_inside)) { contact_points[layer_nr].insert(candidate); added = true; } } } if (!added) //If we didn't add any points due to bad luck, we want to add one anyway such that loose parts are also supported. { Point candidate = bounding_box.getMiddle(); PolygonUtils::moveInside(overhang_part, candidate); contact_points[layer_nr].insert(candidate); } } } } }<commit_msg>Avoid collisions with existing objects<commit_after>//Copyright (c) 2017 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/intpoint.h" //To normalize vectors. #include "utils/math.h" //For round_up_divide. #include "utils/MinimumSpanningTree.h" //For the #include "utils/polygonUtils.h" //For moveInside. #include "TreeSupport.h" #define SQRT_2 1.4142135623730950488 //Square root of 2. namespace cura { TreeSupport::TreeSupport() { } void TreeSupport::generateSupportAreas(SliceDataStorage& storage) { std::vector<std::unordered_set<Point>> contact_points; contact_points.reserve(storage.support.supportLayers.size()); for (size_t layer_nr = 0; layer_nr < storage.support.supportLayers.size(); layer_nr++) //Generate empty layers to store the points in. { contact_points.emplace_back(); } for (SliceMeshStorage& mesh : storage.meshes) { if (!mesh.getSettingBoolean("support_tree_enable")) { return; } generateContactPoints(mesh, contact_points); } //Generate areas that have to be avoided. const coord_t layer_height = storage.getSettingInMicrons("layer_height"); const double angle = storage.getSettingInAngleRadians("support_tree_angle"); const coord_t maximum_move_distance = tan(angle) * layer_height; std::vector<Polygons> model_collision; constexpr bool include_helper_parts = false; model_collision.push_back(storage.getLayerOutlines(0, include_helper_parts)); //TODO: If allowing support to rest on model, these need to be just the model outlines. for (size_t layer_nr = 1; layer_nr < storage.print_layer_count; layer_nr ++) { model_collision.push_back(model_collision[layer_nr - 1].offset(-maximum_move_distance)); model_collision[layer_nr] = model_collision[layer_nr].unionPolygons(storage.getLayerOutlines(layer_nr, include_helper_parts)); } //Use Minimum Spanning Tree to connect the points on each layer and move them while dropping them down. for (size_t layer_nr = contact_points.size() - 1; layer_nr > 0; layer_nr--) //Skip layer 0, since we can't drop down the vertices there. { MinimumSpanningTree mst(contact_points[layer_nr]); for (Point vertex : contact_points[layer_nr]) { std::vector<Point> neighbours = mst.adjacentNodes(vertex); if (neighbours.size() == 1) //This is a leaf. { Point direction = neighbours[0] - vertex; if (vSize2(direction) < maximum_move_distance * maximum_move_distance) //Smaller than one step. Leave this one out. { continue; } Point motion = normal(direction, maximum_move_distance); Point next_layer_vertex = vertex + motion; constexpr coord_t xy_distance = 1000; PolygonUtils::moveOutside(model_collision[layer_nr], next_layer_vertex, xy_distance, maximum_move_distance); //Avoid collision. contact_points[layer_nr - 1].insert(next_layer_vertex); } else //Not a leaf or just a single vertex. { constexpr coord_t xy_distance = 1000; PolygonUtils::moveOutside(model_collision[layer_nr], vertex, xy_distance, maximum_move_distance); //Avoid collision. contact_points[layer_nr - 1].insert(vertex); //Just drop the leaves directly down. //TODO: Avoid collisions. } } } //TODO: When reaching the bottom, cut away all edges of the MST that are still not contracted. //TODO: Do a second pass of dropping down but with leftover edges removed. //Placeholder to test with that generates a simple diamond at each contact point (without generating any trees yet). for (size_t layer_nr = 0; layer_nr < contact_points.size(); layer_nr++) { for (Point point : contact_points[layer_nr]) { PolygonsPart outline; Polygon diamond; diamond.add(point + Point(0, 1000)); diamond.add(point + Point(-1000, 0)); diamond.add(point + Point(0, -1000)); diamond.add(point + Point(1000, 0)); outline.add(diamond); storage.support.supportLayers[layer_nr].support_infill_parts.emplace_back(outline, 350); } if (!contact_points[layer_nr].empty()) { storage.support.layer_nr_max_filled_layer = layer_nr; } } //TODO: Apply some diameter to the tree branches. storage.support.generated = true; } void TreeSupport::generateContactPoints(const SliceMeshStorage& mesh, std::vector<std::unordered_set<Point>>& contact_points) { const coord_t layer_height = mesh.getSettingInMicrons("layer_height"); const coord_t z_distance_top = mesh.getSettingInMicrons("support_top_distance"); const size_t z_distance_top_layers = std::max(0U, round_up_divide(z_distance_top, layer_height)) + 1; //Support must always be 1 layer below overhang. for (size_t layer_nr = 0; layer_nr < mesh.overhang_areas.size() - z_distance_top_layers; layer_nr++) { const Polygons& overhang = mesh.overhang_areas[layer_nr + z_distance_top_layers]; if (overhang.empty()) { continue; } //First generate a lot of points in a grid pattern. Polygons outside_polygons = overhang.getOutsidePolygons(); AABB bounding_box(outside_polygons); //To know how far we should generate points. coord_t point_spread = mesh.getSettingInMicrons("support_tree_branch_distance"); point_spread *= SQRT_2; //We'll rotate these points 45 degrees, so this is the point distance when axis-aligned. bounding_box.round(point_spread); for (PolygonRef overhang_part : outside_polygons) { AABB bounding_box(outside_polygons); bounding_box.round(point_spread); bool added = false; //Did we add a point this way? for (coord_t x = bounding_box.min.X; x <= bounding_box.max.X; x += point_spread << 1) { for (coord_t y = bounding_box.min.Y + (point_spread << 1) * (x % 2); y <= bounding_box.max.Y; y += point_spread) //This produces points in a 45-degree rotated grid. { Point candidate(x, y); constexpr bool border_is_inside = true; if (overhang_part.inside(candidate, border_is_inside)) { contact_points[layer_nr].insert(candidate); added = true; } } } if (!added) //If we didn't add any points due to bad luck, we want to add one anyway such that loose parts are also supported. { Point candidate = bounding_box.getMiddle(); PolygonUtils::moveInside(overhang_part, candidate); contact_points[layer_nr].insert(candidate); } } } } }<|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkMapper.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkMapper.h" #include "vtkDataSet.h" #include "vtkLookupTable.h" #include "vtkMath.h" vtkCxxRevisionMacro(vtkMapper, "1.108"); // Initialize static member that controls global immediate mode rendering static int vtkMapperGlobalImmediateModeRendering = 0; // Initialize static member that controls global coincidence resolution static int vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF; static double vtkMapperGlobalResolveCoincidentTopologyZShift = 0.01; static double vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = 1.0; static double vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits = 1.0; // Construct with initial range (0,1). vtkMapper::vtkMapper() { this->Colors = NULL; this->LookupTable = NULL; this->ScalarVisibility = 1; this->ScalarRange[0] = 0.0; this->ScalarRange[1] = 1.0; this->UseLookupTableScalarRange = 0; this->ImmediateModeRendering = 0; this->ColorMode = VTK_COLOR_MODE_DEFAULT; this->ScalarMode = VTK_SCALAR_MODE_DEFAULT; this->ScalarMaterialMode = VTK_MATERIALMODE_DEFAULT; vtkMath::UninitializeBounds(this->Bounds); this->Center[0] = this->Center[1] = this->Center[2] = 0.0; this->RenderTime = 0.0; strcpy(this->ArrayName, ""); this->ArrayId = -1; this->ArrayComponent = 0; this->ArrayAccessMode = VTK_GET_ARRAY_BY_ID; } vtkMapper::~vtkMapper() { if (this->LookupTable) { this->LookupTable->UnRegister(this); } if ( this->Colors != NULL ) { this->Colors->UnRegister(this); } } // Get the bounds for the input of this mapper as // (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax). double *vtkMapper::GetBounds() { static double bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0}; if ( ! this->GetInput() ) { return bounds; } else { this->Update(); this->GetInput()->GetBounds(this->Bounds); return this->Bounds; } } vtkDataSet *vtkMapper::GetInput() { if (this->NumberOfInputs < 1) { return NULL; } return (vtkDataSet *)(this->Inputs[0]); } void vtkMapper::SetGlobalImmediateModeRendering(int val) { if (val == vtkMapperGlobalImmediateModeRendering) { return; } vtkMapperGlobalImmediateModeRendering = val; } int vtkMapper::GetGlobalImmediateModeRendering() { return vtkMapperGlobalImmediateModeRendering; } void vtkMapper::SetResolveCoincidentTopology(int val) { if (val == vtkMapperGlobalResolveCoincidentTopology) { return; } vtkMapperGlobalResolveCoincidentTopology = val; } int vtkMapper::GetResolveCoincidentTopology() { return vtkMapperGlobalResolveCoincidentTopology; } void vtkMapper::SetResolveCoincidentTopologyToDefault() { vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF; } void vtkMapper::SetResolveCoincidentTopologyZShift(double val) { if (val == vtkMapperGlobalResolveCoincidentTopologyZShift) { return; } vtkMapperGlobalResolveCoincidentTopologyZShift = val; } double vtkMapper::GetResolveCoincidentTopologyZShift() { return vtkMapperGlobalResolveCoincidentTopologyZShift; } void vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters( double factor, double units) { if (factor == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor && units == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits ) { return; } vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = factor; vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits = units; } void vtkMapper::GetResolveCoincidentTopologyPolygonOffsetParameters( double& factor, double& units) { factor = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor; units = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits; } // Overload standard modified time function. If lookup table is modified, // then this object is modified as well. unsigned long vtkMapper::GetMTime() { //unsigned long mTime=this->MTime.GetMTime(); unsigned long mTime=vtkAbstractMapper::GetMTime(); unsigned long lutMTime; if ( this->LookupTable != NULL ) { lutMTime = this->LookupTable->GetMTime(); mTime = ( lutMTime > mTime ? lutMTime : mTime ); } return mTime; } void vtkMapper::ShallowCopy(vtkAbstractMapper *mapper) { vtkMapper *m = vtkMapper::SafeDownCast(mapper); if ( m != NULL ) { this->SetLookupTable(m->GetLookupTable()); this->SetScalarVisibility(m->GetScalarVisibility()); this->SetScalarRange(m->GetScalarRange()); this->SetColorMode(m->GetColorMode()); this->SetScalarMode(m->GetScalarMode()); this->SetScalarMaterialMode(m->GetScalarMaterialMode()); this->SetImmediateModeRendering(m->GetImmediateModeRendering()); this->SetUseLookupTableScalarRange(m->GetUseLookupTableScalarRange()); if ( m->GetArrayAccessMode() == VTK_GET_ARRAY_BY_ID ) { this->ColorByArrayComponent(m->GetArrayId(),m->GetArrayComponent()); } else { this->ColorByArrayComponent(m->GetArrayName(),m->GetArrayComponent()); } } // Now do superclass this->vtkAbstractMapper3D::ShallowCopy(mapper); } // a side effect of this is that this->Colors is also set // to the return value vtkUnsignedCharArray *vtkMapper::MapScalars(double alpha) { // Lets try to resuse the old colors. if (this->ScalarVisibility && this->Colors) { vtkDataArray *scalars = vtkAbstractMapper:: GetScalars(this->GetInput(), this->ScalarMode, this->ArrayAccessMode, this->ArrayId, this->ArrayName, this->ArrayComponent); if (this->GetMTime() < this->Colors->GetMTime() && scalars && scalars->GetMTime() < this->Colors->GetMTime()) { return this->Colors; } } // Get rid of old colors if ( this->Colors ) { this->Colors->UnRegister(this); this->Colors = NULL; } // map scalars if necessary if ( this->ScalarVisibility ) { vtkDataArray *scalars = vtkAbstractMapper:: GetScalars(this->GetInput(), this->ScalarMode, this->ArrayAccessMode, this->ArrayId, this->ArrayName, this->ArrayComponent); if ( scalars ) { if ( scalars->GetLookupTable() ) { this->SetLookupTable(scalars->GetLookupTable()); } else { // make sure we have a lookup table if ( this->LookupTable == NULL ) { this->CreateDefaultLookupTable(); } this->LookupTable->Build(); } if ( !this->UseLookupTableScalarRange ) { this->LookupTable->SetRange(this->ScalarRange); } this->LookupTable->SetAlpha(alpha); this->Colors = this->LookupTable-> MapScalars(scalars, this->ColorMode, this->ArrayComponent); // Consistent register and unregisters this->Colors->Register(this); this->Colors->Delete(); } } return this->Colors; } void vtkMapper::SelectColorArray(int arrayNum) { this->ColorByArrayComponent(arrayNum, -1); } void vtkMapper::SelectColorArray(const char* arrayName) { this->ColorByArrayComponent(arrayName, -1); } void vtkMapper::ColorByArrayComponent(int arrayNum, int component) { if (this->ArrayId == arrayNum && component == this->ArrayComponent && this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID) { return; } this->Modified(); this->ArrayId = arrayNum; this->ArrayComponent = component; this->ArrayAccessMode = VTK_GET_ARRAY_BY_ID; } void vtkMapper::ColorByArrayComponent(const char* arrayName, int component) { if (!arrayName || ( strcmp(this->ArrayName, arrayName) == 0 && component == this->ArrayComponent && this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID )) { return; } this->Modified(); strcpy(this->ArrayName, arrayName); this->ArrayComponent = component; this->ArrayAccessMode = VTK_GET_ARRAY_BY_NAME; } // Specify a lookup table for the mapper to use. void vtkMapper::SetLookupTable(vtkScalarsToColors *lut) { if ( this->LookupTable != lut ) { if ( this->LookupTable) { this->LookupTable->UnRegister(this); } this->LookupTable = lut; if (lut) { lut->Register(this); } this->Modified(); } } vtkScalarsToColors *vtkMapper::GetLookupTable() { if ( this->LookupTable == NULL ) { this->CreateDefaultLookupTable(); } return this->LookupTable; } void vtkMapper::CreateDefaultLookupTable() { if ( this->LookupTable) { this->LookupTable->UnRegister(this); } this->LookupTable = vtkLookupTable::New(); // Consistent Register/UnRegisters. this->LookupTable->Register(this); this->LookupTable->Delete(); } // Update the network connected to this mapper. void vtkMapper::Update() { if ( this->GetInput() ) { this->GetInput()->Update(); } } // Return the method of coloring scalar data. const char *vtkMapper::GetColorModeAsString(void) { if ( this->ColorMode == VTK_COLOR_MODE_MAP_SCALARS ) { return "MapScalars"; } else { return "Default"; } } // Return the method for obtaining scalar data. const char *vtkMapper::GetScalarModeAsString(void) { if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA ) { return "UseCellData"; } else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA ) { return "UsePointData"; } else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA ) { return "UsePointFieldData"; } else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA ) { return "UseCellFieldData"; } else { return "Default"; } } const char *vtkMapper::GetScalarMaterialModeAsString(void) { if ( this->ColorMode == VTK_MATERIALMODE_AMBIENT ) { return "Ambient"; } else if ( this->ColorMode == VTK_MATERIALMODE_DIFFUSE ) { return "Diffuse"; } else if ( this->ColorMode == VTK_MATERIALMODE_AMBIENT_AND_DIFFUSE ) { return "Ambient and Diffuse"; } else { return "Default"; } } void vtkMapper::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if ( this->LookupTable ) { os << indent << "Lookup Table:\n"; this->LookupTable->PrintSelf(os,indent.GetNextIndent()); } else { os << indent << "Lookup Table: (none)\n"; } os << indent << "Immediate Mode Rendering: " << (this->ImmediateModeRendering ? "On\n" : "Off\n"); os << indent << "Global Immediate Mode Rendering: " << (vtkMapperGlobalImmediateModeRendering ? "On\n" : "Off\n"); os << indent << "Scalar Visibility: " << (this->ScalarVisibility ? "On\n" : "Off\n"); double *range = this->GetScalarRange(); os << indent << "Scalar Range: (" << range[0] << ", " << range[1] << ")\n"; os << indent << "UseLookupTableScalarRange: " << this->UseLookupTableScalarRange << "\n"; os << indent << "Color Mode: " << this->GetColorModeAsString() << endl; os << indent << "Scalar Mode: " << this->GetScalarModeAsString() << endl; os << indent << "LM Color Mode: " << this->GetScalarMaterialModeAsString() << endl; os << indent << "RenderTime: " << this->RenderTime << endl; os << indent << "Resolve Coincident Topology: "; if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_OFF ) { os << "Off" << endl; } else if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_POLYGON_OFFSET ) { os << "Polygon Offset" << endl; } else { os << "Shift Z-Buffer" << endl; } } <commit_msg>Rebuild colors if alpha changes.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkMapper.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkMapper.h" #include "vtkDataSet.h" #include "vtkLookupTable.h" #include "vtkMath.h" vtkCxxRevisionMacro(vtkMapper, "1.109"); // Initialize static member that controls global immediate mode rendering static int vtkMapperGlobalImmediateModeRendering = 0; // Initialize static member that controls global coincidence resolution static int vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF; static double vtkMapperGlobalResolveCoincidentTopologyZShift = 0.01; static double vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = 1.0; static double vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits = 1.0; // Construct with initial range (0,1). vtkMapper::vtkMapper() { this->Colors = NULL; this->LookupTable = NULL; this->ScalarVisibility = 1; this->ScalarRange[0] = 0.0; this->ScalarRange[1] = 1.0; this->UseLookupTableScalarRange = 0; this->ImmediateModeRendering = 0; this->ColorMode = VTK_COLOR_MODE_DEFAULT; this->ScalarMode = VTK_SCALAR_MODE_DEFAULT; this->ScalarMaterialMode = VTK_MATERIALMODE_DEFAULT; vtkMath::UninitializeBounds(this->Bounds); this->Center[0] = this->Center[1] = this->Center[2] = 0.0; this->RenderTime = 0.0; strcpy(this->ArrayName, ""); this->ArrayId = -1; this->ArrayComponent = 0; this->ArrayAccessMode = VTK_GET_ARRAY_BY_ID; } vtkMapper::~vtkMapper() { if (this->LookupTable) { this->LookupTable->UnRegister(this); } if ( this->Colors != NULL ) { this->Colors->UnRegister(this); } } // Get the bounds for the input of this mapper as // (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax). double *vtkMapper::GetBounds() { static double bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0}; if ( ! this->GetInput() ) { return bounds; } else { this->Update(); this->GetInput()->GetBounds(this->Bounds); return this->Bounds; } } vtkDataSet *vtkMapper::GetInput() { if (this->NumberOfInputs < 1) { return NULL; } return (vtkDataSet *)(this->Inputs[0]); } void vtkMapper::SetGlobalImmediateModeRendering(int val) { if (val == vtkMapperGlobalImmediateModeRendering) { return; } vtkMapperGlobalImmediateModeRendering = val; } int vtkMapper::GetGlobalImmediateModeRendering() { return vtkMapperGlobalImmediateModeRendering; } void vtkMapper::SetResolveCoincidentTopology(int val) { if (val == vtkMapperGlobalResolveCoincidentTopology) { return; } vtkMapperGlobalResolveCoincidentTopology = val; } int vtkMapper::GetResolveCoincidentTopology() { return vtkMapperGlobalResolveCoincidentTopology; } void vtkMapper::SetResolveCoincidentTopologyToDefault() { vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF; } void vtkMapper::SetResolveCoincidentTopologyZShift(double val) { if (val == vtkMapperGlobalResolveCoincidentTopologyZShift) { return; } vtkMapperGlobalResolveCoincidentTopologyZShift = val; } double vtkMapper::GetResolveCoincidentTopologyZShift() { return vtkMapperGlobalResolveCoincidentTopologyZShift; } void vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters( double factor, double units) { if (factor == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor && units == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits ) { return; } vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = factor; vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits = units; } void vtkMapper::GetResolveCoincidentTopologyPolygonOffsetParameters( double& factor, double& units) { factor = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor; units = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits; } // Overload standard modified time function. If lookup table is modified, // then this object is modified as well. unsigned long vtkMapper::GetMTime() { //unsigned long mTime=this->MTime.GetMTime(); unsigned long mTime=vtkAbstractMapper::GetMTime(); unsigned long lutMTime; if ( this->LookupTable != NULL ) { lutMTime = this->LookupTable->GetMTime(); mTime = ( lutMTime > mTime ? lutMTime : mTime ); } return mTime; } void vtkMapper::ShallowCopy(vtkAbstractMapper *mapper) { vtkMapper *m = vtkMapper::SafeDownCast(mapper); if ( m != NULL ) { this->SetLookupTable(m->GetLookupTable()); this->SetScalarVisibility(m->GetScalarVisibility()); this->SetScalarRange(m->GetScalarRange()); this->SetColorMode(m->GetColorMode()); this->SetScalarMode(m->GetScalarMode()); this->SetScalarMaterialMode(m->GetScalarMaterialMode()); this->SetImmediateModeRendering(m->GetImmediateModeRendering()); this->SetUseLookupTableScalarRange(m->GetUseLookupTableScalarRange()); if ( m->GetArrayAccessMode() == VTK_GET_ARRAY_BY_ID ) { this->ColorByArrayComponent(m->GetArrayId(),m->GetArrayComponent()); } else { this->ColorByArrayComponent(m->GetArrayName(),m->GetArrayComponent()); } } // Now do superclass this->vtkAbstractMapper3D::ShallowCopy(mapper); } // a side effect of this is that this->Colors is also set // to the return value vtkUnsignedCharArray *vtkMapper::MapScalars(double alpha) { // Lets try to resuse the old colors. if (this->ScalarVisibility && this->Colors) { if (this->LookupTable && this->LookupTable->GetAlpha() == alpha) { vtkDataArray *scalars = vtkAbstractMapper:: GetScalars(this->GetInput(), this->ScalarMode, this->ArrayAccessMode, this->ArrayId, this->ArrayName, this->ArrayComponent); if (this->GetMTime() < this->Colors->GetMTime() && scalars && scalars->GetMTime() < this->Colors->GetMTime()) { return this->Colors; } } } // Get rid of old colors if ( this->Colors ) { this->Colors->UnRegister(this); this->Colors = NULL; } // map scalars if necessary if ( this->ScalarVisibility ) { vtkDataArray *scalars = vtkAbstractMapper:: GetScalars(this->GetInput(), this->ScalarMode, this->ArrayAccessMode, this->ArrayId, this->ArrayName, this->ArrayComponent); if ( scalars ) { if ( scalars->GetLookupTable() ) { this->SetLookupTable(scalars->GetLookupTable()); } else { // make sure we have a lookup table if ( this->LookupTable == NULL ) { this->CreateDefaultLookupTable(); } this->LookupTable->Build(); } if ( !this->UseLookupTableScalarRange ) { this->LookupTable->SetRange(this->ScalarRange); } this->LookupTable->SetAlpha(alpha); this->Colors = this->LookupTable-> MapScalars(scalars, this->ColorMode, this->ArrayComponent); // Consistent register and unregisters this->Colors->Register(this); this->Colors->Delete(); } } return this->Colors; } void vtkMapper::SelectColorArray(int arrayNum) { this->ColorByArrayComponent(arrayNum, -1); } void vtkMapper::SelectColorArray(const char* arrayName) { this->ColorByArrayComponent(arrayName, -1); } void vtkMapper::ColorByArrayComponent(int arrayNum, int component) { if (this->ArrayId == arrayNum && component == this->ArrayComponent && this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID) { return; } this->Modified(); this->ArrayId = arrayNum; this->ArrayComponent = component; this->ArrayAccessMode = VTK_GET_ARRAY_BY_ID; } void vtkMapper::ColorByArrayComponent(const char* arrayName, int component) { if (!arrayName || ( strcmp(this->ArrayName, arrayName) == 0 && component == this->ArrayComponent && this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID )) { return; } this->Modified(); strcpy(this->ArrayName, arrayName); this->ArrayComponent = component; this->ArrayAccessMode = VTK_GET_ARRAY_BY_NAME; } // Specify a lookup table for the mapper to use. void vtkMapper::SetLookupTable(vtkScalarsToColors *lut) { if ( this->LookupTable != lut ) { if ( this->LookupTable) { this->LookupTable->UnRegister(this); } this->LookupTable = lut; if (lut) { lut->Register(this); } this->Modified(); } } vtkScalarsToColors *vtkMapper::GetLookupTable() { if ( this->LookupTable == NULL ) { this->CreateDefaultLookupTable(); } return this->LookupTable; } void vtkMapper::CreateDefaultLookupTable() { if ( this->LookupTable) { this->LookupTable->UnRegister(this); } this->LookupTable = vtkLookupTable::New(); // Consistent Register/UnRegisters. this->LookupTable->Register(this); this->LookupTable->Delete(); } // Update the network connected to this mapper. void vtkMapper::Update() { if ( this->GetInput() ) { this->GetInput()->Update(); } } // Return the method of coloring scalar data. const char *vtkMapper::GetColorModeAsString(void) { if ( this->ColorMode == VTK_COLOR_MODE_MAP_SCALARS ) { return "MapScalars"; } else { return "Default"; } } // Return the method for obtaining scalar data. const char *vtkMapper::GetScalarModeAsString(void) { if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA ) { return "UseCellData"; } else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA ) { return "UsePointData"; } else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA ) { return "UsePointFieldData"; } else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA ) { return "UseCellFieldData"; } else { return "Default"; } } const char *vtkMapper::GetScalarMaterialModeAsString(void) { if ( this->ColorMode == VTK_MATERIALMODE_AMBIENT ) { return "Ambient"; } else if ( this->ColorMode == VTK_MATERIALMODE_DIFFUSE ) { return "Diffuse"; } else if ( this->ColorMode == VTK_MATERIALMODE_AMBIENT_AND_DIFFUSE ) { return "Ambient and Diffuse"; } else { return "Default"; } } void vtkMapper::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if ( this->LookupTable ) { os << indent << "Lookup Table:\n"; this->LookupTable->PrintSelf(os,indent.GetNextIndent()); } else { os << indent << "Lookup Table: (none)\n"; } os << indent << "Immediate Mode Rendering: " << (this->ImmediateModeRendering ? "On\n" : "Off\n"); os << indent << "Global Immediate Mode Rendering: " << (vtkMapperGlobalImmediateModeRendering ? "On\n" : "Off\n"); os << indent << "Scalar Visibility: " << (this->ScalarVisibility ? "On\n" : "Off\n"); double *range = this->GetScalarRange(); os << indent << "Scalar Range: (" << range[0] << ", " << range[1] << ")\n"; os << indent << "UseLookupTableScalarRange: " << this->UseLookupTableScalarRange << "\n"; os << indent << "Color Mode: " << this->GetColorModeAsString() << endl; os << indent << "Scalar Mode: " << this->GetScalarModeAsString() << endl; os << indent << "LM Color Mode: " << this->GetScalarMaterialModeAsString() << endl; os << indent << "RenderTime: " << this->RenderTime << endl; os << indent << "Resolve Coincident Topology: "; if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_OFF ) { os << "Off" << endl; } else if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_POLYGON_OFFSET ) { os << "Polygon Offset" << endl; } else { os << "Shift Z-Buffer" << endl; } } <|endoftext|>
<commit_before>// Logger.cpp #include "Logger.h" #include <stdarg.h> #include <time.h> #include <iostream> /// Default constructor: called the first time Instance() is called. /// Open the output file. Logger::Logger() { m_stream.open("RiftVolume-log.txt"); Write("RiftVolume log"); } /// Flush and close the output file. Logger::~Logger() { m_stream.close(); } /// Write a message to the log's output stream. ///@param format The string to write to the log. void Logger::Write(const char* format, ...) { const unsigned int bufSz = 1024; char buffer[bufSz]; va_list args; va_start(args, format); vsnprintf(buffer, bufSz, format, args); va_end(args); // Prefix entry by timestamp char timestamp[128]; struct tm* tm; time_t t = time(0); tm = gmtime(&t); strftime(timestamp, sizeof(timestamp), "%Y %b %d %H:%M:%S - ", tm); m_stream << timestamp << buffer << std::endl; std::cout << buffer << std::endl; } <commit_msg>Use PROJECT_NAME macro in Logger.<commit_after>// Logger.cpp #include "Logger.h" #include <stdarg.h> #include <time.h> #include <iostream> #ifndef PROJECT_NAME // This macro should be defined in CMakeLists.txt #define PROJECT_NAME "RiftSkeleton" #endif /// Default constructor: called the first time Instance() is called. /// Open the output file. Logger::Logger() { m_stream.open(PROJECT_NAME "-log.txt"); Write(PROJECT_NAME "log"); } /// Flush and close the output file. Logger::~Logger() { m_stream.close(); } /// Write a message to the log's output stream. ///@param format The string to write to the log. void Logger::Write(const char* format, ...) { const unsigned int bufSz = 1024; char buffer[bufSz]; va_list args; va_start(args, format); vsnprintf(buffer, bufSz, format, args); va_end(args); // Prefix entry by timestamp char timestamp[128]; struct tm* tm; time_t t = time(0); tm = gmtime(&t); strftime(timestamp, sizeof(timestamp), "%Y %b %d %H:%M:%S - ", tm); m_stream << timestamp << buffer << std::endl; std::cout << buffer << std::endl; } <|endoftext|>
<commit_before>#include <iostream> #include <cstdlib> #include <cassert> #include "VtkUgReader.h" #include "vtkCellArray.h" #include "vtkPointData.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" // --------------------------------------------------------------------------- cigma::VtkUgReader::VtkUgReader() { reader = 0; grid = 0; } cigma::VtkUgReader::~VtkUgReader() { reader->Delete(); } // --------------------------------------------------------------------------- void cigma::VtkUgReader::open(std::string filename) { reader = vtkUnstructuredGridReader::New(); reader->SetFileName(filename.c_str()); reader->Update(); //reader->PrintSelf(std::cout, 0); grid = reader->GetOutput(); //grid->PrintSelf(std::cout, 4); } // --------------------------------------------------------------------------- void cigma::VtkUgReader:: get_coordinates(double **coordinates, int *nno, int *nsd) { assert(grid != 0); vtkPoints *points = grid->GetPoints(); //points->PrintSelf(std::cout, 0); int dims[2]; dims[0] = points->GetNumberOfPoints(); dims[1] = 3; int size = dims[0] * dims[1]; int dataType = points->GetDataType(); double *coords = new double[size]; if (dataType == VTK_DOUBLE) { double *ptr = static_cast<double*>(points->GetVoidPointer(0)); for (int i = 0; i < size; i++) { coords[i] = ptr[i]; } } else if (dataType == VTK_FLOAT) { float *ptr = static_cast<float*>(points->GetVoidPointer(0)); for (int i = 0; i < size; i++) { coords[i] = ptr[i]; } } else { assert(false); } *coordinates = coords; *nno = dims[0]; *nsd = dims[1]; } void cigma::VtkUgReader:: get_connectivity(int **connectivity, int *nel, int *ndofs) { assert(grid != 0); vtkCellArray *cellArray = grid->GetCells(); //cellArray->PrintSelf(std::cout, 0); vtkIdType numCells = grid->GetNumberOfCells(); vtkIdType *cellArrayPtr = cellArray->GetPointer(); int dofs_per_elt = cellArrayPtr[0]; int offset = dofs_per_elt + 1; int *connect = new int[numCells * dofs_per_elt]; for (int e = 0; e < numCells; ++e) { for (int i = 1; i <= dofs_per_elt; ++i) { connect[dofs_per_elt * e + (i-1)] = cellArrayPtr[offset*e + i]; } } *connectivity = connect; *nel = numCells; *ndofs = dofs_per_elt; } void cigma::VtkUgReader:: get_vector_point_data(const char *name, double **vectors, int *num, int *dim) { assert(grid != 0); vtkPointData *pointData = grid->GetPointData(); //pointData->PrintSelf(std::cout, 0); vtkDataArray *dataArray; if (name != 0) { assert(pointData->HasArray(name) == 1); dataArray = pointData->GetVectors(name); } else { dataArray = pointData->GetScalars(); } //dataArray->PrintSelf(std::cout, 0); int dataType = dataArray->GetDataType(); assert(dataType == VTK_DOUBLE); double *ptr = static_cast<double*>(dataArray->GetVoidPointer(0)); // XXX: copy the data, or keep the reference? // if dataType from the file is float, then we'd need to copy anyway // perhaps we need a void pointer and a type // new function signature would be // void get_vector_point_data(const char *name, void **vectors, int *num, int *dim, int *type) *vectors = ptr; *num = dataArray->GetNumberOfTuples(); *dim = dataArray->GetNumberOfComponents(); } void cigma::VtkUgReader:: get_scalar_point_data(const char *name, double **scalars, int *num, int *dim) { assert(grid != 0); vtkPointData *pointData = grid->GetPointData(); //pointData->PrintSelf(std::cout, 0); vtkDataArray *dataArray; if (name != 0) { assert(pointData->HasArray(name) == 1); dataArray = pointData->GetScalars(name); } else { dataArray = pointData->GetScalars(); } //dataArray->PrintSelf(std::cout, 0); int dataType = dataArray->GetDataType(); assert(dataType == VTK_DOUBLE); double *ptr = static_cast<double*>(dataArray->GetVoidPointer(0)); // XXX: see comment in get_vector_point_data() *scalars = ptr; *num = dataArray->GetNumberOfTuples(); *dim = dataArray->GetNumberOfComponents(); } // --------------------------------------------------------------------------- <commit_msg>VTK reader object can be null. In destructor, check before deleting.<commit_after>#include <iostream> #include <cstdlib> #include <cassert> #include "VtkUgReader.h" #include "vtkCellArray.h" #include "vtkPointData.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" // --------------------------------------------------------------------------- cigma::VtkUgReader::VtkUgReader() { reader = 0; grid = 0; } cigma::VtkUgReader::~VtkUgReader() { if (reader != 0) reader->Delete(); } // --------------------------------------------------------------------------- void cigma::VtkUgReader::open(std::string filename) { /* XXX: throw exception if file doesn't exist */ reader = vtkUnstructuredGridReader::New(); reader->SetFileName(filename.c_str()); reader->Update(); //reader->PrintSelf(std::cout, 0); grid = reader->GetOutput(); //grid->PrintSelf(std::cout, 4); } // --------------------------------------------------------------------------- void cigma::VtkUgReader:: get_coordinates(double **coordinates, int *nno, int *nsd) { assert(grid != 0); vtkPoints *points = grid->GetPoints(); //points->PrintSelf(std::cout, 0); int dims[2]; dims[0] = points->GetNumberOfPoints(); dims[1] = 3; int size = dims[0] * dims[1]; int dataType = points->GetDataType(); double *coords = new double[size]; if (dataType == VTK_DOUBLE) { double *ptr = static_cast<double*>(points->GetVoidPointer(0)); for (int i = 0; i < size; i++) { coords[i] = ptr[i]; } } else if (dataType == VTK_FLOAT) { float *ptr = static_cast<float*>(points->GetVoidPointer(0)); for (int i = 0; i < size; i++) { coords[i] = ptr[i]; } } else { assert(false); } *coordinates = coords; *nno = dims[0]; *nsd = dims[1]; } void cigma::VtkUgReader:: get_connectivity(int **connectivity, int *nel, int *ndofs) { assert(grid != 0); vtkCellArray *cellArray = grid->GetCells(); //cellArray->PrintSelf(std::cout, 0); vtkIdType numCells = grid->GetNumberOfCells(); vtkIdType *cellArrayPtr = cellArray->GetPointer(); int dofs_per_elt = cellArrayPtr[0]; int offset = dofs_per_elt + 1; int *connect = new int[numCells * dofs_per_elt]; for (int e = 0; e < numCells; ++e) { for (int i = 1; i <= dofs_per_elt; ++i) { connect[dofs_per_elt * e + (i-1)] = cellArrayPtr[offset*e + i]; } } *connectivity = connect; *nel = numCells; *ndofs = dofs_per_elt; } void cigma::VtkUgReader:: get_vector_point_data(const char *name, double **vectors, int *num, int *dim) { assert(grid != 0); vtkPointData *pointData = grid->GetPointData(); //pointData->PrintSelf(std::cout, 0); vtkDataArray *dataArray; if (name != 0) { assert(pointData->HasArray(name) == 1); dataArray = pointData->GetVectors(name); } else { dataArray = pointData->GetScalars(); } //dataArray->PrintSelf(std::cout, 0); int dataType = dataArray->GetDataType(); assert(dataType == VTK_DOUBLE); double *ptr = static_cast<double*>(dataArray->GetVoidPointer(0)); // XXX: copy the data, or keep the reference? // if dataType from the file is float, then we'd need to copy anyway // perhaps we need a void pointer and a type // new function signature would be // void get_vector_point_data(const char *name, void **vectors, int *num, int *dim, int *type) *vectors = ptr; *num = dataArray->GetNumberOfTuples(); *dim = dataArray->GetNumberOfComponents(); } void cigma::VtkUgReader:: get_scalar_point_data(const char *name, double **scalars, int *num, int *dim) { assert(grid != 0); vtkPointData *pointData = grid->GetPointData(); //pointData->PrintSelf(std::cout, 0); vtkDataArray *dataArray; if (name != 0) { assert(pointData->HasArray(name) == 1); dataArray = pointData->GetScalars(name); } else { dataArray = pointData->GetScalars(); } //dataArray->PrintSelf(std::cout, 0); int dataType = dataArray->GetDataType(); assert(dataType == VTK_DOUBLE); double *ptr = static_cast<double*>(dataArray->GetVoidPointer(0)); // XXX: see comment in get_vector_point_data() *scalars = ptr; *num = dataArray->GetNumberOfTuples(); *dim = dataArray->GetNumberOfComponents(); } // --------------------------------------------------------------------------- <|endoftext|>
<commit_before>// ----------------------------------------------------------------------- // pion-common: a collection of common libraries used by the Pion Platform // ----------------------------------------------------------------------- // Copyright (C) 2007-2011 Atomic Labs, Inc. (http://www.atomiclabs.com) // // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt // #include <pion/PionAlgorithms.hpp> #include <boost/assert.hpp> namespace pion { // begin namespace pion bool algo::base64_decode(const std::string &input, std::string &output) { static const char nop = -1; static const char decoding_data[] = { nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop, 62, nop,nop,nop, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,nop,nop, nop,nop,nop,nop, nop, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,nop, nop,nop,nop,nop, nop,26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop }; unsigned int input_length=input.size(); const char * input_ptr = input.data(); // allocate space for output string output.clear(); output.reserve(((input_length+2)/3)*4); // for each 4-bytes sequence from the input, extract 4 6-bits sequences by droping first two bits // and regenerate into 3 8-bits sequence for (unsigned int i=0; i<input_length;i++) { char base64code0; char base64code1; char base64code2 = 0; // initialized to 0 to suppress warnings char base64code3; base64code0 = decoding_data[static_cast<int>(input_ptr[i])]; if(base64code0==nop) // non base64 character return false; if(!(++i<input_length)) // we need at least two input bytes for first byte output return false; base64code1 = decoding_data[static_cast<int>(input_ptr[i])]; if(base64code1==nop) // non base64 character return false; output += ((base64code0 << 2) | ((base64code1 >> 4) & 0x3)); if(++i<input_length) { char c = input_ptr[i]; if(c =='=') { // padding , end of input BOOST_ASSERT( (base64code1 & 0x0f)==0); return true; } base64code2 = decoding_data[static_cast<int>(input_ptr[i])]; if(base64code2==nop) // non base64 character return false; output += ((base64code1 << 4) & 0xf0) | ((base64code2 >> 2) & 0x0f); } if(++i<input_length) { char c = input_ptr[i]; if(c =='=') { // padding , end of input BOOST_ASSERT( (base64code2 & 0x03)==0); return true; } base64code3 = decoding_data[static_cast<int>(input_ptr[i])]; if(base64code3==nop) // non base64 character return false; output += (((base64code2 << 6) & 0xc0) | base64code3 ); } } return true; } bool algo::base64_encode(const std::string &input, std::string &output) { static const char encoding_data[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; unsigned int input_length=input.size(); const char * input_ptr = input.data(); // allocate space for output string output.clear(); output.reserve(((input_length+2)/3)*4); // for each 3-bytes sequence from the input, extract 4 6-bits sequences and encode using // encoding_data lookup table. // if input do not contains enough chars to complete 3-byte sequence,use pad char '=' for (unsigned int i=0; i<input_length;i++) { int base64code0=0; int base64code1=0; int base64code2=0; int base64code3=0; base64code0 = (input_ptr[i] >> 2) & 0x3f; // 1-byte 6 bits output += encoding_data[base64code0]; base64code1 = (input_ptr[i] << 4 ) & 0x3f; // 1-byte 2 bits + if (++i < input_length) { base64code1 |= (input_ptr[i] >> 4) & 0x0f; // 2-byte 4 bits output += encoding_data[base64code1]; base64code2 = (input_ptr[i] << 2) & 0x3f; // 2-byte 4 bits + if (++i < input_length) { base64code2 |= (input_ptr[i] >> 6) & 0x03; // 3-byte 2 bits base64code3 = input_ptr[i] & 0x3f; // 3-byte 6 bits output += encoding_data[base64code2]; output += encoding_data[base64code3]; } else { output += encoding_data[base64code2]; output += '='; } } else { output += encoding_data[base64code1]; output += '='; output += '='; } } return true; } std::string algo::url_decode(const std::string& str) { char decode_buf[3]; std::string result; result.reserve(str.size()); for (std::string::size_type pos = 0; pos < str.size(); ++pos) { switch(str[pos]) { case '+': // convert to space character result += ' '; break; case '%': // decode hexidecimal value if (pos + 2 < str.size()) { decode_buf[0] = str[++pos]; decode_buf[1] = str[++pos]; decode_buf[2] = '\0'; result += static_cast<char>( strtol(decode_buf, 0, 16) ); } else { // recover from error by not decoding character result += '%'; } break; default: // character does not need to be escaped result += str[pos]; } }; return result; } std::string algo::url_encode(const std::string& str) { char encode_buf[4]; std::string result; encode_buf[0] = '%'; result.reserve(str.size()); // character selection for this algorithm is based on the following url: // http://www.blooberry.com/indexdot/html/topics/urlencoding.htm for (std::string::size_type pos = 0; pos < str.size(); ++pos) { switch(str[pos]) { default: if (str[pos] > 32 && str[pos] < 127) { // character does not need to be escaped result += str[pos]; break; } // else pass through to next case case ' ': case '$': case '&': case '+': case ',': case '/': case ':': case ';': case '=': case '?': case '@': case '"': case '<': case '>': case '#': case '%': case '{': case '}': case '|': case '\\': case '^': case '~': case '[': case ']': case '`': // the character needs to be encoded sprintf(encode_buf+1, "%.2X", (unsigned char)(str[pos])); result += encode_buf; break; } }; return result; } } // end namespace pion <commit_msg>Added missing c-library headers required on Ubuntu<commit_after>// ----------------------------------------------------------------------- // pion-common: a collection of common libraries used by the Pion Platform // ----------------------------------------------------------------------- // Copyright (C) 2007-2011 Atomic Labs, Inc. (http://www.atomiclabs.com) // // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt // #include <cstdlib> #include <cstdio> #include <pion/PionAlgorithms.hpp> #include <boost/assert.hpp> namespace pion { // begin namespace pion bool algo::base64_decode(const std::string &input, std::string &output) { static const char nop = -1; static const char decoding_data[] = { nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop, 62, nop,nop,nop, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,nop,nop, nop,nop,nop,nop, nop, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,nop, nop,nop,nop,nop, nop,26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop, nop,nop,nop,nop }; unsigned int input_length=input.size(); const char * input_ptr = input.data(); // allocate space for output string output.clear(); output.reserve(((input_length+2)/3)*4); // for each 4-bytes sequence from the input, extract 4 6-bits sequences by droping first two bits // and regenerate into 3 8-bits sequence for (unsigned int i=0; i<input_length;i++) { char base64code0; char base64code1; char base64code2 = 0; // initialized to 0 to suppress warnings char base64code3; base64code0 = decoding_data[static_cast<int>(input_ptr[i])]; if(base64code0==nop) // non base64 character return false; if(!(++i<input_length)) // we need at least two input bytes for first byte output return false; base64code1 = decoding_data[static_cast<int>(input_ptr[i])]; if(base64code1==nop) // non base64 character return false; output += ((base64code0 << 2) | ((base64code1 >> 4) & 0x3)); if(++i<input_length) { char c = input_ptr[i]; if(c =='=') { // padding , end of input BOOST_ASSERT( (base64code1 & 0x0f)==0); return true; } base64code2 = decoding_data[static_cast<int>(input_ptr[i])]; if(base64code2==nop) // non base64 character return false; output += ((base64code1 << 4) & 0xf0) | ((base64code2 >> 2) & 0x0f); } if(++i<input_length) { char c = input_ptr[i]; if(c =='=') { // padding , end of input BOOST_ASSERT( (base64code2 & 0x03)==0); return true; } base64code3 = decoding_data[static_cast<int>(input_ptr[i])]; if(base64code3==nop) // non base64 character return false; output += (((base64code2 << 6) & 0xc0) | base64code3 ); } } return true; } bool algo::base64_encode(const std::string &input, std::string &output) { static const char encoding_data[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; unsigned int input_length=input.size(); const char * input_ptr = input.data(); // allocate space for output string output.clear(); output.reserve(((input_length+2)/3)*4); // for each 3-bytes sequence from the input, extract 4 6-bits sequences and encode using // encoding_data lookup table. // if input do not contains enough chars to complete 3-byte sequence,use pad char '=' for (unsigned int i=0; i<input_length;i++) { int base64code0=0; int base64code1=0; int base64code2=0; int base64code3=0; base64code0 = (input_ptr[i] >> 2) & 0x3f; // 1-byte 6 bits output += encoding_data[base64code0]; base64code1 = (input_ptr[i] << 4 ) & 0x3f; // 1-byte 2 bits + if (++i < input_length) { base64code1 |= (input_ptr[i] >> 4) & 0x0f; // 2-byte 4 bits output += encoding_data[base64code1]; base64code2 = (input_ptr[i] << 2) & 0x3f; // 2-byte 4 bits + if (++i < input_length) { base64code2 |= (input_ptr[i] >> 6) & 0x03; // 3-byte 2 bits base64code3 = input_ptr[i] & 0x3f; // 3-byte 6 bits output += encoding_data[base64code2]; output += encoding_data[base64code3]; } else { output += encoding_data[base64code2]; output += '='; } } else { output += encoding_data[base64code1]; output += '='; output += '='; } } return true; } std::string algo::url_decode(const std::string& str) { char decode_buf[3]; std::string result; result.reserve(str.size()); for (std::string::size_type pos = 0; pos < str.size(); ++pos) { switch(str[pos]) { case '+': // convert to space character result += ' '; break; case '%': // decode hexidecimal value if (pos + 2 < str.size()) { decode_buf[0] = str[++pos]; decode_buf[1] = str[++pos]; decode_buf[2] = '\0'; result += static_cast<char>( strtol(decode_buf, 0, 16) ); } else { // recover from error by not decoding character result += '%'; } break; default: // character does not need to be escaped result += str[pos]; } }; return result; } std::string algo::url_encode(const std::string& str) { char encode_buf[4]; std::string result; encode_buf[0] = '%'; result.reserve(str.size()); // character selection for this algorithm is based on the following url: // http://www.blooberry.com/indexdot/html/topics/urlencoding.htm for (std::string::size_type pos = 0; pos < str.size(); ++pos) { switch(str[pos]) { default: if (str[pos] > 32 && str[pos] < 127) { // character does not need to be escaped result += str[pos]; break; } // else pass through to next case case ' ': case '$': case '&': case '+': case ',': case '/': case ':': case ';': case '=': case '?': case '@': case '"': case '<': case '>': case '#': case '%': case '{': case '}': case '|': case '\\': case '^': case '~': case '[': case ']': case '`': // the character needs to be encoded sprintf(encode_buf+1, "%.2X", (unsigned char)(str[pos])); result += encode_buf; break; } }; return result; } } // end namespace pion <|endoftext|>
<commit_before>#include "RenderController.h" using namespace std; RenderController::RenderController(QWidget *parent, const DatabaseRef& dbr) : QWidget(parent) { mSettings.LoadSettingsFromFile(); mShapes = dynamic_pointer_cast<ShapesModule>(dbr.GetModule(DatabaseRef::SHAPES_KEY)); mSolver = dynamic_pointer_cast<SolverModule>(dbr.GetModule(DatabaseRef::SOLVER_KEY)); const int x = mSettings.GetValue(SettingsManager::KEY_SIZE_X); const int y = mSettings.GetValue(SettingsManager::KEY_SIZE_Y); const int pixelSize = mSettings.GetValue(SettingsManager::KEY_PIXEL_SIZE); mPix = make_unique<QPixmap>(x * pixelSize, y * pixelSize); mScene = make_unique<QGraphicsScene>(this); mPixItem = make_unique<QGraphicsPixmapItem>(mScene->addPixmap(*mPix)); mView = make_unique<QGraphicsView>(mScene.get(), this); mCThread = make_unique<CalcThread>(((SolverModule*)dbr.GetModule(DatabaseRef::SOLVER_KEY).get())->GetField(), mSettings, this); mPThread = make_unique<PaintThread>(dbr, mPix.get(), mSettings, this); connect(mPThread.get(), &PaintThread::paintDone, this, &RenderController::afterPainting); const int windowWidth = mSettings.GetValue(SettingsManager::KEY_WINDOW_WIDTH); const int windowHeight = mSettings.GetValue(SettingsManager::KEY_WINDOW_HEIGHT); setFixedSize(windowWidth, windowHeight); mView->resize(windowWidth + 2, windowHeight + 2); mPThread->start(QThread::HighPriority); mSettings.SaveSettingsToFile(); } void RenderController::startCalculation() { qApp->setStyleSheet("QToolBar { background-color: #5fc3fc }"); mCThread->SetDoCalculation(true); mCThread->SetRunning(true); mCThread->start(QThread::HighPriority); } void RenderController::doOneTimestep() { mCThread->PerformOneTimestep(); } void RenderController::pauseCalculation() { mCThread->SetDoCalculation(false); } void RenderController::stopCalculation() { qApp->setStyleSheet(""); mCThread->SetDoCalculation(false); mCThread->SetRunning(false); mCThread->exit(); } void RenderController::AddRect(const int x, const int y, const int width, const int height, const double vel) { if (validateRect(x, y, width, height)) { mShapes->AddRect(x, y, width, height, vel); mSolver->AddRectangle(x, y, width, height, vel); emit rectAdded(x, y, width, height); } else { QMessageBox::warning(this, "Out of Bounds", "The rectangle you are trying to add exceeds the allowed boundaries"); } } void RenderController::AddCircle(const int x, const int y, const int radius, const double vel) { if (validateCircle(x, y, radius)) { mShapes->AddCircle(x, y, radius, vel); mSolver->AddCircle(x, y, radius, vel); emit circleAdded(x, y, radius); } else { QMessageBox::warning(this, "Out of Bounds", "The circle you are trying to add exceeds the allowed boundaries"); } } void RenderController::ClearShapes() { mShapes->ClearAllShapes(); mSolver->ResetMaterials(); emit shapesCleared(); } void RenderController::ResetField() { mSolver->ResetField(); } bool RenderController::validateRect(const int x, const int y, const int w, const int h) { if (x < 1) return false; if (y < 1) return false; if (x + w > mSettings.GetValue(SettingsManager::KEY_SIZE_X)) return false; if (y + h > mSettings.GetValue(SettingsManager::KEY_SIZE_Y)) return false; return true; } bool RenderController::validateCircle(const int x, const int y, const int r) { if (x - r < 1) return false; if (y - r < 1) return false; if (x + r > mSettings.GetValue(SettingsManager::KEY_SIZE_X)) return false; if (y + r > mSettings.GetValue(SettingsManager::KEY_SIZE_Y)) return false; return true; } void RenderController::afterPainting() { mPixItem->setPixmap(*mPix); mView->show(); } <commit_msg>Add comments<commit_after>#include "RenderController.h" using namespace std; /** * Constructor for the RenderController class. * * @param parent The parent object of the RenderController. * @param dbr Reference to the database. */ RenderController::RenderController(QWidget *parent, const DatabaseRef& dbr) : QWidget(parent) { mSettings.LoadSettingsFromFile(); mShapes = dynamic_pointer_cast<ShapesModule>(dbr.GetModule(DatabaseRef::SHAPES_KEY)); mSolver = dynamic_pointer_cast<SolverModule>(dbr.GetModule(DatabaseRef::SOLVER_KEY)); const int x = mSettings.GetValue(SettingsManager::KEY_SIZE_X); const int y = mSettings.GetValue(SettingsManager::KEY_SIZE_Y); const int pixelSize = mSettings.GetValue(SettingsManager::KEY_PIXEL_SIZE); mPix = make_unique<QPixmap>(x * pixelSize, y * pixelSize); mScene = make_unique<QGraphicsScene>(this); mPixItem = make_unique<QGraphicsPixmapItem>(mScene->addPixmap(*mPix)); mView = make_unique<QGraphicsView>(mScene.get(), this); mCThread = make_unique<CalcThread>(((SolverModule*)dbr.GetModule(DatabaseRef::SOLVER_KEY).get())->GetField(), mSettings, this); mPThread = make_unique<PaintThread>(dbr, mPix.get(), mSettings, this); connect(mPThread.get(), &PaintThread::paintDone, this, &RenderController::afterPainting); const int windowWidth = mSettings.GetValue(SettingsManager::KEY_WINDOW_WIDTH); const int windowHeight = mSettings.GetValue(SettingsManager::KEY_WINDOW_HEIGHT); setFixedSize(windowWidth, windowHeight); mView->resize(windowWidth + 2, windowHeight + 2); mPThread->start(QThread::HighPriority); mSettings.SaveSettingsToFile(); } /** * Starts the calculation thread. Also makes the tool bar blue while * the calculation is going. */ void RenderController::startCalculation() { qApp->setStyleSheet("QToolBar { background-color: #5fc3fc }"); mCThread->SetDoCalculation(true); mCThread->SetRunning(true); mCThread->start(QThread::HighPriority); } /** * Make the solver perform 1 timestep. */ void RenderController::doOneTimestep() { mCThread->PerformOneTimestep(); } /** * Pauses the calculation. */ void RenderController::pauseCalculation() { mCThread->SetDoCalculation(false); } /** * Stops the calculation thread, and changes the style of the tool bar. */ void RenderController::stopCalculation() { qApp->setStyleSheet(""); mCThread->SetDoCalculation(false); mCThread->SetRunning(false); mCThread->exit(); } /** * Adds a rectangle to the renderer. * * @param x The top left X-coordinate of the rectangle. * @param y The top left Y-coordinate of the rectangle. * @param w The width of the rectangle. * @param h The height of the rectangle. * @param vel The velocity of the rectangle. A higher velocity will make the * wave travel more slowly through the rectangle. A lower velocity * will do the opposite. */ void RenderController::AddRect(const int x, const int y, const int width, const int height, const double vel) { if (validateRect(x, y, width, height)) { mShapes->AddRect(x, y, width, height, vel); mSolver->AddRectangle(x, y, width, height, vel); emit rectAdded(x, y, width, height); } else { QMessageBox::warning(this, "Out of Bounds", "The rectangle you are trying to add exceeds the allowed boundaries"); } } /** * Adds a circle the renderer. * * @param x The X-coordinate of the center of the circle. * @param y The Y-coordinate of the center of the circle. * @param radius The radius of the circle. * @param vel The velocity of the circle. Affects the behaviour of the wave when it * passes through the circle. */ void RenderController::AddCircle(const int x, const int y, const int radius, const double vel) { if (validateCircle(x, y, radius)) { mShapes->AddCircle(x, y, radius, vel); mSolver->AddCircle(x, y, radius, vel); emit circleAdded(x, y, radius); } else { QMessageBox::warning(this, "Out of Bounds", "The circle you are trying to add exceeds the allowed boundaries"); } } /** * Clears all of the shapes from the renderer. */ void RenderController::ClearShapes() { mShapes->ClearAllShapes(); mSolver->ResetMaterials(); emit shapesCleared(); } /** * Resets the field. This causes the simulator to restart. */ void RenderController::ResetField() { mSolver->ResetField(); } /** * Validates a rectangle before adding it to the renderer. * * @param x The top left X-coordinate of the rectangle. * @param y The top left Y-coordinate of the rectangle. * @param w The width of the rectangle. * @param h The height of the rectangle. * * @return True if the rectangle is valid, false otherwise. */ bool RenderController::validateRect(const int x, const int y, const int w, const int h) { if (x < 1) return false; if (y < 1) return false; if (x + w > mSettings.GetValue(SettingsManager::KEY_SIZE_X)) return false; if (y + h > mSettings.GetValue(SettingsManager::KEY_SIZE_Y)) return false; return true; } /** * Validates a circle before adding it to the renderer. * * @param x The X-coordinate of the center of the circle. * @param y The Y-coordinate of the center of the circle. * @param r The radius of the circle. * * @return True if the circle is valid, false otherwise. */ bool RenderController::validateCircle(const int x, const int y, const int r) { if (x - r < 1) return false; if (y - r < 1) return false; if (x + r > mSettings.GetValue(SettingsManager::KEY_SIZE_X)) return false; if (y + r > mSettings.GetValue(SettingsManager::KEY_SIZE_Y)) return false; return true; } /** * */ void RenderController::afterPainting() { mPixItem->setPixmap(*mPix); mView->show(); } <|endoftext|>
<commit_before>#include "basic_tiling_render_policy.hpp" #include "../platform/platform.hpp" #include "../indexer/scales.hpp" #include "tile_renderer.hpp" #include "coverage_generator.hpp" #include "queued_renderer.hpp" size_t BasicTilingRenderPolicy::CalculateTileSize(size_t screenWidth, size_t screenHeight) { int const maxSz = max(screenWidth, screenHeight); // we're calculating the tileSize based on (maxSz > 1024 ? rounded : ceiled) // to the nearest power of two value of the maxSz int const ceiledSz = 1 << static_cast<int>(ceil(log(double(maxSz + 1)) / log(2.0))); int res = 0; if (maxSz < 1024) res = ceiledSz; else { int const flooredSz = ceiledSz / 2; // rounding to the nearest power of two. if (ceiledSz - maxSz < maxSz - flooredSz) res = ceiledSz; else res = flooredSz; } return min(max(res / 2, 256), 1024); } BasicTilingRenderPolicy::BasicTilingRenderPolicy(Params const & p, bool doUseQueuedRenderer) : RenderPolicy(p, GetPlatform().IsPro(), GetPlatform().CpuCores() + 2), m_DrawScale(0), m_IsEmptyModel(false), m_IsNavigating(false), m_WasAnimatingLastFrame(false), m_DoRecreateCoverage(false) { m_TileSize = CalculateTileSize(p.m_screenWidth, p.m_screenHeight); LOG(LINFO, ("ScreenSize=", p.m_screenWidth, "x", p.m_screenHeight, ", TileSize=", m_TileSize)); if (doUseQueuedRenderer) m_QueuedRenderer.reset(new QueuedRenderer(GetPlatform().CpuCores() + 1, p.m_primaryRC)); } void BasicTilingRenderPolicy::BeginFrame(shared_ptr<PaintEvent> const & e, ScreenBase const & s) { RenderPolicy::BeginFrame(e, s); if (m_QueuedRenderer) m_QueuedRenderer->BeginFrame(); } void BasicTilingRenderPolicy::CheckAnimationTransition() { // transition from non-animating to animating, // should stop all background work if (!m_WasAnimatingLastFrame && IsAnimating()) PauseBackgroundRendering(); // transition from animating to non-animating // should resume all background work if (m_WasAnimatingLastFrame && !IsAnimating()) ResumeBackgroundRendering(); m_WasAnimatingLastFrame = IsAnimating(); } void BasicTilingRenderPolicy::DrawFrame(shared_ptr<PaintEvent> const & e, ScreenBase const & s) { if (m_QueuedRenderer) { m_QueuedRenderer->DrawFrame(); m_resourceManager->updatePoolState(); } CheckAnimationTransition(); /// checking, whether we should add the CoverScreen command bool doForceUpdate = DoForceUpdate(); bool doIntersectInvalidRect = GetInvalidRect().IsIntersect(s.GlobalRect()); bool doForceUpdateFromGenerator = m_CoverageGenerator->DoForceUpdate(); if (doForceUpdate) m_CoverageGenerator->InvalidateTiles(GetInvalidRect(), scales::GetUpperWorldScale() + 1); if (!m_IsNavigating && (!IsAnimating())) m_CoverageGenerator->CoverScreen(s, doForceUpdateFromGenerator || m_DoRecreateCoverage || (doForceUpdate && doIntersectInvalidRect)); SetForceUpdate(false); m_DoRecreateCoverage = false; /// rendering current coverage Drawer * pDrawer = e->drawer(); pDrawer->beginFrame(); pDrawer->screen()->clear(m_bgColor); FrameLock(); m_CoverageGenerator->Draw(pDrawer->screen(), s); m_DrawScale = m_CoverageGenerator->GetDrawScale(); m_IsEmptyModel = m_CoverageGenerator->IsEmptyDrawing(); if (m_IsEmptyModel) m_countryIndex = m_CoverageGenerator->GetCountryIndexAtCenter(); pDrawer->endFrame(); } void BasicTilingRenderPolicy::EndFrame(shared_ptr<PaintEvent> const & e, ScreenBase const & s) { FrameUnlock(); if (m_QueuedRenderer) m_QueuedRenderer->EndFrame(); RenderPolicy::EndFrame(e, s); } TileRenderer & BasicTilingRenderPolicy::GetTileRenderer() { return *m_TileRenderer.get(); } void BasicTilingRenderPolicy::PauseBackgroundRendering() { m_TileRenderer->SetIsPaused(true); m_TileRenderer->CancelCommands(); m_CoverageGenerator->Pause(); if (m_QueuedRenderer) m_QueuedRenderer->SetPartialExecution(GetPlatform().CpuCores(), true); } void BasicTilingRenderPolicy::ResumeBackgroundRendering() { m_TileRenderer->SetIsPaused(false); m_CoverageGenerator->Resume(); m_DoRecreateCoverage = true; if (m_QueuedRenderer) m_QueuedRenderer->SetPartialExecution(GetPlatform().CpuCores(), false); } void BasicTilingRenderPolicy::StartNavigation() { m_IsNavigating = true; PauseBackgroundRendering(); } void BasicTilingRenderPolicy::StopNavigation() { m_IsNavigating = false; ResumeBackgroundRendering(); } void BasicTilingRenderPolicy::StartScale() { StartNavigation(); } void BasicTilingRenderPolicy::StopScale() { StopNavigation(); RenderPolicy::StopScale(); } void BasicTilingRenderPolicy::StartDrag() { StartNavigation(); } void BasicTilingRenderPolicy::StopDrag() { StopNavigation(); RenderPolicy::StopDrag(); } void BasicTilingRenderPolicy::StartRotate(double a, double timeInSec) { StartNavigation(); } void BasicTilingRenderPolicy::StopRotate(double a, double timeInSec) { StopNavigation(); RenderPolicy::StopRotate(a, timeInSec); } bool BasicTilingRenderPolicy::IsTiling() const { return true; } int BasicTilingRenderPolicy::GetDrawScale(ScreenBase const & s) const { return m_DrawScale; } bool BasicTilingRenderPolicy::IsEmptyModel() const { return m_IsEmptyModel; } storage::TIndex BasicTilingRenderPolicy::GetCountryIndex() const { return m_countryIndex; } bool BasicTilingRenderPolicy::NeedRedraw() const { if (RenderPolicy::NeedRedraw()) return true; if (m_QueuedRenderer && m_QueuedRenderer->NeedRedraw()) return true; return false; } size_t BasicTilingRenderPolicy::ScaleEtalonSize() const { return m_TileSize; } size_t BasicTilingRenderPolicy::TileSize() const { return m_TileSize; } void BasicTilingRenderPolicy::FrameLock() { m_CoverageGenerator->Lock(); } void BasicTilingRenderPolicy::FrameUnlock() { m_CoverageGenerator->Unlock(); } graphics::Overlay * BasicTilingRenderPolicy::FrameOverlay() const { return m_CoverageGenerator->GetOverlay(); } int BasicTilingRenderPolicy::InsertBenchmarkFence() { return m_CoverageGenerator->InsertBenchmarkFence(); } void BasicTilingRenderPolicy::JoinBenchmarkFence(int fenceID) { return m_CoverageGenerator->JoinBenchmarkFence(fenceID); } <commit_msg>Don't stop rendering on active animation task<commit_after>#include "basic_tiling_render_policy.hpp" #include "../platform/platform.hpp" #include "../indexer/scales.hpp" #include "tile_renderer.hpp" #include "coverage_generator.hpp" #include "queued_renderer.hpp" size_t BasicTilingRenderPolicy::CalculateTileSize(size_t screenWidth, size_t screenHeight) { int const maxSz = max(screenWidth, screenHeight); // we're calculating the tileSize based on (maxSz > 1024 ? rounded : ceiled) // to the nearest power of two value of the maxSz int const ceiledSz = 1 << static_cast<int>(ceil(log(double(maxSz + 1)) / log(2.0))); int res = 0; if (maxSz < 1024) res = ceiledSz; else { int const flooredSz = ceiledSz / 2; // rounding to the nearest power of two. if (ceiledSz - maxSz < maxSz - flooredSz) res = ceiledSz; else res = flooredSz; } return min(max(res / 2, 256), 1024); } BasicTilingRenderPolicy::BasicTilingRenderPolicy(Params const & p, bool doUseQueuedRenderer) : RenderPolicy(p, GetPlatform().IsPro(), GetPlatform().CpuCores() + 2), m_DrawScale(0), m_IsEmptyModel(false), m_IsNavigating(false), m_WasAnimatingLastFrame(false), m_DoRecreateCoverage(false) { m_TileSize = CalculateTileSize(p.m_screenWidth, p.m_screenHeight); LOG(LINFO, ("ScreenSize=", p.m_screenWidth, "x", p.m_screenHeight, ", TileSize=", m_TileSize)); if (doUseQueuedRenderer) m_QueuedRenderer.reset(new QueuedRenderer(GetPlatform().CpuCores() + 1, p.m_primaryRC)); } void BasicTilingRenderPolicy::BeginFrame(shared_ptr<PaintEvent> const & e, ScreenBase const & s) { RenderPolicy::BeginFrame(e, s); if (m_QueuedRenderer) m_QueuedRenderer->BeginFrame(); } void BasicTilingRenderPolicy::CheckAnimationTransition() { // transition from non-animating to animating, // should stop all background work if (!m_WasAnimatingLastFrame && IsAnimating()) PauseBackgroundRendering(); // transition from animating to non-animating // should resume all background work if (m_WasAnimatingLastFrame && !IsAnimating()) ResumeBackgroundRendering(); m_WasAnimatingLastFrame = IsAnimating(); } void BasicTilingRenderPolicy::DrawFrame(shared_ptr<PaintEvent> const & e, ScreenBase const & s) { if (m_QueuedRenderer) { m_QueuedRenderer->DrawFrame(); m_resourceManager->updatePoolState(); } //CheckAnimationTransition(); /// checking, whether we should add the CoverScreen command bool doForceUpdate = DoForceUpdate(); bool doIntersectInvalidRect = GetInvalidRect().IsIntersect(s.GlobalRect()); bool doForceUpdateFromGenerator = m_CoverageGenerator->DoForceUpdate(); if (doForceUpdate) m_CoverageGenerator->InvalidateTiles(GetInvalidRect(), scales::GetUpperWorldScale() + 1); if (!m_IsNavigating && (!IsAnimating())) m_CoverageGenerator->CoverScreen(s, doForceUpdateFromGenerator || m_DoRecreateCoverage || (doForceUpdate && doIntersectInvalidRect)); SetForceUpdate(false); m_DoRecreateCoverage = false; /// rendering current coverage Drawer * pDrawer = e->drawer(); pDrawer->beginFrame(); pDrawer->screen()->clear(m_bgColor); FrameLock(); m_CoverageGenerator->Draw(pDrawer->screen(), s); m_DrawScale = m_CoverageGenerator->GetDrawScale(); m_IsEmptyModel = m_CoverageGenerator->IsEmptyDrawing(); if (m_IsEmptyModel) m_countryIndex = m_CoverageGenerator->GetCountryIndexAtCenter(); pDrawer->endFrame(); } void BasicTilingRenderPolicy::EndFrame(shared_ptr<PaintEvent> const & e, ScreenBase const & s) { FrameUnlock(); if (m_QueuedRenderer) m_QueuedRenderer->EndFrame(); RenderPolicy::EndFrame(e, s); } TileRenderer & BasicTilingRenderPolicy::GetTileRenderer() { return *m_TileRenderer.get(); } void BasicTilingRenderPolicy::PauseBackgroundRendering() { m_TileRenderer->SetIsPaused(true); m_TileRenderer->CancelCommands(); m_CoverageGenerator->Pause(); if (m_QueuedRenderer) m_QueuedRenderer->SetPartialExecution(GetPlatform().CpuCores(), true); } void BasicTilingRenderPolicy::ResumeBackgroundRendering() { m_TileRenderer->SetIsPaused(false); m_CoverageGenerator->Resume(); m_DoRecreateCoverage = true; if (m_QueuedRenderer) m_QueuedRenderer->SetPartialExecution(GetPlatform().CpuCores(), false); } void BasicTilingRenderPolicy::StartNavigation() { m_IsNavigating = true; PauseBackgroundRendering(); } void BasicTilingRenderPolicy::StopNavigation() { m_IsNavigating = false; ResumeBackgroundRendering(); } void BasicTilingRenderPolicy::StartScale() { StartNavigation(); } void BasicTilingRenderPolicy::StopScale() { StopNavigation(); RenderPolicy::StopScale(); } void BasicTilingRenderPolicy::StartDrag() { StartNavigation(); } void BasicTilingRenderPolicy::StopDrag() { StopNavigation(); RenderPolicy::StopDrag(); } void BasicTilingRenderPolicy::StartRotate(double a, double timeInSec) { StartNavigation(); } void BasicTilingRenderPolicy::StopRotate(double a, double timeInSec) { StopNavigation(); RenderPolicy::StopRotate(a, timeInSec); } bool BasicTilingRenderPolicy::IsTiling() const { return true; } int BasicTilingRenderPolicy::GetDrawScale(ScreenBase const & s) const { return m_DrawScale; } bool BasicTilingRenderPolicy::IsEmptyModel() const { return m_IsEmptyModel; } storage::TIndex BasicTilingRenderPolicy::GetCountryIndex() const { return m_countryIndex; } bool BasicTilingRenderPolicy::NeedRedraw() const { if (RenderPolicy::NeedRedraw()) return true; if (m_QueuedRenderer && m_QueuedRenderer->NeedRedraw()) return true; return false; } size_t BasicTilingRenderPolicy::ScaleEtalonSize() const { return m_TileSize; } size_t BasicTilingRenderPolicy::TileSize() const { return m_TileSize; } void BasicTilingRenderPolicy::FrameLock() { m_CoverageGenerator->Lock(); } void BasicTilingRenderPolicy::FrameUnlock() { m_CoverageGenerator->Unlock(); } graphics::Overlay * BasicTilingRenderPolicy::FrameOverlay() const { return m_CoverageGenerator->GetOverlay(); } int BasicTilingRenderPolicy::InsertBenchmarkFence() { return m_CoverageGenerator->InsertBenchmarkFence(); } void BasicTilingRenderPolicy::JoinBenchmarkFence(int fenceID) { return m_CoverageGenerator->JoinBenchmarkFence(fenceID); } <|endoftext|>
<commit_before>#include "PRINTOBJ.H" #include "EFFECTS.H" #include "MATHS.H" #include "LOAD_LEV.H" #include "SETUP.H" #include "SPECIFIC.H" #include "DRAWOBJ.H" #include "DRAW.H" #include "3D_GEN.H" #include "ITEMS.H" #include "DELTAPAK.H" #include "CONTROL.H" #include "ANIMITEM.H" #include "LIGHT.H" #include <GTEREG.H> void DrawEffect(short item_num) { struct FX_INFO* fx = &effects[item_num]; struct object_info* obj = &objects[fx->object_number]; if (obj->draw_routine != NULL && obj->loaded) { mPushMatrix(); mTranslateAbsXYZ(fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos); if (Matrix->tz < 20480) { mRotYXZ(fx->pos.y_rot, fx->pos.x_rot, fx->pos.z_rot); S_CalculateLight(fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos, fx->room_number, &duff_item.il); duff_item.il.Light[3].pad = 0; phd_PutPolygons(meshes[obj->nmeshes != 0 ? obj->mesh_index : fx->frame_number], -1); } mPopMatrix(); } } void PrintAllOtherObjects_ASM(short room_num /*s3*/)//(F) { struct room_info* r = &room[room_num]; struct ITEM_INFO* item = NULL; struct object_info* object; short item_num; struct FX_INFO* effect; int mesh_num; // short* mesh; int effect_num; r->bound_active = 0; mPushMatrix(); mTranslateAbsXYZ(r->x, r->y, r->z); phd_right = 512; phd_bottom = 240; phd_left = 0; phd_top = 0; item_num = r->item_number; if (item_num != -1) { do { item = &items[item_num]; object = &objects[item->object_number]; if (item->status != 3) { if (!object->using_drawanimating_item && object->draw_routine != NULL) { object->draw_routine(item); } } //loc_8F5AC if (object->draw_routine_extra != NULL) { object->draw_routine_extra(item); } //loc_8F5C4 if (item->after_death - 1 < 127) { item->after_death++; if (item->after_death == 128) { KillItem(r->item_number); } }//loc_8F5EC item_num = item->next_item; } while (item_num != -1); }//loc_8F5FC effect_num = r->fx_number; if (effect_num != -1) { //loc_8F608 do { effect = &effects[effect_num]; object = &objects[effect->object_number]; if (object->draw_routine != NULL && object->loaded) { mPushMatrix(); mTranslateAbsXYZ(effect->pos.x_pos, effect->pos.y_pos, effect->pos.z_pos); if (((int*)MatrixStack)[2] - 21 < 20459) { mRotYXZ(effect->pos.y_rot, effect->pos.x_rot, effect->pos.z_rot); duff_item.il.Light[3].pad = 0; S_CalculateLight(effect->pos.x_pos, effect->pos.y_pos, effect->pos.z_pos, effect->room_number, &duff_item.il); mesh_num = effect->frame_number; if (object->nmeshes != 0) { mesh_num = object->mesh_index; }//loc_8F6C0 phd_PutPolygons(meshes[mesh_num], -1); }//loc_8F6D8 mPopMatrix(); //loc_8F6E0 effect_num = effect->next_fx; } } while (effect_num != -1);//loc_8F6E0 }//loc_8F6EC mPopMatrix(); ((int*)&r->left)[0] = 511; ((int*)&r->top)[0] = 239; } void print_all_object_NOW()//8F474(<), 914B8(<) (F) { CalcAllAnimatingItems_ASM(); for (int i = 0; i < number_draw_rooms; i++) { PrintAllOtherObjects_ASM(draw_rooms[i]); } }<commit_msg>[Specific-PSXPC_N] Fix sign error.<commit_after>#include "PRINTOBJ.H" #include "EFFECTS.H" #include "MATHS.H" #include "LOAD_LEV.H" #include "SETUP.H" #include "SPECIFIC.H" #include "DRAWOBJ.H" #include "DRAW.H" #include "3D_GEN.H" #include "ITEMS.H" #include "DELTAPAK.H" #include "CONTROL.H" #include "ANIMITEM.H" #include "LIGHT.H" #include <GTEREG.H> void DrawEffect(short item_num) { struct FX_INFO* fx = &effects[item_num]; struct object_info* obj = &objects[fx->object_number]; if (obj->draw_routine != NULL && obj->loaded) { mPushMatrix(); mTranslateAbsXYZ(fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos); if (Matrix->tz < 20480) { mRotYXZ(fx->pos.y_rot, fx->pos.x_rot, fx->pos.z_rot); S_CalculateLight(fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos, fx->room_number, &duff_item.il); duff_item.il.Light[3].pad = 0; phd_PutPolygons(meshes[obj->nmeshes != 0 ? obj->mesh_index : fx->frame_number], -1); } mPopMatrix(); } } void PrintAllOtherObjects_ASM(short room_num /*s3*/)//(F) { struct room_info* r = &room[room_num]; struct ITEM_INFO* item = NULL; struct object_info* object; short item_num; struct FX_INFO* effect; int mesh_num; // short* mesh; int effect_num; r->bound_active = 0; mPushMatrix(); mTranslateAbsXYZ(r->x, r->y, r->z); phd_right = 512; phd_bottom = 240; phd_left = 0; phd_top = 0; item_num = r->item_number; if (item_num != -1) { do { item = &items[item_num]; object = &objects[item->object_number]; if (item->status != 3) { if (!object->using_drawanimating_item && object->draw_routine != NULL) { object->draw_routine(item); } } //loc_8F5AC if (object->draw_routine_extra != NULL) { object->draw_routine_extra(item); } //loc_8F5C4 if ((unsigned)(item->after_death - 1) < 127) { item->after_death++; if (item->after_death == 128) { KillItem(r->item_number); } }//loc_8F5EC item_num = item->next_item; } while (item_num != -1); }//loc_8F5FC effect_num = r->fx_number; if (effect_num != -1) { //loc_8F608 do { effect = &effects[effect_num]; object = &objects[effect->object_number]; if (object->draw_routine != NULL && object->loaded) { mPushMatrix(); mTranslateAbsXYZ(effect->pos.x_pos, effect->pos.y_pos, effect->pos.z_pos); if (((int*)MatrixStack)[2] - 21 < 20459) { mRotYXZ(effect->pos.y_rot, effect->pos.x_rot, effect->pos.z_rot); duff_item.il.Light[3].pad = 0; S_CalculateLight(effect->pos.x_pos, effect->pos.y_pos, effect->pos.z_pos, effect->room_number, &duff_item.il); mesh_num = effect->frame_number; if (object->nmeshes != 0) { mesh_num = object->mesh_index; }//loc_8F6C0 phd_PutPolygons(meshes[mesh_num], -1); }//loc_8F6D8 mPopMatrix(); //loc_8F6E0 effect_num = effect->next_fx; } } while (effect_num != -1);//loc_8F6E0 }//loc_8F6EC mPopMatrix(); ((int*)&r->left)[0] = 511; ((int*)&r->top)[0] = 239; } void print_all_object_NOW()//8F474(<), 914B8(<) (F) { CalcAllAnimatingItems_ASM(); for (int i = 0; i < number_draw_rooms; i++) { PrintAllOtherObjects_ASM(draw_rooms[i]); } }<|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////// // // name: AliHits2SDigits // date: 4.4.2002 // last update: 4.4.2002 // author: Jiri Chudoba // version: 1.0 // // description: // creates sdigits for several detectors // stores sdigits in separate file (or in the source file // with hits). Stores gAlice object and copies TE to the // file with sdigits // // input: // TString fileNameSDigits ... output file with sdigits // TString fileNameHits ... input file with hits // Int_t nEvents ... how many events to proceed // Int_t firstEvent ... first event number // Int_t ITS, TPC, ... many flags for diff. detectors // // History: // // 04.04.02 - first version // //////////////////////////////////////////////////////////////////////// #if !defined(__CINT__) || defined(__MAKECINT__) #include "iostream.h" #include "TTree.h" #include "TBranch.h" #include "TDirectory.h" #include "TFile.h" #include "AliRun.h" #include "TParticle.h" #include "TPC/AliTPCDigitsArray.h" #include "AliHeader.h" #include "TGeometry.h" #include "TObjArray.h" #include "TString.h" #include "ITS/AliITS.h" #include "TPC/AliTPC.h" #include "PHOS/AliPHOSSDigitizer.h" #include "TRD/AliTRDdigitizer.h" #include "TStopwatch.h" #include "TRD/AliTRDparameter.h" #endif TFile* Init(TString fileNameSDigits, TString fileNameHits); TFile* OpenFile(TString fileName); Bool_t ImportgAlice(TFile *file); AliTRDdigitizer *InitTRDdigitizer(); void AliCopy(TFile *inputFile, TFile *outputFile); // global variables TFile *gFileHits = 0; Bool_t gSameFiles = kFALSE; Int_t gDEBUG = 1; Int_t AliHits2SDigits(TString fileNameSDigits="sdigits.root", TString fileNameHits="rfio:galice.root", Int_t nEvents = 1, Int_t firstEvent = 0, Int_t iITS = 0, Int_t iTPC = 0, Int_t iTRD = 0,Int_t iPHOS = 0, Int_t iCopy = 1) { // // Initialization // TFile *fileSDigits; fileSDigits = Init(fileNameSDigits, fileNameHits); if (!fileSDigits) return 1; if (iCopy) { AliCopy(gFileHits,fileSDigits); gFileHits->cd(); } // ITS AliITS *ITS; if (iITS) { ITS = (AliITS*) gAlice->GetModule("ITS"); if (!ITS) { iITS = 0; cerr<<"AliITS object not found on file." << endl; } else if (!ITS->GetITSgeom()) { cerr<<"AliITSgeom not found." << endl; iITS = 0; } } // TPC AliTPC *TPC; if (iTPC) { TPC = (AliTPC*)gAlice->GetDetector("TPC"); if (!TPC) { iTPC = 0; cerr<<"AliTPC object not found"<<endl; } } // TRD AliTRDdigitizer *sdTRD; if (iTRD) { sdTRD = InitTRDdigitizer(); } // PHOS AliPHOSSDigitizer *sdPHOS; if (iPHOS) { sdPHOS = new AliPHOSSDigitizer(fileNameHits.Data()); } // // loop over events // TStopwatch timer; timer.Start(); for (Int_t iEvent = firstEvent;iEvent<firstEvent+nEvents;iEvent++){ gAlice->GetEvent(iEvent); gAlice->MakeTree("S",fileSDigits); // ITS if (iITS) { if (gDEBUG) {cout<<" Create ITS sdigits: ";} ITS->MakeBranch("S"); ITS->SetTreeAddress(); ITS->Hits2SDigits(); if (gDEBUG) {cout<<"done"<<endl;} } // TPC if (iTPC) { if (gDEBUG) {cout<<" Create TPC sdigits: ";} TPC->SetActiveSectors(1); TPC->Hits2SDigits2(iEvent); if (gDEBUG) {cout<<"done"<<endl;} } // TRD if (iTRD) { if (gDEBUG) {cout<<" Create TRD sdigits: ";} sdTRD->InitOutput(fileSDigits, iEvent); sdTRD->MakeDigits(); sdTRD->WriteDigits(); if (gDEBUG) {cout<<"done"<<endl;} } } // end of loop over events // PHOS processes always all events if (iPHOS) { sdPHOS->ExecuteTask("deb all"); } // // finish // timer.Stop(); timer.Print(); if (iTRD) { fileSDigits->cd(); sdTRD->GetParameter()->Write(); gFileHits->cd(); } fileSDigits->Close(); delete fileSDigits; if (!gSameFiles) { gFileHits->Close(); delete gFileHits; } } //////////////////////////////////////////////////////////////////////// TFile* Init(TString fileNameSDigits, TString fileNameHits) { // open input file, read in gAlice, prepare output file if (gAlice) delete gAlice; gAlice = 0; Bool_t gSameFiles = kFALSE; if (fileNameSDigits == fileNameHits || fileNameSDigits == "") gSameFiles = kTRUE; TString fileMode = "read"; if (gSameFiles) fileMode = "update"; gFileHits = TFile::Open(fileNameHits.Data(),fileMode.Data()); if (!gFileHits->IsOpen()) { cerr<<"Can't open "<<fileNameHits.Data()<<" !\n"; return 0; } if (!ImportgAlice(gFileHits)) return 0; if (!gSameFiles) return gAlice->InitTreeFile("S",fileNameSDigits.Data()); return gFileHits; } //////////////////////////////////////////////////////////////////////// TFile* OpenFile(TString fileName) { // open file fileName TFile *file = TFile::Open(fileName.Data()); if (!file->IsOpen()) { cerr<<"Can't open "<<fileName.Data()<<" !\n"; return 0; } return file; } //////////////////////////////////////////////////////////////////////// Bool_t ImportgAlice(TFile *file) { // read in gAlice object from the file gAlice = (AliRun*)file->Get("gAlice"); if (!gAlice) return kFALSE; return kTRUE; } //////////////////////////////////////////////////////////////////////// AliTRDdigitizer *InitTRDdigitizer() { // initialization of TRD digitizer AliTRDdigitizer *sdTRD = new AliTRDdigitizer("TRDdigitizer" ,"TRD digitizer class"); sdTRD->SetDebug(0); sdTRD->SetSDigits(kTRUE); AliTRDparameter *TRDparam = new AliTRDparameter("TRDparameter" ,"TRD parameter class"); sdTRD->SetParameter(TRDparam); sdTRD->InitDetector(); return sdTRD; } //////////////////////////////////////////////////////////////////////// void AliCopy(TFile *inputFile, TFile *outputFile) { // copy some objects // copy gAlice if (gDEBUG) cout<<"Copy gAlice: "; outputFile->cd(); gAlice->Write(); if (gDEBUG) cout<<"done"<<endl; TTree *treeE = gAlice->TreeE(); if (!treeE) { cerr<<"No TreeE found "<<endl; return; } // copy TreeE if (gDEBUG) cout<<"Copy TreeE: "; AliHeader *header = new AliHeader(); treeE->SetBranchAddress("Header", &header); treeE->SetBranchStatus("*",1); TTree *treeENew = treeE->CloneTree(); treeENew->Write(); if (gDEBUG) cout<<"done"<<endl; // copy AliceGeom if (gDEBUG) cout<<"Copy AliceGeom: "; TGeometry *AliceGeom = static_cast<TGeometry*>(inputFile->Get("AliceGeom")); if (!AliceGeom) { cerr<<"AliceGeom was not found in the input file "<<endl; return; } AliceGeom->Write(); if (gDEBUG) cout<<"done"<<endl; } <commit_msg>Add TOF. Beware - the number of input parameters increased by 1. Add possibility to choose between full TPC (param = 1) and partially processed TPC (only sectors with signal, param = 2).<commit_after>//////////////////////////////////////////////////////////////////////// // // name: AliHits2SDigits // date: 4.4.2002 // last update: 4.4.2002 // author: Jiri Chudoba // version: 1.0 // // description: // creates sdigits for several detectors // stores sdigits in separate file (or in the source file // with hits). Stores gAlice object and copies TE to the // file with sdigits // // input: // TString fileNameSDigits ... output file with sdigits // TString fileNameHits ... input file with hits // Int_t nEvents ... how many events to proceed // Int_t firstEvent ... first event number // Int_t ITS, TPC, ... many flags for diff. detectors // // History: // // 04.04.02 - first version // //////////////////////////////////////////////////////////////////////// #if !defined(__CINT__) || defined(__MAKECINT__) #include "iostream.h" #include "TTree.h" #include "TBranch.h" #include "TDirectory.h" #include "TFile.h" #include "AliRun.h" #include "TParticle.h" #include "TPC/AliTPCDigitsArray.h" #include "AliHeader.h" #include "TGeometry.h" #include "TObjArray.h" #include "TString.h" #include "ITS/AliITS.h" #include "TPC/AliTPC.h" #include "PHOS/AliPHOSSDigitizer.h" #include "TRD/AliTRDdigitizer.h" #include "TStopwatch.h" #include "TRD/AliTRDparameter.h" #include "TOF/AliTOFSDigitizer.h" #endif TFile* Init(TString fileNameSDigits, TString fileNameHits); TFile* OpenFile(TString fileName); Bool_t ImportgAlice(TFile *file); AliTRDdigitizer *InitTRDdigitizer(); void AliCopy(TFile *inputFile, TFile *outputFile); // global variables TFile *gFileHits = 0; Bool_t gSameFiles = kFALSE; Int_t gDEBUG = 1; Int_t AliHits2SDigits(TString fileNameSDigits="sdigits.root", TString fileNameHits="rfio:galice.root", Int_t nEvents = 1, Int_t firstEvent = 0, Int_t iITS = 0, Int_t iTPC = 0, Int_t iTRD = 0,Int_t iPHOS = 0, Int_t iTOF = 0, Int_t iCopy = 1) { // // Initialization // TFile *fileSDigits; fileSDigits = Init(fileNameSDigits, fileNameHits); if (!fileSDigits) return 1; if (iCopy) { AliCopy(gFileHits,fileSDigits); gFileHits->cd(); } // ITS AliITS *ITS; if (iITS) { ITS = (AliITS*) gAlice->GetModule("ITS"); if (!ITS) { iITS = 0; cerr<<"AliITS object not found on file." << endl; } else if (!ITS->GetITSgeom()) { iITS = 0; cerr<<"AliITSgeom not found." << endl; } } // TPC AliTPC *TPC; if (iTPC) { TPC = (AliTPC*)gAlice->GetDetector("TPC"); if (!TPC) { iTPC = 0; cerr<<"AliTPC object not found"<<endl; } } // TRD AliTRDdigitizer *sdTRD; if (iTRD) { sdTRD = InitTRDdigitizer(); } // PHOS AliPHOSSDigitizer *sdPHOS; if (iPHOS) { sdPHOS = new AliPHOSSDigitizer(fileNameHits.Data()); } // TOF AliTOFSDigitizer *sdTOF; if (iTOF) { sdTOF = new AliTOFSDigitizer(fileNameHits.Data(),firstEvent,nEvents); } // // loop over events // TStopwatch timer; timer.Start(); for (Int_t iEvent = firstEvent;iEvent<firstEvent+nEvents;iEvent++){ gAlice->GetEvent(iEvent); if (!gAlice->TreeS()) gAlice->MakeTree("S",fileSDigits); // ITS if (iITS) { if (gDEBUG) {cout<<" Create ITS sdigits: ";} ITS->MakeBranch("S"); ITS->SetTreeAddress(); ITS->Hits2SDigits(); if (gDEBUG) {cout<<"done"<<endl;} } // TPC if (iTPC) { if (gDEBUG) {cout<<" Create TPC sdigits: ";} if (iTPC == 1) { // process all sectors TPC->SetActiveSectors(1); if (gDEBUG) {cout<<"All TPC sectors set active."<<endl;} } else if (iTPC == 2) { // process only sectors with hits TPC->SetActiveSectors(0); if (gDEBUG) { printf("\nActive sectors\n"); Int_t iActive = 0; for (Int_t i=0;i<72;i++) { if (TPC->IsSectorActive(i)) { printf("%2d ",i); iActive++; if (iActive%10 == 0) printf("\n"); } } printf("\n"); } } TPC->Hits2SDigits2(iEvent); if (gDEBUG) {cout<<"done"<<endl;} } // TRD if (iTRD) { if (gDEBUG) {cout<<" Create TRD sdigits: ";} sdTRD->InitOutput(fileSDigits, iEvent); sdTRD->MakeDigits(); sdTRD->WriteDigits(); if (gDEBUG) {cout<<"done"<<endl;} } } // end of loop over events // PHOS processes always all events if (iPHOS) { sdPHOS->ExecuteTask("deb all"); } // TOF does its own loop if (iTOF) { sdTOF->Exec(""); } // // finish // timer.Stop(); timer.Print(); if (iTRD) { fileSDigits->cd(); sdTRD->GetParameter()->Write(); } gFileHits->cd(); delete gAlice; gAlice = 0; if (!gSameFiles) { gFileHits->Close(); delete gFileHits; } } //////////////////////////////////////////////////////////////////////// TFile* Init(TString fileNameSDigits, TString fileNameHits) { // open input file, read in gAlice, prepare output file if (gAlice) delete gAlice; gAlice = 0; Bool_t gSameFiles = kFALSE; if (fileNameSDigits == fileNameHits || fileNameSDigits == "") gSameFiles = kTRUE; TString fileMode = "read"; if (gSameFiles) fileMode = "update"; gFileHits = TFile::Open(fileNameHits.Data(),fileMode.Data()); if (!gFileHits->IsOpen()) { cerr<<"Can't open "<<fileNameHits.Data()<<" !\n"; return 0; } if (!ImportgAlice(gFileHits)) return 0; if (!gSameFiles) return gAlice->InitTreeFile("S",fileNameSDigits.Data()); return gFileHits; } //////////////////////////////////////////////////////////////////////// TFile* OpenFile(TString fileName) { // open file fileName TFile *file = TFile::Open(fileName.Data()); if (!file->IsOpen()) { cerr<<"Can't open "<<fileName.Data()<<" !\n"; return 0; } return file; } //////////////////////////////////////////////////////////////////////// Bool_t ImportgAlice(TFile *file) { // read in gAlice object from the file gAlice = (AliRun*)file->Get("gAlice"); if (!gAlice) return kFALSE; return kTRUE; } //////////////////////////////////////////////////////////////////////// AliTRDdigitizer *InitTRDdigitizer() { // initialization of TRD digitizer AliTRDdigitizer *sdTRD = new AliTRDdigitizer("TRDdigitizer" ,"TRD digitizer class"); sdTRD->SetDebug(0); sdTRD->SetSDigits(kTRUE); AliTRDparameter *TRDparam = new AliTRDparameter("TRDparameter" ,"TRD parameter class"); sdTRD->SetParameter(TRDparam); sdTRD->InitDetector(); return sdTRD; } //////////////////////////////////////////////////////////////////////// void AliCopy(TFile *inputFile, TFile *outputFile) { // copy some objects // copy gAlice if (gDEBUG) cout<<"Copy gAlice: "; outputFile->cd(); gAlice->Write(); if (gDEBUG) cout<<"done"<<endl; TTree *treeE = gAlice->TreeE(); if (!treeE) { cerr<<"No TreeE found "<<endl; return; } // copy TreeE if (gDEBUG) cout<<"Copy TreeE: "; AliHeader *header = new AliHeader(); treeE->SetBranchAddress("Header", &header); treeE->SetBranchStatus("*",1); TTree *treeENew = treeE->CloneTree(); treeENew->Write(); if (gDEBUG) cout<<"done"<<endl; // copy AliceGeom if (gDEBUG) cout<<"Copy AliceGeom: "; TGeometry *AliceGeom = static_cast<TGeometry*>(inputFile->Get("AliceGeom")); if (!AliceGeom) { cerr<<"AliceGeom was not found in the input file "<<endl; return; } AliceGeom->Write(); if (gDEBUG) cout<<"done"<<endl; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //------------------------------------------------------------------------ // Magnetic field composed by 4 maps: the L3 magnet (inside and outside measured region), // extended region, and dipole magnet. // Used in the configuration macros (macros/Config.C, etc.) // Author: Andreas Morsch <andreas.morsch@cern.ch> //------------------------------------------------------------------------ #include <TClass.h> #include <TFile.h> #include <TMath.h> #include <TSystem.h> #include "AliLog.h" #include "AliFieldMap.h" #include "AliMagFMapsV1.h" #include "AliMagFCheb.h" ClassImp(AliMagFMapsV1) //_______________________________________________________________________ AliMagFMapsV1::AliMagFMapsV1(): AliMagFMaps() { // // Default constructor // } //_______________________________________________________________________ AliMagFMapsV1::AliMagFMapsV1(const char *name, const char *title, Int_t integ, Float_t factor, Float_t fmax, Int_t map, Int_t l3): AliMagFMaps(name, title, integ, factor, fmax, map, l3), fMeasuredMap(0) { // // Constructor // char* fname; fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/mfcheb.root"); TFile* file = new TFile(fname); if (fMap == k2kG) { fMeasuredMap = dynamic_cast<AliMagFCheb*>(file->Get("Sol12_Dip6_Hole")); fSolenoid = 0.2; // T } else if (fMap == k5kG) { fMeasuredMap = dynamic_cast<AliMagFCheb*>(file->Get("Sol30_Dip6_Hole")); fSolenoid = 0.5; // T } else if (fMap == k4kG){ fMeasuredMap = 0; fSolenoid = 0.4; // T } file->Close(); delete file; } //_______________________________________________________________________ AliMagFMapsV1::~AliMagFMapsV1() { // Destructor delete fMeasuredMap; } //_______________________________________________________________________ void AliMagFMapsV1::Field(Float_t *x, Float_t *b) const { // // Method to calculate the magnetic field at position x // const Float_t kRmax2 = 500. * 500.; const Float_t kZmax = 550.; const Float_t kTeslaTokG = 10.; const Float_t kScale = 0.98838; // matching factor // Check if position inside measured map Float_t r2 = x[0] * x[0] + x[1] * x[1]; if (fMeasuredMap && r2 < kRmax2 && TMath::Abs(x[2]) < kZmax ) { fMeasuredMap->Field(x, b); b[0] *= kTeslaTokG; b[1] *= kTeslaTokG; b[2] *= kTeslaTokG; } else { AliMagFMaps::Field(x, b); // Match to measure map b[0] = - b[0] * kScale; b[2] = - b[2] * kScale; b[1] = b[1] * kScale; } } Float_t AliMagFMapsV1::SolenoidField() const { // // Returns max. L3 (solenoid) field strength // according to field map setting // return fSolenoid; } <commit_msg>Correct sign for calculated b_y (outside measured region).<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //------------------------------------------------------------------------ // Magnetic field composed by 4 maps: the L3 magnet (inside and outside measured region), // extended region, and dipole magnet. // Used in the configuration macros (macros/Config.C, etc.) // Author: Andreas Morsch <andreas.morsch@cern.ch> //------------------------------------------------------------------------ #include <TClass.h> #include <TFile.h> #include <TMath.h> #include <TSystem.h> #include "AliLog.h" #include "AliFieldMap.h" #include "AliMagFMapsV1.h" #include "AliMagFCheb.h" ClassImp(AliMagFMapsV1) //_______________________________________________________________________ AliMagFMapsV1::AliMagFMapsV1(): AliMagFMaps() { // // Default constructor // } //_______________________________________________________________________ AliMagFMapsV1::AliMagFMapsV1(const char *name, const char *title, Int_t integ, Float_t factor, Float_t fmax, Int_t map, Int_t l3): AliMagFMaps(name, title, integ, factor, fmax, map, l3), fMeasuredMap(0) { // // Constructor // char* fname; fname = gSystem->ExpandPathName("$(ALICE_ROOT)/data/maps/mfcheb.root"); TFile* file = new TFile(fname); if (fMap == k2kG) { fMeasuredMap = dynamic_cast<AliMagFCheb*>(file->Get("Sol12_Dip6_Hole")); fSolenoid = 0.2; // T } else if (fMap == k5kG) { fMeasuredMap = dynamic_cast<AliMagFCheb*>(file->Get("Sol30_Dip6_Hole")); fSolenoid = 0.5; // T } else if (fMap == k4kG){ fMeasuredMap = 0; fSolenoid = 0.4; // T } file->Close(); delete file; } //_______________________________________________________________________ AliMagFMapsV1::~AliMagFMapsV1() { // Destructor delete fMeasuredMap; } //_______________________________________________________________________ void AliMagFMapsV1::Field(Float_t *x, Float_t *b) const { // // Method to calculate the magnetic field at position x // const Float_t kRmax2 = 500. * 500.; const Float_t kZmax = 550.; const Float_t kTeslaTokG = 10.; const Float_t kScale = 0.98838; // matching factor // Check if position inside measured map Float_t r2 = x[0] * x[0] + x[1] * x[1]; if (fMeasuredMap && r2 < kRmax2 && TMath::Abs(x[2]) < kZmax ) { fMeasuredMap->Field(x, b); b[0] *= kTeslaTokG; b[1] *= kTeslaTokG; b[2] *= kTeslaTokG; } else { AliMagFMaps::Field(x, b); // Match to measure map b[0] = - b[0] * kScale; b[2] = - b[2] * kScale; b[1] = - b[1] * kScale; } } Float_t AliMagFMapsV1::SolenoidField() const { // // Returns max. L3 (solenoid) field strength // according to field map setting // return fSolenoid; } <|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 "common/common.h" #ifndef ZORBA_NO_UNICODE #include "zorbatypes/libicu.h" #endif //#include <boost/algorithm/string/split.hpp> //#include <boost/algorithm/string/classification.hpp> #include <vector> #include <iostream> #include <memory> #include <assert.h> #include <cstring> #include <cstdlib> #include "zorbatypes/collation_manager.h" namespace zorba { #if !defined WIN32 && !defined WCE #define strtok_s strtok_r #endif XQPCollator::XQPCollator(void* aCollator) : theCollator((Collator*)aCollator) {} XQPCollator::~XQPCollator() { delete (Collator*)theCollator; } XQPCollator* CollationFactory::createCollator(const std::string& aCollationURI) { if (aCollationURI == "http://www.w3.org/2005/xpath-functions/collation/codepoint") { #ifndef ZORBA_NO_UNICODE Collator* lCollator; UErrorCode lError = U_ZERO_ERROR; lCollator = Collator::createInstance(Locale("root"), lError); assert(lError == U_ZERO_ERROR); lCollator->setStrength(Collator::TERTIARY); lCollator->setAttribute(UCOL_CASE_FIRST, UCOL_UPPER_FIRST, lError); assert( lError == U_ZERO_ERROR ); return new XQPCollator(lCollator); #else Collator *coll = new Collator; return new XQPCollator(coll); #endif } size_t lStartURI = aCollationURI.find("http://www.flworfound.org/collations/"); if ( lStartURI == std::string::npos ) return 0; // e.g. PRIMARY/en/US std::string lCollationIdentifier = aCollationURI.substr(37, aCollationURI.size() - 37); // the vector will contain the strength, language, and optional country code // std::vector<std::string> lSplitVec;; // boost::split( lSplitVec, lCollationIdentifier, boost::algorithm::is_any_of("/") ); char *strtok_context = NULL; char *collstrdup = ::strdup(lCollationIdentifier.c_str()); char *tok1, *tok2, *tok3; tok1 = strtok_s(collstrdup, "/", &strtok_context); if(!tok1) { ::free(collstrdup); return 0; } tok2 = strtok_s(NULL, "/", &strtok_context); if ( !tok2) { ::free(collstrdup); return 0; } tok3 = strtok_s(NULL, "/", &strtok_context); Collator* lCollator; #ifndef ZORBA_NO_UNICODE UErrorCode lError = U_ZERO_ERROR; if ( tok3 == NULL ) { lCollator = Collator::createInstance(Locale(tok2), lError); } else { lCollator = Collator::createInstance(Locale(tok2, tok3), lError); } if( U_FAILURE(lError) ) { ::free(collstrdup); return 0; } #else lCollator = new Collator; #endif if (!strcmp(tok1, "PRIMARY")) { #ifndef ZORBA_NO_UNICODE lCollator->setStrength(Collator::PRIMARY); #endif } else if (!strcmp(tok1, "SECONDARY")) { #ifndef ZORBA_NO_UNICODE lCollator->setStrength(Collator::SECONDARY); #endif } else if (!strcmp(tok1, "TERTIARY")) { #ifndef ZORBA_NO_UNICODE lCollator->setStrength(Collator::TERTIARY); #endif } else if (!strcmp(tok1, "QUATERNARY")) { #ifndef ZORBA_NO_UNICODE lCollator->setStrength(Collator::QUATERNARY); #endif } else if (!strcmp(tok1, "IDENTICAL")) { #ifndef ZORBA_NO_UNICODE lCollator->setStrength(Collator::IDENTICAL); #endif } else { ::free(collstrdup); return 0; } ::free(collstrdup); return new XQPCollator(lCollator); } XQPCollator* CollationFactory::createCollator() { Collator* lCollator; #ifndef ZORBA_NO_UNICODE UErrorCode lError = U_ZERO_ERROR; lCollator = Collator::createInstance(Locale("en", "US"), lError); if( U_FAILURE(lError) ) { assert(false); } lCollator->setStrength(Collator::IDENTICAL); #else lCollator = new Collator; #endif return new XQPCollator(lCollator); } CollationFactory::CollationFactory() : theRootCollator(0) { theRootCollator = createCollator(); } CollationFactory::~CollationFactory() { if ( theRootCollator ) delete theRootCollator; } } /* namespace xqp */ <commit_msg>double memory free in CollationFactory::createCollator fixed<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 "common/common.h" #ifndef ZORBA_NO_UNICODE #include "zorbatypes/libicu.h" #endif #include <vector> #include <iostream> #include <memory> #include <assert.h> #include <cstring> #include <cstdlib> #include "zorbatypes/collation_manager.h" namespace zorba { /** * Method splits the passed string into tokes. Delimiters are all characters * passed in the variable delims. */ std::vector<std::string> tokenize_str(const std::string& str, const std::string& delims) { // Skip delims at beginning, find start of first token std::string::size_type lastPos = str.find_first_not_of(delims, 0); // Find next delimiter @ end of token std::string::size_type pos = str.find_first_of(delims, lastPos); // output vector std::vector<std::string> tokens; while (std::string::npos != pos || std::string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delims. Note the "not_of". this is beginning of token lastPos = str.find_first_not_of(delims, pos); // Find next delimiter at end of token. pos = str.find_first_of(delims, lastPos); } return tokens; } XQPCollator::XQPCollator(void* aCollator) : theCollator((Collator*)aCollator) {} XQPCollator::~XQPCollator() { delete (Collator*)theCollator; } XQPCollator* CollationFactory::createCollator(const std::string& aCollationURI) { if (aCollationURI == "http://www.w3.org/2005/xpath-functions/collation/codepoint") { #ifndef ZORBA_NO_UNICODE Collator* lCollator; UErrorCode lError = U_ZERO_ERROR; lCollator = Collator::createInstance(Locale("root"), lError); assert(lError == U_ZERO_ERROR); lCollator->setStrength(Collator::TERTIARY); lCollator->setAttribute(UCOL_CASE_FIRST, UCOL_UPPER_FIRST, lError); assert( lError == U_ZERO_ERROR ); return new XQPCollator(lCollator); #else Collator *coll = new Collator; return new XQPCollator(coll); #endif } size_t lStartURI = aCollationURI.find("http://www.flworfound.org/collations/"); if ( lStartURI == std::string::npos ) return 0; // e.g. PRIMARY/en/US std::string lCollationIdentifier = aCollationURI.substr(37, aCollationURI.size() - 37); std::vector<std::string> lTokens = tokenize_str(lCollationIdentifier, "/"); if(lTokens.size() < 2) { return 0; } Collator* lCollator; #ifndef ZORBA_NO_UNICODE UErrorCode lError = U_ZERO_ERROR; if (lTokens.size() == 2) { lCollator = Collator::createInstance(Locale(lTokens[1].c_str()), lError); } else { lCollator = Collator::createInstance(Locale(lTokens[1].c_str(), lTokens[2].c_str()), lError); } if( U_FAILURE(lError) ) { return 0; } #else lCollator = new Collator; #endif if (lTokens[0].compare("PRIMARY") == 0) { #ifndef ZORBA_NO_UNICODE lCollator->setStrength(Collator::PRIMARY); #endif } else if (lTokens[0].compare("SECONDARY") == 0) { #ifndef ZORBA_NO_UNICODE lCollator->setStrength(Collator::SECONDARY); #endif } else if (lTokens[0].compare("TERTIARY") == 0) { #ifndef ZORBA_NO_UNICODE lCollator->setStrength(Collator::TERTIARY); #endif } else if (lTokens[0].compare("QUATERNARY") == 0) { #ifndef ZORBA_NO_UNICODE lCollator->setStrength(Collator::QUATERNARY); #endif } else if (lTokens[0].compare("IDENTICAL") == 0) { #ifndef ZORBA_NO_UNICODE lCollator->setStrength(Collator::IDENTICAL); #endif } else { return 0; } return new XQPCollator(lCollator); } XQPCollator* CollationFactory::createCollator() { Collator* lCollator; #ifndef ZORBA_NO_UNICODE UErrorCode lError = U_ZERO_ERROR; lCollator = Collator::createInstance(Locale("en", "US"), lError); if( U_FAILURE(lError) ) { assert(false); } lCollator->setStrength(Collator::IDENTICAL); #else lCollator = new Collator; #endif return new XQPCollator(lCollator); } CollationFactory::CollationFactory() : theRootCollator(0) { theRootCollator = createCollator(); } CollationFactory::~CollationFactory() { if ( theRootCollator ) delete theRootCollator; } } /* namespace xqp */ <|endoftext|>
<commit_before>// // Created by Miguel Rentes on 19/01/2017. // #include "STL.h" int main(void) { unsigned int number_elements; unsigned int number_queries; unsigned int element; bool present = false; unsigned int index; cin >> number_elements; vector <unsigned int> elements; for (int i = 0; i < number_elements; i++) { if (cin >> element) { elements.push_back(element); } } cin >> number_queries; std::vector<unsigned int>::iterator low; for (int i = 0; i < number_queries; i++) { cin >> element; for (int j = 0; j < number_elements; j++) { if (elements.at(j) == element) { present = true; index = j; break; } else { low = lower_bound(elements.begin(), elements.end(), element); } } if (present) { cout << "Yes " << index+1 << endl; } else { cout << "No " << low - elements.begin()+1 << endl; } present = false; } return EXIT_SUCCESS; }<commit_msg>Starts solution for the Lower Bound-STL challenge.<commit_after>// // Created by Miguel Rentes on 19/01/2017. // #include "STL.h" int main(void) { unsigned int number_elements; unsigned int number_queries; unsigned int element; bool present = false; unsigned int index; cin >> number_elements; vector <unsigned int> elements; for (int i = 0; i < number_elements; i++) { if (cin >> element) { elements.push_back(element); } } cin >> number_queries; std::vector<unsigned int>::iterator low; for (int i = 0; i < number_queries; i++) { cin >> element; for (int j = 0; j < number_elements && !present; j++) { if (elements.at(j) == element) { present = true; index = j; } else { low = lower_bound(elements.begin(), elements.end(), element); } } if (present) { cout << "Yes " << index+1 << endl; } else { cout << "No " << low - elements.begin()+1 << endl; } present = false; } return EXIT_SUCCESS; }<|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <FontTable.hxx> #include <doctok/resourceids.hxx> #include <ooxml/resourceids.hxx> #include <vector> #include <osl/file.hxx> #include <stdio.h> #include <rtl/tencinfo.h> #include <vcl/embeddedfontshelper.hxx> #include <unotools/fontdefs.hxx> #include <com/sun/star/awt/FontPitch.hpp> #include "dmapperLoggers.hxx" namespace writerfilter { namespace dmapper { struct FontTable_Impl { std::vector< FontEntry::Pointer_t > aFontEntries; FontEntry::Pointer_t pCurrentEntry; FontTable_Impl() {} }; FontTable::FontTable() : LoggedProperties(dmapper_logger, "FontTable") , LoggedTable(dmapper_logger, "FontTable") , LoggedStream(dmapper_logger, "FontTable") , m_pImpl( new FontTable_Impl ) { } FontTable::~FontTable() { delete m_pImpl; } void FontTable::lcl_attribute(Id Name, Value & val) { OSL_ENSURE( m_pImpl->pCurrentEntry, "current entry has to be set here"); if(!m_pImpl->pCurrentEntry) return ; int nIntValue = val.getInt(); OUString sValue = val.getString(); switch(Name) { case NS_ooxml::LN_CT_Pitch_val: if (nIntValue == NS_ooxml::LN_Value_ST_Pitch_fixed) m_pImpl->pCurrentEntry->nPitchRequest = awt::FontPitch::FIXED; else if (nIntValue == NS_ooxml::LN_Value_ST_Pitch_variable) m_pImpl->pCurrentEntry->nPitchRequest = awt::FontPitch::VARIABLE; else if (nIntValue == NS_ooxml::LN_Value_ST_Pitch_default) m_pImpl->pCurrentEntry->nPitchRequest = awt::FontPitch::DONTKNOW; else SAL_WARN("writerfilter", "FontTable::lcl_attribute: unhandled NS_ooxml::CT_Pitch_val: " << nIntValue); break; case NS_ooxml::LN_CT_Font_name: m_pImpl->pCurrentEntry->sFontName = sValue; break; case NS_ooxml::LN_CT_Charset_val: // w:characterSet has higher priority, set only if that one is not set if( m_pImpl->pCurrentEntry->nTextEncoding == RTL_TEXTENCODING_DONTKNOW ) { m_pImpl->pCurrentEntry->nTextEncoding = rtl_getTextEncodingFromWindowsCharset( nIntValue ); if( IsStarSymbol( m_pImpl->pCurrentEntry->sFontName )) m_pImpl->pCurrentEntry->nTextEncoding = RTL_TEXTENCODING_SYMBOL; } break; case NS_ooxml::LN_CT_Charset_characterSet: { OString tmp; sValue.convertToString( &tmp, RTL_TEXTENCODING_ASCII_US, OUSTRING_TO_OSTRING_CVTFLAGS ); m_pImpl->pCurrentEntry->nTextEncoding = rtl_getTextEncodingFromMimeCharset( tmp.getStr() ); // Older LO versions used to write incorrect character set for OpenSymbol, fix. if( IsStarSymbol( m_pImpl->pCurrentEntry->sFontName )) m_pImpl->pCurrentEntry->nTextEncoding = RTL_TEXTENCODING_SYMBOL; break; } default: { //----> debug int nVal = val.getInt(); ++nVal; //<---- debug } } } void FontTable::lcl_sprm(Sprm& rSprm) { OSL_ENSURE( m_pImpl->pCurrentEntry, "current entry has to be set here"); if(!m_pImpl->pCurrentEntry) return ; sal_uInt32 nSprmId = rSprm.getId(); Value::Pointer_t pValue = rSprm.getValue(); sal_Int32 nIntValue = pValue->getInt(); (void)nIntValue; switch(nSprmId) { case NS_ooxml::LN_CT_Font_charset: case NS_ooxml::LN_CT_Font_pitch: resolveSprm( rSprm ); break; case NS_ooxml::LN_CT_Font_embedRegular: case NS_ooxml::LN_CT_Font_embedBold: case NS_ooxml::LN_CT_Font_embedItalic: case NS_ooxml::LN_CT_Font_embedBoldItalic: { writerfilter::Reference< Properties >::Pointer_t pProperties = rSprm.getProps(); if( pProperties.get( )) { EmbeddedFontHandler handler( m_pImpl->pCurrentEntry->sFontName, nSprmId == NS_ooxml::LN_CT_Font_embedRegular ? "" : nSprmId == NS_ooxml::LN_CT_Font_embedBold ? "b" : nSprmId == NS_ooxml::LN_CT_Font_embedItalic ? "i" : nSprmId == NS_ooxml::LN_CT_Font_embedBoldItalic ? "bi" : "?" ); pProperties->resolve( handler ); } break; } case NS_ooxml::LN_CT_Font_panose1: break; case NS_ooxml::LN_CT_Font_family: break; case NS_ooxml::LN_CT_Font_sig: break; default: SAL_WARN("writerfilter", "FontTable::lcl_sprm: unhandled token: " << nSprmId); break; } } void FontTable::resolveSprm(Sprm & r_Sprm) { writerfilter::Reference<Properties>::Pointer_t pProperties = r_Sprm.getProps(); if( pProperties.get()) pProperties->resolve(*this); } void FontTable::lcl_entry(int /*pos*/, writerfilter::Reference<Properties>::Pointer_t ref) { //create a new font entry OSL_ENSURE( !m_pImpl->pCurrentEntry, "current entry has to be NULL here"); m_pImpl->pCurrentEntry.reset(new FontEntry); ref->resolve(*this); //append it to the table m_pImpl->aFontEntries.push_back( m_pImpl->pCurrentEntry ); m_pImpl->pCurrentEntry.reset(); } void FontTable::lcl_startSectionGroup() { } void FontTable::lcl_endSectionGroup() { } void FontTable::lcl_startParagraphGroup() { } void FontTable::lcl_endParagraphGroup() { } void FontTable::lcl_startCharacterGroup() { } void FontTable::lcl_endCharacterGroup() { } void FontTable::lcl_text(const sal_uInt8*, size_t ) { } void FontTable::lcl_utext(const sal_uInt8* , size_t) { } void FontTable::lcl_props(writerfilter::Reference<Properties>::Pointer_t) { } void FontTable::lcl_table(Id, writerfilter::Reference<Table>::Pointer_t) { } void FontTable::lcl_substream(Id, ::writerfilter::Reference<Stream>::Pointer_t) { } void FontTable::lcl_info(const string& ) { } void FontTable::lcl_startShape( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > ) { } void FontTable::lcl_endShape( ) { } const FontEntry::Pointer_t FontTable::getFontEntry(sal_uInt32 nIndex) { return (m_pImpl->aFontEntries.size() > nIndex) ? m_pImpl->aFontEntries[nIndex] : FontEntry::Pointer_t(); } sal_uInt32 FontTable::size() { return m_pImpl->aFontEntries.size(); } EmbeddedFontHandler::EmbeddedFontHandler( const OUString& _fontName, const char* _style ) : LoggedProperties(dmapper_logger, "EmbeddedFontHandler") , fontName( _fontName ) , style( _style ) { } EmbeddedFontHandler::~EmbeddedFontHandler() { if( !inputStream.is()) return; std::vector< unsigned char > key( 32 ); if( !fontKey.isEmpty()) { // key for unobfuscating // 1 3 5 7 10 2 5 7 20 2 5 7 9 1 3 5 // {62E79491-959F-41E9-B76B-6B32631DEA5C} static const int pos[ 16 ] = { 35, 33, 31, 29, 27, 25, 22, 20, 17, 15, 12, 10, 7, 5, 3, 1 }; for( int i = 0; i < 16; ++i ) { int v1 = fontKey[ pos[ i ]]; int v2 = fontKey[ pos[ i ] + 1 ]; assert(( v1 >= '0' && v1 <= '9' ) || ( v1 >= 'A' && v1 <= 'F' )); assert(( v2 >= '0' && v2 <= '9' ) || ( v2 >= 'A' && v2 <= 'F' )); int val = ( v1 - ( v1 <= '9' ? '0' : 'A' - 10 )) * 16 + v2 - ( v2 <= '9' ? '0' : 'A' - 10 ); key[ i ] = val; key[ i + 16 ] = val; } } EmbeddedFontsHelper::addEmbeddedFont( inputStream, fontName, style, key ); inputStream->closeInput(); } void EmbeddedFontHandler::lcl_attribute( Id name, Value& val ) { OUString sValue = val.getString(); switch( name ) { case NS_ooxml::LN_CT_FontRel_fontKey: fontKey = sValue; break; case NS_ooxml::LN_CT_Rel_id: id = sValue; break; case NS_ooxml::LN_CT_FontRel_subsetted: break; // TODO? Let's just ignore this for now and hope // it doesn't break anything. case NS_ooxml::LN_inputstream: // the actual font data as stream val.getAny() >>= inputStream; break; default: break; } } void EmbeddedFontHandler::lcl_sprm( Sprm& ) { } }//namespace dmapper }//namespace writerfilter /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>WaE: comparison between signed and unsigned integer expressions<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <FontTable.hxx> #include <doctok/resourceids.hxx> #include <ooxml/resourceids.hxx> #include <vector> #include <osl/file.hxx> #include <stdio.h> #include <rtl/tencinfo.h> #include <vcl/embeddedfontshelper.hxx> #include <unotools/fontdefs.hxx> #include <com/sun/star/awt/FontPitch.hpp> #include "dmapperLoggers.hxx" namespace writerfilter { namespace dmapper { struct FontTable_Impl { std::vector< FontEntry::Pointer_t > aFontEntries; FontEntry::Pointer_t pCurrentEntry; FontTable_Impl() {} }; FontTable::FontTable() : LoggedProperties(dmapper_logger, "FontTable") , LoggedTable(dmapper_logger, "FontTable") , LoggedStream(dmapper_logger, "FontTable") , m_pImpl( new FontTable_Impl ) { } FontTable::~FontTable() { delete m_pImpl; } void FontTable::lcl_attribute(Id Name, Value & val) { OSL_ENSURE( m_pImpl->pCurrentEntry, "current entry has to be set here"); if(!m_pImpl->pCurrentEntry) return ; int nIntValue = val.getInt(); OUString sValue = val.getString(); switch(Name) { case NS_ooxml::LN_CT_Pitch_val: if (static_cast<Id>(nIntValue) == NS_ooxml::LN_Value_ST_Pitch_fixed) m_pImpl->pCurrentEntry->nPitchRequest = awt::FontPitch::FIXED; else if (static_cast<Id>(nIntValue) == NS_ooxml::LN_Value_ST_Pitch_variable) m_pImpl->pCurrentEntry->nPitchRequest = awt::FontPitch::VARIABLE; else if (static_cast<Id>(nIntValue) == NS_ooxml::LN_Value_ST_Pitch_default) m_pImpl->pCurrentEntry->nPitchRequest = awt::FontPitch::DONTKNOW; else SAL_WARN("writerfilter", "FontTable::lcl_attribute: unhandled NS_ooxml::CT_Pitch_val: " << nIntValue); break; case NS_ooxml::LN_CT_Font_name: m_pImpl->pCurrentEntry->sFontName = sValue; break; case NS_ooxml::LN_CT_Charset_val: // w:characterSet has higher priority, set only if that one is not set if( m_pImpl->pCurrentEntry->nTextEncoding == RTL_TEXTENCODING_DONTKNOW ) { m_pImpl->pCurrentEntry->nTextEncoding = rtl_getTextEncodingFromWindowsCharset( nIntValue ); if( IsStarSymbol( m_pImpl->pCurrentEntry->sFontName )) m_pImpl->pCurrentEntry->nTextEncoding = RTL_TEXTENCODING_SYMBOL; } break; case NS_ooxml::LN_CT_Charset_characterSet: { OString tmp; sValue.convertToString( &tmp, RTL_TEXTENCODING_ASCII_US, OUSTRING_TO_OSTRING_CVTFLAGS ); m_pImpl->pCurrentEntry->nTextEncoding = rtl_getTextEncodingFromMimeCharset( tmp.getStr() ); // Older LO versions used to write incorrect character set for OpenSymbol, fix. if( IsStarSymbol( m_pImpl->pCurrentEntry->sFontName )) m_pImpl->pCurrentEntry->nTextEncoding = RTL_TEXTENCODING_SYMBOL; break; } default: { //----> debug int nVal = val.getInt(); ++nVal; //<---- debug } } } void FontTable::lcl_sprm(Sprm& rSprm) { OSL_ENSURE( m_pImpl->pCurrentEntry, "current entry has to be set here"); if(!m_pImpl->pCurrentEntry) return ; sal_uInt32 nSprmId = rSprm.getId(); Value::Pointer_t pValue = rSprm.getValue(); sal_Int32 nIntValue = pValue->getInt(); (void)nIntValue; switch(nSprmId) { case NS_ooxml::LN_CT_Font_charset: case NS_ooxml::LN_CT_Font_pitch: resolveSprm( rSprm ); break; case NS_ooxml::LN_CT_Font_embedRegular: case NS_ooxml::LN_CT_Font_embedBold: case NS_ooxml::LN_CT_Font_embedItalic: case NS_ooxml::LN_CT_Font_embedBoldItalic: { writerfilter::Reference< Properties >::Pointer_t pProperties = rSprm.getProps(); if( pProperties.get( )) { EmbeddedFontHandler handler( m_pImpl->pCurrentEntry->sFontName, nSprmId == NS_ooxml::LN_CT_Font_embedRegular ? "" : nSprmId == NS_ooxml::LN_CT_Font_embedBold ? "b" : nSprmId == NS_ooxml::LN_CT_Font_embedItalic ? "i" : nSprmId == NS_ooxml::LN_CT_Font_embedBoldItalic ? "bi" : "?" ); pProperties->resolve( handler ); } break; } case NS_ooxml::LN_CT_Font_panose1: break; case NS_ooxml::LN_CT_Font_family: break; case NS_ooxml::LN_CT_Font_sig: break; default: SAL_WARN("writerfilter", "FontTable::lcl_sprm: unhandled token: " << nSprmId); break; } } void FontTable::resolveSprm(Sprm & r_Sprm) { writerfilter::Reference<Properties>::Pointer_t pProperties = r_Sprm.getProps(); if( pProperties.get()) pProperties->resolve(*this); } void FontTable::lcl_entry(int /*pos*/, writerfilter::Reference<Properties>::Pointer_t ref) { //create a new font entry OSL_ENSURE( !m_pImpl->pCurrentEntry, "current entry has to be NULL here"); m_pImpl->pCurrentEntry.reset(new FontEntry); ref->resolve(*this); //append it to the table m_pImpl->aFontEntries.push_back( m_pImpl->pCurrentEntry ); m_pImpl->pCurrentEntry.reset(); } void FontTable::lcl_startSectionGroup() { } void FontTable::lcl_endSectionGroup() { } void FontTable::lcl_startParagraphGroup() { } void FontTable::lcl_endParagraphGroup() { } void FontTable::lcl_startCharacterGroup() { } void FontTable::lcl_endCharacterGroup() { } void FontTable::lcl_text(const sal_uInt8*, size_t ) { } void FontTable::lcl_utext(const sal_uInt8* , size_t) { } void FontTable::lcl_props(writerfilter::Reference<Properties>::Pointer_t) { } void FontTable::lcl_table(Id, writerfilter::Reference<Table>::Pointer_t) { } void FontTable::lcl_substream(Id, ::writerfilter::Reference<Stream>::Pointer_t) { } void FontTable::lcl_info(const string& ) { } void FontTable::lcl_startShape( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > ) { } void FontTable::lcl_endShape( ) { } const FontEntry::Pointer_t FontTable::getFontEntry(sal_uInt32 nIndex) { return (m_pImpl->aFontEntries.size() > nIndex) ? m_pImpl->aFontEntries[nIndex] : FontEntry::Pointer_t(); } sal_uInt32 FontTable::size() { return m_pImpl->aFontEntries.size(); } EmbeddedFontHandler::EmbeddedFontHandler( const OUString& _fontName, const char* _style ) : LoggedProperties(dmapper_logger, "EmbeddedFontHandler") , fontName( _fontName ) , style( _style ) { } EmbeddedFontHandler::~EmbeddedFontHandler() { if( !inputStream.is()) return; std::vector< unsigned char > key( 32 ); if( !fontKey.isEmpty()) { // key for unobfuscating // 1 3 5 7 10 2 5 7 20 2 5 7 9 1 3 5 // {62E79491-959F-41E9-B76B-6B32631DEA5C} static const int pos[ 16 ] = { 35, 33, 31, 29, 27, 25, 22, 20, 17, 15, 12, 10, 7, 5, 3, 1 }; for( int i = 0; i < 16; ++i ) { int v1 = fontKey[ pos[ i ]]; int v2 = fontKey[ pos[ i ] + 1 ]; assert(( v1 >= '0' && v1 <= '9' ) || ( v1 >= 'A' && v1 <= 'F' )); assert(( v2 >= '0' && v2 <= '9' ) || ( v2 >= 'A' && v2 <= 'F' )); int val = ( v1 - ( v1 <= '9' ? '0' : 'A' - 10 )) * 16 + v2 - ( v2 <= '9' ? '0' : 'A' - 10 ); key[ i ] = val; key[ i + 16 ] = val; } } EmbeddedFontsHelper::addEmbeddedFont( inputStream, fontName, style, key ); inputStream->closeInput(); } void EmbeddedFontHandler::lcl_attribute( Id name, Value& val ) { OUString sValue = val.getString(); switch( name ) { case NS_ooxml::LN_CT_FontRel_fontKey: fontKey = sValue; break; case NS_ooxml::LN_CT_Rel_id: id = sValue; break; case NS_ooxml::LN_CT_FontRel_subsetted: break; // TODO? Let's just ignore this for now and hope // it doesn't break anything. case NS_ooxml::LN_inputstream: // the actual font data as stream val.getAny() >>= inputStream; break; default: break; } } void EmbeddedFontHandler::lcl_sprm( Sprm& ) { } }//namespace dmapper }//namespace writerfilter /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// Copyright (c) 2009 libmv authors. // // 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 <cstdio> // TODO(keir): This code is plain unfinished! Doesn't even compile! #include "libmv/base/vector.h" #include "libmv/multiview/fundamental_kernel.h" #include "libmv/numeric/numeric.h" #include "libmv/numeric/poly.h" #include "libmv/logging/logging.h" namespace libmv { namespace fundamental { namespace kernel { void SevenPointSolver::Solve(const Mat &x1, const Mat &x2, vector<Mat3> *F) { assert(2 == x1.rows()); assert(7 == x1.cols()); assert(x1.rows() == x2.rows()); assert(x1.cols() == x2.cols()); // Set up the homogeneous system Af = 0 from the equations x'T*F*x = 0. MatX9 A(x1.cols(), 9); EncodeEpipolarEquation(x1, x2, &A); // Find the two F matrices in the nullspace of A. Vec9 f1, f2; Nullspace2(&A, &f1, &f2); Mat3 F1 = Map<RMat3>(f1.data()); Mat3 F2 = Map<RMat3>(f2.data()); // Then, use the condition det(F) = 0 to determine F. In other words, solve // det(F1 + a*F2) = 0 for a. double a = F1(0, 0), j = F2(0, 0), b = F1(0, 1), k = F2(0, 1), c = F1(0, 2), l = F2(0, 2), d = F1(1, 0), m = F2(1, 0), e = F1(1, 1), n = F2(1, 1), f = F1(1, 2), o = F2(1, 2), g = F1(2, 0), p = F2(2, 0), h = F1(2, 1), q = F2(2, 1), i = F1(2, 2), r = F2(2, 2); // Run fundamental_7point_coeffs.py to get the below coefficients. // The coefficients are in ascending powers of alpha, i.e. P[N]*x^N. double P[4] = { a*e*i + b*f*g + c*d*h - a*f*h - b*d*i - c*e*g, a*e*r + a*i*n + b*f*p + b*g*o + c*d*q + c*h*m + d*h*l + e*i*j + f*g*k - a*f*q - a*h*o - b*d*r - b*i*m - c*e*p - c*g*n - d*i*k - e*g*l - f*h*j, a*n*r + b*o*p + c*m*q + d*l*q + e*j*r + f*k*p + g*k*o + h*l*m + i*j*n - a*o*q - b*m*r - c*n*p - d*k*r - e*l*p - f*j*q - g*l*n - h*j*o - i*k*m, j*n*r + k*o*p + l*m*q - j*o*q - k*m*r - l*n*p, }; // Solve for the roots of P[3]*x^3 + P[2]*x^2 + P[1]*x + P[0] = 0. double roots[3]; int num_roots = SolveCubicPolynomial(P, roots); // Build the fundamental matrix for each solution. for (int kk = 0; kk < num_roots; ++kk) { F->push_back(F1 + roots[kk] * F2); } } //template<bool force_essential_constraint> void EightPointSolver::Solve(const Mat &x1, const Mat &x2, vector<Mat3> *Fs) { assert(2 == x1.rows()); assert(8 <= x1.cols()); assert(x1.rows() == x2.rows()); assert(x1.cols() == x2.cols()); MatX9 A(x1.cols(), 9); EncodeEpipolarEquation(x1, x2, &A); Vec9 f; Nullspace(&A, &f); Mat3 F = Map<RMat3>(f.data()); // Force the fundamental property if the A matrix has full rank. if (x1.cols() > 8) { Eigen::SVD<Mat3> USV(F); Vec3 d = USV.singularValues(); d[2] = 0.0; F = USV.matrixU() * d.asDiagonal() * USV.matrixV().transpose(); } Fs->push_back(F); } } // namespace kernel } // namespace fundamental } // namespace libmv <commit_msg>- Make SevenPointSolver::Solve be estimable from 7 to N correspondences. (Fix the assert test).<commit_after>// Copyright (c) 2009 libmv authors. // // 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 <cstdio> // TODO(keir): This code is plain unfinished! Doesn't even compile! #include "libmv/base/vector.h" #include "libmv/multiview/fundamental_kernel.h" #include "libmv/numeric/numeric.h" #include "libmv/numeric/poly.h" #include "libmv/logging/logging.h" namespace libmv { namespace fundamental { namespace kernel { void SevenPointSolver::Solve(const Mat &x1, const Mat &x2, vector<Mat3> *F) { assert(2 == x1.rows()); assert(7 <= x1.cols()); assert(x1.rows() == x2.rows()); assert(x1.cols() == x2.cols()); // Set up the homogeneous system Af = 0 from the equations x'T*F*x = 0. MatX9 A(x1.cols(), 9); EncodeEpipolarEquation(x1, x2, &A); // Find the two F matrices in the nullspace of A. Vec9 f1, f2; Nullspace2(&A, &f1, &f2); Mat3 F1 = Map<RMat3>(f1.data()); Mat3 F2 = Map<RMat3>(f2.data()); // Then, use the condition det(F) = 0 to determine F. In other words, solve // det(F1 + a*F2) = 0 for a. double a = F1(0, 0), j = F2(0, 0), b = F1(0, 1), k = F2(0, 1), c = F1(0, 2), l = F2(0, 2), d = F1(1, 0), m = F2(1, 0), e = F1(1, 1), n = F2(1, 1), f = F1(1, 2), o = F2(1, 2), g = F1(2, 0), p = F2(2, 0), h = F1(2, 1), q = F2(2, 1), i = F1(2, 2), r = F2(2, 2); // Run fundamental_7point_coeffs.py to get the below coefficients. // The coefficients are in ascending powers of alpha, i.e. P[N]*x^N. double P[4] = { a*e*i + b*f*g + c*d*h - a*f*h - b*d*i - c*e*g, a*e*r + a*i*n + b*f*p + b*g*o + c*d*q + c*h*m + d*h*l + e*i*j + f*g*k - a*f*q - a*h*o - b*d*r - b*i*m - c*e*p - c*g*n - d*i*k - e*g*l - f*h*j, a*n*r + b*o*p + c*m*q + d*l*q + e*j*r + f*k*p + g*k*o + h*l*m + i*j*n - a*o*q - b*m*r - c*n*p - d*k*r - e*l*p - f*j*q - g*l*n - h*j*o - i*k*m, j*n*r + k*o*p + l*m*q - j*o*q - k*m*r - l*n*p, }; // Solve for the roots of P[3]*x^3 + P[2]*x^2 + P[1]*x + P[0] = 0. double roots[3]; int num_roots = SolveCubicPolynomial(P, roots); // Build the fundamental matrix for each solution. for (int kk = 0; kk < num_roots; ++kk) { F->push_back(F1 + roots[kk] * F2); } } //template<bool force_essential_constraint> void EightPointSolver::Solve(const Mat &x1, const Mat &x2, vector<Mat3> *Fs) { assert(2 == x1.rows()); assert(8 <= x1.cols()); assert(x1.rows() == x2.rows()); assert(x1.cols() == x2.cols()); MatX9 A(x1.cols(), 9); EncodeEpipolarEquation(x1, x2, &A); Vec9 f; Nullspace(&A, &f); Mat3 F = Map<RMat3>(f.data()); // Force the fundamental property if the A matrix has full rank. if (x1.cols() > 8) { Eigen::SVD<Mat3> USV(F); Vec3 d = USV.singularValues(); d[2] = 0.0; F = USV.matrixU() * d.asDiagonal() * USV.matrixV().transpose(); } Fs->push_back(F); } } // namespace kernel } // namespace fundamental } // namespace libmv <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <com/sun/star/awt/Size.hpp> #include <com/sun/star/awt/XControlModel.hpp> #include <com/sun/star/drawing/XControlShape.hpp> #include <com/sun/star/text/VertOrientation.hpp> #include <comphelper/sequenceashashmap.hxx> #include <editeng/unoprnms.hxx> #include <vcl/outdev.hxx> #include <vcl/svapp.hxx> #include <unotools/datetime.hxx> #include <DomainMapper_Impl.hxx> #include <StyleSheetTable.hxx> #include <SdtHelper.hxx> namespace writerfilter { namespace dmapper { using namespace ::com::sun::star; /// w:sdt's w:dropDownList doesn't have width, so guess the size based on the longest string. awt::Size lcl_getOptimalWidth(StyleSheetTablePtr pStyleSheet, OUString& rDefault, std::vector<OUString>& rItems) { OUString aLongest = rDefault; sal_Int32 nHeight = 0; for (size_t i = 0; i < rItems.size(); ++i) if (rItems[i].getLength() > aLongest.getLength()) aLongest = rItems[i]; MapMode aMap(MAP_100TH_MM); OutputDevice* pOut = Application::GetDefaultDevice(); pOut->Push(PUSH_FONT | PUSH_MAPMODE); PropertyMapPtr pDefaultCharProps = pStyleSheet->GetDefaultCharProps(); Font aFont(pOut->GetFont()); PropertyMap::iterator aFontName = pDefaultCharProps->find(PROP_CHAR_FONT_NAME); if (aFontName != pDefaultCharProps->end()) aFont.SetName(aFontName->second.getValue().get<OUString>()); PropertyMap::iterator aHeight = pDefaultCharProps->find(PROP_CHAR_HEIGHT); if (aHeight != pDefaultCharProps->end()) { nHeight = aHeight->second.getValue().get<double>() * 35; // points -> mm100 aFont.SetSize(Size(0, nHeight)); } pOut->SetFont(aFont); pOut->SetMapMode(aMap); sal_Int32 nWidth = pOut->GetTextWidth(aLongest); pOut->Pop(); // Border: see PDFWriterImpl::drawFieldBorder(), border size is font height / 4, // so additional width / height needed is height / 2. sal_Int32 nBorder = nHeight / 2; // Width: space for the text + the square having the dropdown arrow. return awt::Size(nWidth + nBorder + nHeight, nHeight + nBorder); } SdtHelper::SdtHelper(DomainMapper_Impl& rDM_Impl) : m_rDM_Impl(rDM_Impl) , m_bHasElements(false) { } SdtHelper::~SdtHelper() { } void SdtHelper::createDropDownControl() { OUString aDefaultText = m_aSdtTexts.makeStringAndClear(); uno::Reference<awt::XControlModel> xControlModel(m_rDM_Impl.GetTextFactory()->createInstance("com.sun.star.form.component.ComboBox"), uno::UNO_QUERY); uno::Reference<beans::XPropertySet> xPropertySet(xControlModel, uno::UNO_QUERY); xPropertySet->setPropertyValue("DefaultText", uno::makeAny(aDefaultText)); xPropertySet->setPropertyValue("Dropdown", uno::makeAny(sal_True)); uno::Sequence<OUString> aItems(m_aDropDownItems.size()); for (size_t i = 0; i < m_aDropDownItems.size(); ++i) aItems[i] = m_aDropDownItems[i]; xPropertySet->setPropertyValue("StringItemList", uno::makeAny(aItems)); createControlShape(lcl_getOptimalWidth(m_rDM_Impl.GetStyleSheetTable(), aDefaultText, m_aDropDownItems), xControlModel); m_aDropDownItems.clear(); } void SdtHelper::createDateControl(OUString& rContentText, beans::PropertyValue aCharFormat) { uno::Reference<awt::XControlModel> xControlModel(m_rDM_Impl.GetTextFactory()->createInstance("com.sun.star.form.component.DateField"), uno::UNO_QUERY); uno::Reference<beans::XPropertySet> xPropertySet(xControlModel, uno::UNO_QUERY); xPropertySet->setPropertyValue("Dropdown", uno::makeAny(sal_True)); // See com/sun/star/awt/UnoControlDateFieldModel.idl, DateFormat; sadly there are no constants sal_Int16 nDateFormat = 0; OUString sDateFormat = m_sDateFormat.makeStringAndClear(); if (sDateFormat == "M/d/yyyy" || sDateFormat == "M.d.yyyy") // Approximate with MM.dd.yyy nDateFormat = 8; else // Set default format, so at least the date picker is created. SAL_WARN("writerfilter", "unhandled w:dateFormat value"); xPropertySet->setPropertyValue("DateFormat", uno::makeAny(nDateFormat)); util::Date aDate; util::DateTime aDateTime; if (utl::ISO8601parseDateTime(m_sDate.makeStringAndClear(), aDateTime)) { utl::extractDate(aDateTime, aDate); xPropertySet->setPropertyValue("Date", uno::makeAny(aDate)); } else xPropertySet->setPropertyValue("HelpText", uno::makeAny(rContentText)); // append date format to grab bag comphelper::SequenceAsHashMap aGrabBag; aGrabBag["OriginalDate"] <<= aDate; aGrabBag["OriginalContent"] <<= rContentText; aGrabBag["DateFormat"] <<= sDateFormat; aGrabBag["Locale"] <<= m_sLocale.makeStringAndClear(); aGrabBag["CharFormat"] <<= aCharFormat.Value; std::vector<OUString> aItems; createControlShape(lcl_getOptimalWidth(m_rDM_Impl.GetStyleSheetTable(), rContentText, aItems), xControlModel, aGrabBag.getAsConstPropertyValueList()); } void SdtHelper::createControlShape(awt::Size aSize, uno::Reference<awt::XControlModel> xControlModel) { createControlShape(aSize, xControlModel, uno::Sequence<beans::PropertyValue>()); } void SdtHelper::createControlShape(awt::Size aSize, uno::Reference<awt::XControlModel> xControlModel, const uno::Sequence<beans::PropertyValue>& rGrabBag) { uno::Reference<drawing::XControlShape> xControlShape(m_rDM_Impl.GetTextFactory()->createInstance("com.sun.star.drawing.ControlShape"), uno::UNO_QUERY); xControlShape->setSize(aSize); xControlShape->setControl(xControlModel); uno::Reference<beans::XPropertySet> xPropertySet(xControlShape, uno::UNO_QUERY); xPropertySet->setPropertyValue("VertOrient", uno::makeAny(text::VertOrientation::CENTER)); if (rGrabBag.hasElements()) xPropertySet->setPropertyValue(UNO_NAME_MISC_OBJ_INTEROPGRABBAG, uno::makeAny(rGrabBag)); uno::Reference<text::XTextContent> xTextContent(xControlShape, uno::UNO_QUERY); m_rDM_Impl.appendTextContent(xTextContent, uno::Sequence< beans::PropertyValue >()); m_bHasElements = true; } void SdtHelper::appendToInteropGrabBag(com::sun::star::beans::PropertyValue rValue) { sal_Int32 nLength = m_aGrabBag.getLength(); m_aGrabBag.realloc(nLength + 1); m_aGrabBag[nLength] = rValue; } com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue> SdtHelper::getInteropGrabBagAndClear() { com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue> aRet = m_aGrabBag; m_aGrabBag.realloc(0); return aRet; } bool SdtHelper::isInteropGrabBagEmpty() { return m_aGrabBag.getLength() == 0; } sal_Int32 SdtHelper::getInteropGrabBagSize() { return m_aGrabBag.getLength(); } bool SdtHelper::containedInInteropGrabBag(const OUString& rValueName) { for (sal_Int32 i=0; i < m_aGrabBag.getLength(); ++i) if (m_aGrabBag[i].Name == rValueName) return true; return false; } } // namespace dmapper } // namespace writerfilter /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>DOCX import: handle <w:alias> for the date SDT<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <com/sun/star/awt/Size.hpp> #include <com/sun/star/awt/XControlModel.hpp> #include <com/sun/star/drawing/XControlShape.hpp> #include <com/sun/star/text/VertOrientation.hpp> #include <comphelper/sequenceashashmap.hxx> #include <editeng/unoprnms.hxx> #include <vcl/outdev.hxx> #include <vcl/svapp.hxx> #include <unotools/datetime.hxx> #include <DomainMapper_Impl.hxx> #include <StyleSheetTable.hxx> #include <SdtHelper.hxx> namespace writerfilter { namespace dmapper { using namespace ::com::sun::star; /// w:sdt's w:dropDownList doesn't have width, so guess the size based on the longest string. awt::Size lcl_getOptimalWidth(StyleSheetTablePtr pStyleSheet, OUString& rDefault, std::vector<OUString>& rItems) { OUString aLongest = rDefault; sal_Int32 nHeight = 0; for (size_t i = 0; i < rItems.size(); ++i) if (rItems[i].getLength() > aLongest.getLength()) aLongest = rItems[i]; MapMode aMap(MAP_100TH_MM); OutputDevice* pOut = Application::GetDefaultDevice(); pOut->Push(PUSH_FONT | PUSH_MAPMODE); PropertyMapPtr pDefaultCharProps = pStyleSheet->GetDefaultCharProps(); Font aFont(pOut->GetFont()); PropertyMap::iterator aFontName = pDefaultCharProps->find(PROP_CHAR_FONT_NAME); if (aFontName != pDefaultCharProps->end()) aFont.SetName(aFontName->second.getValue().get<OUString>()); PropertyMap::iterator aHeight = pDefaultCharProps->find(PROP_CHAR_HEIGHT); if (aHeight != pDefaultCharProps->end()) { nHeight = aHeight->second.getValue().get<double>() * 35; // points -> mm100 aFont.SetSize(Size(0, nHeight)); } pOut->SetFont(aFont); pOut->SetMapMode(aMap); sal_Int32 nWidth = pOut->GetTextWidth(aLongest); pOut->Pop(); // Border: see PDFWriterImpl::drawFieldBorder(), border size is font height / 4, // so additional width / height needed is height / 2. sal_Int32 nBorder = nHeight / 2; // Width: space for the text + the square having the dropdown arrow. return awt::Size(nWidth + nBorder + nHeight, nHeight + nBorder); } SdtHelper::SdtHelper(DomainMapper_Impl& rDM_Impl) : m_rDM_Impl(rDM_Impl) , m_bHasElements(false) { } SdtHelper::~SdtHelper() { } void SdtHelper::createDropDownControl() { OUString aDefaultText = m_aSdtTexts.makeStringAndClear(); uno::Reference<awt::XControlModel> xControlModel(m_rDM_Impl.GetTextFactory()->createInstance("com.sun.star.form.component.ComboBox"), uno::UNO_QUERY); uno::Reference<beans::XPropertySet> xPropertySet(xControlModel, uno::UNO_QUERY); xPropertySet->setPropertyValue("DefaultText", uno::makeAny(aDefaultText)); xPropertySet->setPropertyValue("Dropdown", uno::makeAny(sal_True)); uno::Sequence<OUString> aItems(m_aDropDownItems.size()); for (size_t i = 0; i < m_aDropDownItems.size(); ++i) aItems[i] = m_aDropDownItems[i]; xPropertySet->setPropertyValue("StringItemList", uno::makeAny(aItems)); createControlShape(lcl_getOptimalWidth(m_rDM_Impl.GetStyleSheetTable(), aDefaultText, m_aDropDownItems), xControlModel); m_aDropDownItems.clear(); } void SdtHelper::createDateControl(OUString& rContentText, beans::PropertyValue aCharFormat) { uno::Reference<awt::XControlModel> xControlModel(m_rDM_Impl.GetTextFactory()->createInstance("com.sun.star.form.component.DateField"), uno::UNO_QUERY); uno::Reference<beans::XPropertySet> xPropertySet(xControlModel, uno::UNO_QUERY); xPropertySet->setPropertyValue("Dropdown", uno::makeAny(sal_True)); // See com/sun/star/awt/UnoControlDateFieldModel.idl, DateFormat; sadly there are no constants sal_Int16 nDateFormat = 0; OUString sDateFormat = m_sDateFormat.makeStringAndClear(); if (sDateFormat == "M/d/yyyy" || sDateFormat == "M.d.yyyy") // Approximate with MM.dd.yyy nDateFormat = 8; else // Set default format, so at least the date picker is created. SAL_WARN("writerfilter", "unhandled w:dateFormat value"); xPropertySet->setPropertyValue("DateFormat", uno::makeAny(nDateFormat)); util::Date aDate; util::DateTime aDateTime; if (utl::ISO8601parseDateTime(m_sDate.makeStringAndClear(), aDateTime)) { utl::extractDate(aDateTime, aDate); xPropertySet->setPropertyValue("Date", uno::makeAny(aDate)); } else xPropertySet->setPropertyValue("HelpText", uno::makeAny(rContentText)); // append date format to grab bag comphelper::SequenceAsHashMap aGrabBag; aGrabBag["OriginalDate"] <<= aDate; aGrabBag["OriginalContent"] <<= rContentText; aGrabBag["DateFormat"] <<= sDateFormat; aGrabBag["Locale"] <<= m_sLocale.makeStringAndClear(); aGrabBag["CharFormat"] <<= aCharFormat.Value; // merge in properties like ooxml:CT_SdtPr_alias and friends. aGrabBag.update(comphelper::SequenceAsHashMap(m_aGrabBag)); std::vector<OUString> aItems; createControlShape(lcl_getOptimalWidth(m_rDM_Impl.GetStyleSheetTable(), rContentText, aItems), xControlModel, aGrabBag.getAsConstPropertyValueList()); } void SdtHelper::createControlShape(awt::Size aSize, uno::Reference<awt::XControlModel> xControlModel) { createControlShape(aSize, xControlModel, uno::Sequence<beans::PropertyValue>()); } void SdtHelper::createControlShape(awt::Size aSize, uno::Reference<awt::XControlModel> xControlModel, const uno::Sequence<beans::PropertyValue>& rGrabBag) { uno::Reference<drawing::XControlShape> xControlShape(m_rDM_Impl.GetTextFactory()->createInstance("com.sun.star.drawing.ControlShape"), uno::UNO_QUERY); xControlShape->setSize(aSize); xControlShape->setControl(xControlModel); uno::Reference<beans::XPropertySet> xPropertySet(xControlShape, uno::UNO_QUERY); xPropertySet->setPropertyValue("VertOrient", uno::makeAny(text::VertOrientation::CENTER)); if (rGrabBag.hasElements()) xPropertySet->setPropertyValue(UNO_NAME_MISC_OBJ_INTEROPGRABBAG, uno::makeAny(rGrabBag)); uno::Reference<text::XTextContent> xTextContent(xControlShape, uno::UNO_QUERY); m_rDM_Impl.appendTextContent(xTextContent, uno::Sequence< beans::PropertyValue >()); m_bHasElements = true; } void SdtHelper::appendToInteropGrabBag(com::sun::star::beans::PropertyValue rValue) { sal_Int32 nLength = m_aGrabBag.getLength(); m_aGrabBag.realloc(nLength + 1); m_aGrabBag[nLength] = rValue; } com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue> SdtHelper::getInteropGrabBagAndClear() { com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue> aRet = m_aGrabBag; m_aGrabBag.realloc(0); return aRet; } bool SdtHelper::isInteropGrabBagEmpty() { return m_aGrabBag.getLength() == 0; } sal_Int32 SdtHelper::getInteropGrabBagSize() { return m_aGrabBag.getLength(); } bool SdtHelper::containedInInteropGrabBag(const OUString& rValueName) { for (sal_Int32 i=0; i < m_aGrabBag.getLength(); ++i) if (m_aGrabBag[i].Name == rValueName) return true; return false; } } // namespace dmapper } // namespace writerfilter /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// This file is part of eigen2mat, a simple C++ library to use // Eigen with MATLAB's MEX files // // Copyright (C) 2013 Nguyen Damien <damien.nguyen@a3.epfl.ch> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef E2M_CONVERSION_HPP_INCLUDED #define E2M_CONVERSION_HPP_INCLUDED #include "eigen2mat/definitions.hpp" #include "eigen2mat/utils/include_mex" namespace eigen2mat { // MATLAB to eigen2mat /*! * \brief Convert mxArray to \c bool * * \param b mxArray to convert * \return converted value */ bool mxArray_to_bool(const mxArray* b); /*! * \brief Convert mxArray to \c double * * \param d mxArray to convert * \return converted value */ double mxArray_to_double(const mxArray* d); /*! * \brief Convert mxArray to \link definitions::size_t size_t\endlink * * \param i mxArray to convert * \return converted value */ size_t mxArray_to_idx(const mxArray* i); /*! * \brief Convert mxArray to \c int * * \param i mxArray to convert * \return converted value */ int mxArray_to_int(const mxArray* i); /*! * \brief Convert mxArray to \link definitions::dcomplex dcomplex\endlink * * \param z mxArray to convert * \return converted value */ dcomplex mxArray_to_cmplx(const mxArray* z); /*! * \brief Convert mxArray to \link definitions::idx_array_t idx_array_t\endlink * * \param v mxArray to convert * \return converted value */ idx_array_t mxArray_to_idx_array(const mxArray* v); /*! * \brief Convert mxArray to \link definitions::int_array_t int_array_t\endlink * * \param v mxArray to convert * \return converted value */ int_array_t mxArray_to_int_array(const mxArray* v); /*! * \brief Convert mxArray to \link definitions::real_vector_t real_vector_t\endlink * * \param v mxArray to convert * \return converted value */ real_vector_t mxArray_to_real_vector(const mxArray* v); /*! * \brief Convert mxArray to \link definitions::real_row_vector_t real_row_vector_t\endlink * * \param v mxArray to convert * \return converted value */ real_row_vector_t mxArray_to_real_row_vector(const mxArray* v); /*! * \brief Convert mxArray to \link definitions::real_matrix_t real_matrix_t\endlink * * \param m mxArray to convert * \return converted value */ real_matrix_t mxArray_to_real_matrix(const mxArray* m); /*! * \brief Convert mxArray to \link definitions::real_sp_matrix_t real_sp_matrix_t\endlink * * \param m mxArray to convert * \return converted value */ real_sp_matrix_t mxArray_to_real_sp_matrix(const mxArray* m); /*! * \brief Convert mxArray to \link definitions::real_tensor_t real_tensor_t\endlink * * \param t mxArray to convert * \return converted value */ real_tensor_t mxArray_to_real_tensor(const mxArray* t); /*! * \brief Convert mxArray to \link definitions::real_sp_tensor_t real_sp_tensor_t\endlink * * \param t mxArray to convert * \return converted value */ real_sp_tensor_t mxArray_to_real_sp_tensor(const mxArray* t); /*! * \brief Convert mxArray to \link definitions::real_sp_cell_t real_sp_cell_t\endlink * * \param c mxArray to convert * \return converted value */ real_sp_cell_t mxArray_to_real_sp_cell(const mxArray* c); /*! * \brief Convert mxArray to \link definitions::cmplx_vector_t cmplx_vector_t\endlink * * \param v mxArray to convert * \return converted value */ cmplx_vector_t mxArray_to_cmplx_vector(const mxArray* v); /*! * \brief Convert mxArray to \link definitions::cmplx_row_vector_t cmplx_row_vector_t\endlink * * \param v mxArray to convert * \return converted value */ cmplx_row_vector_t mxArray_to_cmplx_row_vector(const mxArray* v); /*! * \brief Convert mxArray to \link definitions::cmplx_matrix_t cmplx_matrix_t\endlink * * \param m mxArray to convert * \return converted value */ cmplx_matrix_t mxArray_to_cmplx_matrix(const mxArray* m); /*! * \brief Convert mxArray to \link definitions::cmplx_sp_matrix_t cmplx_sp_matrix_t \endlink * * \param m mxArray to convert * \return converted value */ cmplx_sp_matrix_t mxArray_to_cmplx_sp_matrix(const mxArray* m); /*! * \brief Convert mxArray to \link definitions::cmplx_tensor_t cmplx_tensor_t\endlink * * \param t mxArray to convert * \return converted value */ cmplx_tensor_t mxArray_to_cmplx_tensor(const mxArray* t); /*! * \brief Convert mxArray to \link definitions::cmplx_sp_tensor_t cmplx_sp_tensor_t\endlink * * \param t mxArray to convert * \return converted value */ cmplx_sp_tensor_t mxArray_to_cmplx_sp_tensor(const mxArray* t); /*! * \brief Convert mxArray to \link definitions::cmplx_sp_cell_t cmplx_sp_cell_t\endlink * * \param c mxArray to convert * \return converted value */ cmplx_sp_cell_t mxArray_to_cmplx_sp_cell(const mxArray* c); // ======================================================================== // eigen2mat to MATLAB /*! * \brief Convert \c bool to mxArray * * \param b value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(bool b); /*! * \brief Convert \c double to mxArray * * \param d value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(double d); /*! * \brief Convert \c int to mxArray * * \param i value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(int i); /*! * \brief Convert \link definitions::size_t size_t\endlink to mxArray * * \param idx value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(size_t idx); /*! * \brief Convert \link definitions::dcomplex dcomplex\endlink to mxArray * * \param z value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const dcomplex& z); /*! * \brief Convert \link definitions::idx_array_t idx_array_t\endlink to mxArray * * \param v value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const idx_array_t& v); /*! * \brief Convert \link definitions::int_array_t int_array_t\endlink to mxArray * * \param v value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const int_array_t& v); /*! * \brief Convert \link definitions::real_sp_matrix_t real_sp_matrix_t\endlink to mxArray * * \param m value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const real_sp_matrix_t& m); /*! * \brief Convert \link definitions::real_tensor_t real_tensor_t\endlink to mxArray * * \param t value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const real_tensor_t& t); /*! * \brief Convert \link definitions::real_sp_cell_t real_sp_cell_t\endlink to mxArray * * \param t value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const real_sp_cell_t& t); /*! * \brief Convert \link definitions::cmplx_sp_matrix_t cmplx_sp_matrix_t\endlink to mxArray * * \param m value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const cmplx_sp_matrix_t& m); /*! * \brief Convert \link definitions::cmplx_tensor_t cmplx_tensor_t\endlink to mxArray * * \param t value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const cmplx_tensor_t& t); /*! * \brief Convert \link definitions::cmplx_sp_cell_t cmplx_sp_cell_t\endlink to mxArray * * \param t value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const cmplx_sp_cell_t& t); /*! * \brief Get the sizes of a 3D mxArray * * \param a input array * \return dimension array */ dim_array_t get_dimensions(const mxArray* a); } // namespace eigen2mat #include "details/eigen_expressions_conversions.hpp" #include "details/generic_conversions.hpp" #endif /* E2M_CONVERSION_HPP_INCLUDED */ <commit_msg>Comment feature under development<commit_after>// This file is part of eigen2mat, a simple C++ library to use // Eigen with MATLAB's MEX files // // Copyright (C) 2013 Nguyen Damien <damien.nguyen@a3.epfl.ch> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef E2M_CONVERSION_HPP_INCLUDED #define E2M_CONVERSION_HPP_INCLUDED #include "eigen2mat/definitions.hpp" #include "eigen2mat/utils/include_mex" namespace eigen2mat { // MATLAB to eigen2mat /*! * \brief Convert mxArray to \c bool * * \param b mxArray to convert * \return converted value */ bool mxArray_to_bool(const mxArray* b); /*! * \brief Convert mxArray to \c double * * \param d mxArray to convert * \return converted value */ double mxArray_to_double(const mxArray* d); /*! * \brief Convert mxArray to \link definitions::size_t size_t\endlink * * \param i mxArray to convert * \return converted value */ size_t mxArray_to_idx(const mxArray* i); /*! * \brief Convert mxArray to \c int * * \param i mxArray to convert * \return converted value */ int mxArray_to_int(const mxArray* i); /*! * \brief Convert mxArray to \link definitions::dcomplex dcomplex\endlink * * \param z mxArray to convert * \return converted value */ dcomplex mxArray_to_cmplx(const mxArray* z); /*! * \brief Convert mxArray to \link definitions::idx_array_t idx_array_t\endlink * * \param v mxArray to convert * \return converted value */ idx_array_t mxArray_to_idx_array(const mxArray* v); /*! * \brief Convert mxArray to \link definitions::int_array_t int_array_t\endlink * * \param v mxArray to convert * \return converted value */ int_array_t mxArray_to_int_array(const mxArray* v); /*! * \brief Convert mxArray to \link definitions::real_vector_t real_vector_t\endlink * * \param v mxArray to convert * \return converted value */ real_vector_t mxArray_to_real_vector(const mxArray* v); /*! * \brief Convert mxArray to \link definitions::real_row_vector_t real_row_vector_t\endlink * * \param v mxArray to convert * \return converted value */ real_row_vector_t mxArray_to_real_row_vector(const mxArray* v); /*! * \brief Convert mxArray to \link definitions::real_matrix_t real_matrix_t\endlink * * \param m mxArray to convert * \return converted value */ real_matrix_t mxArray_to_real_matrix(const mxArray* m); /*! * \brief Convert mxArray to \link definitions::real_sp_matrix_t real_sp_matrix_t\endlink * * \param m mxArray to convert * \return converted value */ real_sp_matrix_t mxArray_to_real_sp_matrix(const mxArray* m); /*! * \brief Convert mxArray to \link definitions::real_tensor_t real_tensor_t\endlink * * \param t mxArray to convert * \return converted value */ real_tensor_t mxArray_to_real_tensor(const mxArray* t); /*! * \brief Convert mxArray to \link definitions::real_sp_tensor_t real_sp_tensor_t\endlink * * \param t mxArray to convert * \return converted value */ real_sp_tensor_t mxArray_to_real_sp_tensor(const mxArray* t); /*! * \brief Convert mxArray to \link definitions::real_sp_cell_t real_sp_cell_t\endlink * * \param c mxArray to convert * \return converted value */ real_sp_cell_t mxArray_to_real_sp_cell(const mxArray* c); /*! * \brief Convert mxArray to \link definitions::cmplx_vector_t cmplx_vector_t\endlink * * \param v mxArray to convert * \return converted value */ cmplx_vector_t mxArray_to_cmplx_vector(const mxArray* v); /*! * \brief Convert mxArray to \link definitions::cmplx_row_vector_t cmplx_row_vector_t\endlink * * \param v mxArray to convert * \return converted value */ cmplx_row_vector_t mxArray_to_cmplx_row_vector(const mxArray* v); /*! * \brief Convert mxArray to \link definitions::cmplx_matrix_t cmplx_matrix_t\endlink * * \param m mxArray to convert * \return converted value */ cmplx_matrix_t mxArray_to_cmplx_matrix(const mxArray* m); /*! * \brief Convert mxArray to \link definitions::cmplx_sp_matrix_t cmplx_sp_matrix_t \endlink * * \param m mxArray to convert * \return converted value */ cmplx_sp_matrix_t mxArray_to_cmplx_sp_matrix(const mxArray* m); /*! * \brief Convert mxArray to \link definitions::cmplx_tensor_t cmplx_tensor_t\endlink * * \param t mxArray to convert * \return converted value */ cmplx_tensor_t mxArray_to_cmplx_tensor(const mxArray* t); /*! * \brief Convert mxArray to \link definitions::cmplx_sp_tensor_t cmplx_sp_tensor_t\endlink * * \param t mxArray to convert * \return converted value */ cmplx_sp_tensor_t mxArray_to_cmplx_sp_tensor(const mxArray* t); /*! * \brief Convert mxArray to \link definitions::cmplx_sp_cell_t cmplx_sp_cell_t\endlink * * \param c mxArray to convert * \return converted value */ cmplx_sp_cell_t mxArray_to_cmplx_sp_cell(const mxArray* c); // ======================================================================== // eigen2mat to MATLAB /*! * \brief Convert \c bool to mxArray * * \param b value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(bool b); /*! * \brief Convert \c double to mxArray * * \param d value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(double d); /*! * \brief Convert \c int to mxArray * * \param i value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(int i); /*! * \brief Convert \link definitions::size_t size_t\endlink to mxArray * * \param idx value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(size_t idx); /*! * \brief Convert \link definitions::dcomplex dcomplex\endlink to mxArray * * \param z value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const dcomplex& z); /*! * \brief Convert \link definitions::idx_array_t idx_array_t\endlink to mxArray * * \param v value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const idx_array_t& v); /*! * \brief Convert \link definitions::int_array_t int_array_t\endlink to mxArray * * \param v value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const int_array_t& v); /*! * \brief Convert \link definitions::real_sp_matrix_t real_sp_matrix_t\endlink to mxArray * * \param m value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const real_sp_matrix_t& m); /*! * \brief Convert \link definitions::real_tensor_t real_tensor_t\endlink to mxArray * * \param t value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const real_tensor_t& t); /*! * \brief Convert \link definitions::real_sp_cell_t real_sp_cell_t\endlink to mxArray * * \param t value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const real_sp_cell_t& t); /*! * \brief Convert \link definitions::cmplx_sp_matrix_t cmplx_sp_matrix_t\endlink to mxArray * * \param m value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const cmplx_sp_matrix_t& m); /*! * \brief Convert \link definitions::cmplx_tensor_t cmplx_tensor_t\endlink to mxArray * * \param t value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const cmplx_tensor_t& t); /*! * \brief Convert \link definitions::cmplx_sp_cell_t cmplx_sp_cell_t\endlink to mxArray * * \param t value to be converted * \return mxArray with data stored in it */ mxArray* to_mxArray(const cmplx_sp_cell_t& t); /*! * \brief Get the sizes of a 3D mxArray * * \param a input array * \return dimension array */ dim_array_t get_dimensions(const mxArray* a); } // namespace eigen2mat #include "details/eigen_expressions_conversions.hpp" // This is still experimental... // #include "details/generic_conversions.hpp" #endif /* E2M_CONVERSION_HPP_INCLUDED */ <|endoftext|>
<commit_before>/* * Copyright (c) 2012 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #include <qi/qi.hpp> #include <qi/os.hpp> #include <numeric> #include <boost/filesystem.hpp> #include "src/filesystem.hpp" #ifdef __APPLE__ #include <mach-o/dyld.h> #endif #ifdef _WIN32 #include <windows.h> #endif namespace qi { static int globalArgc = -1; static char** globalArgv = 0; static std::string globalPrefix; static std::string globalProgram; static std::string guess_app_from_path(int argc, const char *argv[]) { boost::filesystem::path execPath(argv[0], qi::unicodeFacet()); execPath = boost::filesystem::system_complete(execPath).make_preferred(); execPath = boost::filesystem::path(detail::normalizePath(execPath.string(qi::unicodeFacet())), qi::unicodeFacet()); //arg0 does not exists, or is not a program (directory) if (!boost::filesystem::exists(execPath) || boost::filesystem::is_directory(execPath)) { std::string filename = execPath.filename().string(qi::unicodeFacet()); std::string envPath = qi::os::getenv("PATH"); size_t begin = 0; #ifndef _WIN32 size_t end = envPath.find(":", begin); #else size_t end = envPath.find(";", begin); #endif while (end != std::string::npos) { std::string realPath = ""; realPath = envPath.substr(begin, end - begin); boost::filesystem::path p(realPath, qi::unicodeFacet()); p /= filename; p = boost::filesystem::system_complete(p).make_preferred(); p = boost::filesystem::path(detail::normalizePath(p.string(qi::unicodeFacet())), qi::unicodeFacet()); if (boost::filesystem::exists(p) && !boost::filesystem::is_directory(p)) return p.string(qi::unicodeFacet()); begin = end + 1; #ifndef _WIN32 end = envPath.find(":", begin); #else end = envPath.find(";", begin); #endif } } else return execPath.string(qi::unicodeFacet()); return std::string(); } void init(int argc, char *argv[]) { globalArgc = argc; globalArgv = argv; } int argc() { return globalArgc; } const char** argv() { return (const char**)globalArgv; } /* http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe Some OS-specific interfaces: Mac OS X: _NSGetExecutablePath() (man 3 dyld) Linux : readlink /proc/self/exe Solaris : getexecname() FreeBSD : sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1 BSD with procfs: readlink /proc/curproc/file Windows : GetModuleFileName() with hModule = NULL The portable (but less reliable) method is to use argv[0]. Although it could be set to anything by the calling program, by convention it is set to either a path name of the executable or a name that was found using $PATH. Some shells, including bash and ksh, set the environment variable "_" to the full path of the executable before it is executed. In that case you can use getenv("_") to get it. However this is unreliable because not all shells do this, and it could be set to anything or be left over from a parent process which did not change it before executing your program. */ const char *program() { try { if (!globalProgram.empty()) return globalProgram.c_str(); #ifdef __APPLE__ { char *fname = (char *)malloc(PATH_MAX); uint32_t sz = PATH_MAX; fname[0] = 0; int ret; ret = _NSGetExecutablePath(fname, &sz); if (ret == 0) { globalProgram = fname; globalProgram = detail::normalizePath(globalProgram); } else { globalProgram = guess_app_from_path(::qi::argc(), ::qi::argv()); } free(fname); } #elif __linux__ boost::filesystem::path p("/proc/self/exe"); boost::filesystem::path fname = boost::filesystem::read_symlink(p); if (!boost::filesystem::is_empty(fname)) globalProgram = fname.string().c_str(); else globalProgram = guess_app_from_path(::qi::argc(), ::qi::argv()); #elif _WIN32 WCHAR *fname = (WCHAR *) malloc(MAX_PATH); int ret = GetModuleFileNameW(NULL, fname, MAX_PATH); if (ret != 0) { boost::filesystem::path programPath(fname, qi::unicodeFacet()); globalProgram = programPath.string(qi::unicodeFacet()); free(fname); } else { // GetModuleFileName failed, trying to guess from argc, argv... globalProgram = guess_app_from_path(::qi::argc(), ::qi::argv()); } #else globalProgram = guess_app_from_path(::qi::argc(), ::qi::argv()); #endif return globalProgram.c_str(); } catch (...) { return NULL; } } } <commit_msg>Application: feed sdk prefix from share/qi/path.conf if present.<commit_after>/* * Copyright (c) 2012 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #include <fstream> #include <qi/qi.hpp> #include <qi/os.hpp> #include <qi/log.hpp> #include <qi/path.hpp> #include <numeric> #include <boost/filesystem.hpp> #include "src/filesystem.hpp" #ifdef __APPLE__ #include <mach-o/dyld.h> #endif #ifdef _WIN32 #include <windows.h> #endif namespace qi { static int globalArgc = -1; static char** globalArgv = 0; static std::string globalPrefix; static std::string globalProgram; static std::string guess_app_from_path(int argc, const char *argv[]) { boost::filesystem::path execPath(argv[0], qi::unicodeFacet()); execPath = boost::filesystem::system_complete(execPath).make_preferred(); execPath = boost::filesystem::path(detail::normalizePath(execPath.string(qi::unicodeFacet())), qi::unicodeFacet()); //arg0 does not exists, or is not a program (directory) if (!boost::filesystem::exists(execPath) || boost::filesystem::is_directory(execPath)) { std::string filename = execPath.filename().string(qi::unicodeFacet()); std::string envPath = qi::os::getenv("PATH"); size_t begin = 0; #ifndef _WIN32 size_t end = envPath.find(":", begin); #else size_t end = envPath.find(";", begin); #endif while (end != std::string::npos) { std::string realPath = ""; realPath = envPath.substr(begin, end - begin); boost::filesystem::path p(realPath, qi::unicodeFacet()); p /= filename; p = boost::filesystem::system_complete(p).make_preferred(); p = boost::filesystem::path(detail::normalizePath(p.string(qi::unicodeFacet())), qi::unicodeFacet()); if (boost::filesystem::exists(p) && !boost::filesystem::is_directory(p)) return p.string(qi::unicodeFacet()); begin = end + 1; #ifndef _WIN32 end = envPath.find(":", begin); #else end = envPath.find(";", begin); #endif } } else return execPath.string(qi::unicodeFacet()); return std::string(); } void init(int argc, char *argv[]) { //Feed qi::path prefix from share/qi/path.conf if present //(automatically created when using qiBuild) std::string pathConf = ::qi::path::findData("qi", "path.conf"); if (!pathConf.empty()) { std::ifstream is(pathConf.c_str()); while (is.good()) { std::string path; std::getline(is, path); if (!path.empty() && path[0] != '#') { boost::filesystem::path bpath(path, qi::unicodeFacet()); if (boost::filesystem::exists(bpath)) { qiLogDebug("Application") << "Adding to path " << path; ::qi::path::detail::addOptionalSdkPrefix(path.c_str()); } } } } globalArgc = argc; globalArgv = argv; } int argc() { return globalArgc; } const char** argv() { return (const char**)globalArgv; } /* http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe Some OS-specific interfaces: Mac OS X: _NSGetExecutablePath() (man 3 dyld) Linux : readlink /proc/self/exe Solaris : getexecname() FreeBSD : sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1 BSD with procfs: readlink /proc/curproc/file Windows : GetModuleFileName() with hModule = NULL The portable (but less reliable) method is to use argv[0]. Although it could be set to anything by the calling program, by convention it is set to either a path name of the executable or a name that was found using $PATH. Some shells, including bash and ksh, set the environment variable "_" to the full path of the executable before it is executed. In that case you can use getenv("_") to get it. However this is unreliable because not all shells do this, and it could be set to anything or be left over from a parent process which did not change it before executing your program. */ const char *program() { try { if (!globalProgram.empty()) return globalProgram.c_str(); #ifdef __APPLE__ { char *fname = (char *)malloc(PATH_MAX); uint32_t sz = PATH_MAX; fname[0] = 0; int ret; ret = _NSGetExecutablePath(fname, &sz); if (ret == 0) { globalProgram = fname; globalProgram = detail::normalizePath(globalProgram); } else { globalProgram = guess_app_from_path(::qi::argc(), ::qi::argv()); } free(fname); } #elif __linux__ boost::filesystem::path p("/proc/self/exe"); boost::filesystem::path fname = boost::filesystem::read_symlink(p); if (!boost::filesystem::is_empty(fname)) globalProgram = fname.string().c_str(); else globalProgram = guess_app_from_path(::qi::argc(), ::qi::argv()); #elif _WIN32 WCHAR *fname = (WCHAR *) malloc(MAX_PATH); int ret = GetModuleFileNameW(NULL, fname, MAX_PATH); if (ret != 0) { boost::filesystem::path programPath(fname, qi::unicodeFacet()); globalProgram = programPath.string(qi::unicodeFacet()); free(fname); } else { // GetModuleFileName failed, trying to guess from argc, argv... globalProgram = guess_app_from_path(::qi::argc(), ::qi::argv()); } #else globalProgram = guess_app_from_path(::qi::argc(), ::qi::argv()); #endif return globalProgram.c_str(); } catch (...) { return NULL; } } } <|endoftext|>
<commit_before>#include "./application.h" #include <QQmlContext> #include <QStateMachine> #include <QDebug> #include <vector> #include "./window.h" #include "./scene.h" #include "./scene_controller.h" #include "./nodes.h" #include "./nodes_controller.h" #include "./label_node.h" #include "./input/invoke_manager.h" #include "./input/signal_manager.h" #include "./input/scxml_importer.h" #include "./mouse_shape_controller.h" #include "./labeller_model.h" #include "./placement_labeller_model.h" #include "./labels_model.h" #include "./camera_positions_model.h" #include "./labelling/labels.h" #include "./labelling_coordinator.h" #include "./labelling_controller.h" #include "./picking_controller.h" #include "./forces_visualizer_node.h" #include "./camera_node.h" #include "./default_scene_creator.h" #include "./video_recorder.h" #include "./video_recorder_controller.h" #include "./texture_mapper_manager.h" #include "./texture_mapper_manager_controller.h" #include "./utils/memory.h" #include "./utils/path_helper.h" #include "./recording_automation.h" #include "./recording_automation_controller.h" Application::Application(int &argc, char **argv) : application(argc, argv) { application.setApplicationName("voly-labeller"); application.setApplicationVersion("0.0.1"); application.setOrganizationName("LBI"); setupCommandLineParser(); parser.process(application); invokeManager = std::make_shared<InvokeManager>(); nodes = std::make_shared<Nodes>(); nodesController = std::make_shared<NodesController>(nodes); labels = std::make_shared<Labels>(); forcesLabeller = std::make_shared<Forces::Labeller>(labels); int layerCount = parseLayerCount(); auto labellingCoordinator = std::make_shared<LabellingCoordinator>( layerCount, forcesLabeller, labels, nodes); bool synchronousCapturing = parser.isSet("offline"); const float offlineFPS = 24; videoRecorder = std::make_shared<VideoRecorder>(synchronousCapturing, offlineFPS); videoRecorderController = std::make_unique<VideoRecorderController>(videoRecorder); recordingAutomation = std::make_shared<RecordingAutomation>( labellingCoordinator, nodes, videoRecorder); if (parser.isSet("screenshot")) recordingAutomation->takeScreenshotOfPositionAndExit( parser.value("screenshot").toStdString()); recordingAutomationController = std::make_unique<RecordingAutomationController>(recordingAutomation); const int postProcessingTextureSize = 512; textureMapperManager = std::make_shared<TextureMapperManager>(postProcessingTextureSize); textureMapperManagerController = std::make_unique<TextureMapperManagerController>(textureMapperManager); scene = std::make_shared<Scene>(layerCount, invokeManager, nodes, labels, labellingCoordinator, textureMapperManager, recordingAutomation); float offlineRenderingFrameTime = parser.isSet("offline") ? 1.0f / offlineFPS : 0.0f; window = std::make_unique<Window>(scene, videoRecorder, offlineRenderingFrameTime); sceneController = std::make_unique<SceneController>(scene); labellerModel = std::make_unique<LabellerModel>(forcesLabeller); placementLabellerModel = std::make_unique<PlacementLabellerModel>(labellingCoordinator); cameraPositionsModel = std::make_unique<CameraPositionsModel>(nodes); mouseShapeController = std::make_unique<MouseShapeController>(); pickingController = std::make_shared<PickingController>(scene); labelsModel = std::make_unique<LabelsModel>(labels, pickingController); labellingController = std::make_unique<LabellingController>(labellingCoordinator); } Application::~Application() { } int Application::execute() { qInfo() << "Application start"; auto unsubscribeLabelChanges = labels->subscribe( std::bind(&Application::onLabelChangedUpdateLabelNodes, this, std::placeholders::_1, std::placeholders::_2)); setupWindow(); connect(labellerModel.get(), &LabellerModel::isVisibleChanged, this, &Application::onFocesLabellerModelIsVisibleChanged); window->setSource(QUrl("qrc:ui.qml")); forcesLabeller->resize(window->size().width(), window->size().height()); nodes->setOnNodeAdded( [this](std::shared_ptr<Node> node) { this->onNodeAdded(node); }); nodes->getCameraNode()->setOnCameraPositionsChanged( [this](std::vector<CameraPosition> cameraPositions) { this->cameraPositionsModel->update(cameraPositions); }); if (parser.positionalArguments().size()) { auto absolutePath = QDir(parser.positionalArguments()[0]).absolutePath(); auto filename = absolutePathToProjectRelativePath(absolutePath); qInfo() << "import scene:" << filename; nodesController->addSceneNodesFrom(filename); } else { DefaultSceneCreator sceneCreator(nodes, labels); sceneCreator.create(); } createAndStartStateMachine(); window->show(); auto resultCode = application.exec(); unsubscribeLabelChanges(); return resultCode; } void Application::setupCommandLineParser() { QGuiApplication::setApplicationName("voly-labeller"); QGuiApplication::setApplicationVersion("0.1"); parser.setApplicationDescription( "Multiple labelling implementations for volume rendered medical data"); parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument( "scene", QCoreApplication::translate("main", "Scene file to load.")); QCommandLineOption offlineRenderingOption("offline", "Enables offline rendering"); parser.addOption(offlineRenderingOption); QCommandLineOption layersOption("layers", "Number of layers. Default is 4", "layerCount", "4"); parser.addOption(layersOption); QCommandLineOption screenshotOption( QStringList() << "s" << "screenshot", "Takes a screenshot of the given camera position", "Camera Position"); parser.addOption(screenshotOption); } void Application::setupWindow() { window->setResizeMode(QQuickView::SizeRootObjectToView); auto context = window->rootContext(); auto assetsPath = QUrl::fromLocalFile(absolutePathOfProjectRelativePath(QString("assets"))); context->setContextProperty("assetsPath", assetsPath); auto projectRootPath = QUrl::fromLocalFile(absolutePathOfProjectRelativePath(QString("."))); context->setContextProperty("projectRootPath", projectRootPath); context->setContextProperty("window", window.get()); context->setContextProperty("nodes", nodesController.get()); context->setContextProperty("bufferTextures", textureMapperManagerController.get()); context->setContextProperty("scene", sceneController.get()); context->setContextProperty("labeller", labellerModel.get()); context->setContextProperty("placement", placementLabellerModel.get()); context->setContextProperty("cameraPositions", cameraPositionsModel.get()); context->setContextProperty("labels", labelsModel.get()); context->setContextProperty("labelling", labellingController.get()); context->setContextProperty("videoRecorder", videoRecorderController.get()); context->setContextProperty("automation", recordingAutomationController.get()); } void Application::createAndStartStateMachine() { auto signalManager = std::shared_ptr<SignalManager>(new SignalManager()); ScxmlImporter importer(QUrl::fromLocalFile("config/states.xml"), invokeManager, signalManager); invokeManager->addHandler(window.get()); invokeManager->addHandler("mouseShape", mouseShapeController.get()); invokeManager->addHandler("picking", pickingController.get()); invokeManager->addHandler("scene", sceneController.get()); signalManager->addSender("KeyboardEventSender", window.get()); signalManager->addSender("window", window.get()); signalManager->addSender("labels", labelsModel.get()); stateMachine = importer.import(); // just for printCurrentState slot for debugging window->stateMachine = stateMachine; stateMachine->start(); } void Application::onNodeAdded(std::shared_ptr<Node> node) { std::shared_ptr<LabelNode> labelNode = std::dynamic_pointer_cast<LabelNode>(node); if (labelNode.get()) { labelNode->anchorSize = nodesController->getAnchorSize(); labels->add(labelNode->label); } std::shared_ptr<CameraNode> cameraNode = std::dynamic_pointer_cast<CameraNode>(node); if (cameraNode.get()) { cameraNode->setOnCameraPositionsChanged( [this](std::vector<CameraPosition> cameraPositions) { this->cameraPositionsModel->update(cameraPositions); }); } } void Application::onLabelChangedUpdateLabelNodes(Labels::Action action, const Label &label) { auto labelNodes = nodes->getLabelNodes(); auto labelNode = std::find_if(labelNodes.begin(), labelNodes.end(), [label](std::shared_ptr<LabelNode> labelNode) { return labelNode->label.id == label.id; }); if (labelNode == labelNodes.end()) { nodes->addNode(std::make_shared<LabelNode>(label)); } else if (action == Labels::Action::Delete) { nodes->removeNode(*labelNode); } else { (*labelNode)->label = label; } }; void Application::onFocesLabellerModelIsVisibleChanged() { if (labellerModel->getIsVisible()) { nodes->addForcesVisualizerNode( std::make_shared<ForcesVisualizerNode>(forcesLabeller)); } else { nodes->removeForcesVisualizerNode(); } } int Application::parseLayerCount() { int layerCount = 4; if (parser.isSet("layers")) { bool gotLayerCount = true; layerCount = parser.value("layers").toInt(&gotLayerCount); if (!gotLayerCount) { layerCount = 4; qWarning() << "Problem parsing layer count from" << parser.value("layers"); } if (layerCount < 1 || layerCount > 6) qFatal("Layer count must be between 1 and 6"); } return layerCount; } <commit_msg>Increase the postProcessingTextureSize to 1024 (same as view).<commit_after>#include "./application.h" #include <QQmlContext> #include <QStateMachine> #include <QDebug> #include <vector> #include "./window.h" #include "./scene.h" #include "./scene_controller.h" #include "./nodes.h" #include "./nodes_controller.h" #include "./label_node.h" #include "./input/invoke_manager.h" #include "./input/signal_manager.h" #include "./input/scxml_importer.h" #include "./mouse_shape_controller.h" #include "./labeller_model.h" #include "./placement_labeller_model.h" #include "./labels_model.h" #include "./camera_positions_model.h" #include "./labelling/labels.h" #include "./labelling_coordinator.h" #include "./labelling_controller.h" #include "./picking_controller.h" #include "./forces_visualizer_node.h" #include "./camera_node.h" #include "./default_scene_creator.h" #include "./video_recorder.h" #include "./video_recorder_controller.h" #include "./texture_mapper_manager.h" #include "./texture_mapper_manager_controller.h" #include "./utils/memory.h" #include "./utils/path_helper.h" #include "./recording_automation.h" #include "./recording_automation_controller.h" Application::Application(int &argc, char **argv) : application(argc, argv) { application.setApplicationName("voly-labeller"); application.setApplicationVersion("0.0.1"); application.setOrganizationName("LBI"); setupCommandLineParser(); parser.process(application); invokeManager = std::make_shared<InvokeManager>(); nodes = std::make_shared<Nodes>(); nodesController = std::make_shared<NodesController>(nodes); labels = std::make_shared<Labels>(); forcesLabeller = std::make_shared<Forces::Labeller>(labels); int layerCount = parseLayerCount(); auto labellingCoordinator = std::make_shared<LabellingCoordinator>( layerCount, forcesLabeller, labels, nodes); bool synchronousCapturing = parser.isSet("offline"); const float offlineFPS = 24; videoRecorder = std::make_shared<VideoRecorder>(synchronousCapturing, offlineFPS); videoRecorderController = std::make_unique<VideoRecorderController>(videoRecorder); recordingAutomation = std::make_shared<RecordingAutomation>( labellingCoordinator, nodes, videoRecorder); if (parser.isSet("screenshot")) recordingAutomation->takeScreenshotOfPositionAndExit( parser.value("screenshot").toStdString()); recordingAutomationController = std::make_unique<RecordingAutomationController>(recordingAutomation); const int postProcessingTextureSize = 1024; textureMapperManager = std::make_shared<TextureMapperManager>(postProcessingTextureSize); textureMapperManagerController = std::make_unique<TextureMapperManagerController>(textureMapperManager); scene = std::make_shared<Scene>(layerCount, invokeManager, nodes, labels, labellingCoordinator, textureMapperManager, recordingAutomation); float offlineRenderingFrameTime = parser.isSet("offline") ? 1.0f / offlineFPS : 0.0f; window = std::make_unique<Window>(scene, videoRecorder, offlineRenderingFrameTime); sceneController = std::make_unique<SceneController>(scene); labellerModel = std::make_unique<LabellerModel>(forcesLabeller); placementLabellerModel = std::make_unique<PlacementLabellerModel>(labellingCoordinator); cameraPositionsModel = std::make_unique<CameraPositionsModel>(nodes); mouseShapeController = std::make_unique<MouseShapeController>(); pickingController = std::make_shared<PickingController>(scene); labelsModel = std::make_unique<LabelsModel>(labels, pickingController); labellingController = std::make_unique<LabellingController>(labellingCoordinator); } Application::~Application() { } int Application::execute() { qInfo() << "Application start"; auto unsubscribeLabelChanges = labels->subscribe( std::bind(&Application::onLabelChangedUpdateLabelNodes, this, std::placeholders::_1, std::placeholders::_2)); setupWindow(); connect(labellerModel.get(), &LabellerModel::isVisibleChanged, this, &Application::onFocesLabellerModelIsVisibleChanged); window->setSource(QUrl("qrc:ui.qml")); forcesLabeller->resize(window->size().width(), window->size().height()); nodes->setOnNodeAdded( [this](std::shared_ptr<Node> node) { this->onNodeAdded(node); }); nodes->getCameraNode()->setOnCameraPositionsChanged( [this](std::vector<CameraPosition> cameraPositions) { this->cameraPositionsModel->update(cameraPositions); }); if (parser.positionalArguments().size()) { auto absolutePath = QDir(parser.positionalArguments()[0]).absolutePath(); auto filename = absolutePathToProjectRelativePath(absolutePath); qInfo() << "import scene:" << filename; nodesController->addSceneNodesFrom(filename); } else { DefaultSceneCreator sceneCreator(nodes, labels); sceneCreator.create(); } createAndStartStateMachine(); window->show(); auto resultCode = application.exec(); unsubscribeLabelChanges(); return resultCode; } void Application::setupCommandLineParser() { QGuiApplication::setApplicationName("voly-labeller"); QGuiApplication::setApplicationVersion("0.1"); parser.setApplicationDescription( "Multiple labelling implementations for volume rendered medical data"); parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument( "scene", QCoreApplication::translate("main", "Scene file to load.")); QCommandLineOption offlineRenderingOption("offline", "Enables offline rendering"); parser.addOption(offlineRenderingOption); QCommandLineOption layersOption("layers", "Number of layers. Default is 4", "layerCount", "4"); parser.addOption(layersOption); QCommandLineOption screenshotOption( QStringList() << "s" << "screenshot", "Takes a screenshot of the given camera position", "Camera Position"); parser.addOption(screenshotOption); } void Application::setupWindow() { window->setResizeMode(QQuickView::SizeRootObjectToView); auto context = window->rootContext(); auto assetsPath = QUrl::fromLocalFile(absolutePathOfProjectRelativePath(QString("assets"))); context->setContextProperty("assetsPath", assetsPath); auto projectRootPath = QUrl::fromLocalFile(absolutePathOfProjectRelativePath(QString("."))); context->setContextProperty("projectRootPath", projectRootPath); context->setContextProperty("window", window.get()); context->setContextProperty("nodes", nodesController.get()); context->setContextProperty("bufferTextures", textureMapperManagerController.get()); context->setContextProperty("scene", sceneController.get()); context->setContextProperty("labeller", labellerModel.get()); context->setContextProperty("placement", placementLabellerModel.get()); context->setContextProperty("cameraPositions", cameraPositionsModel.get()); context->setContextProperty("labels", labelsModel.get()); context->setContextProperty("labelling", labellingController.get()); context->setContextProperty("videoRecorder", videoRecorderController.get()); context->setContextProperty("automation", recordingAutomationController.get()); } void Application::createAndStartStateMachine() { auto signalManager = std::shared_ptr<SignalManager>(new SignalManager()); ScxmlImporter importer(QUrl::fromLocalFile("config/states.xml"), invokeManager, signalManager); invokeManager->addHandler(window.get()); invokeManager->addHandler("mouseShape", mouseShapeController.get()); invokeManager->addHandler("picking", pickingController.get()); invokeManager->addHandler("scene", sceneController.get()); signalManager->addSender("KeyboardEventSender", window.get()); signalManager->addSender("window", window.get()); signalManager->addSender("labels", labelsModel.get()); stateMachine = importer.import(); // just for printCurrentState slot for debugging window->stateMachine = stateMachine; stateMachine->start(); } void Application::onNodeAdded(std::shared_ptr<Node> node) { std::shared_ptr<LabelNode> labelNode = std::dynamic_pointer_cast<LabelNode>(node); if (labelNode.get()) { labelNode->anchorSize = nodesController->getAnchorSize(); labels->add(labelNode->label); } std::shared_ptr<CameraNode> cameraNode = std::dynamic_pointer_cast<CameraNode>(node); if (cameraNode.get()) { cameraNode->setOnCameraPositionsChanged( [this](std::vector<CameraPosition> cameraPositions) { this->cameraPositionsModel->update(cameraPositions); }); } } void Application::onLabelChangedUpdateLabelNodes(Labels::Action action, const Label &label) { auto labelNodes = nodes->getLabelNodes(); auto labelNode = std::find_if(labelNodes.begin(), labelNodes.end(), [label](std::shared_ptr<LabelNode> labelNode) { return labelNode->label.id == label.id; }); if (labelNode == labelNodes.end()) { nodes->addNode(std::make_shared<LabelNode>(label)); } else if (action == Labels::Action::Delete) { nodes->removeNode(*labelNode); } else { (*labelNode)->label = label; } }; void Application::onFocesLabellerModelIsVisibleChanged() { if (labellerModel->getIsVisible()) { nodes->addForcesVisualizerNode( std::make_shared<ForcesVisualizerNode>(forcesLabeller)); } else { nodes->removeForcesVisualizerNode(); } } int Application::parseLayerCount() { int layerCount = 4; if (parser.isSet("layers")) { bool gotLayerCount = true; layerCount = parser.value("layers").toInt(&gotLayerCount); if (!gotLayerCount) { layerCount = 4; qWarning() << "Problem parsing layer count from" << parser.value("layers"); } if (layerCount < 1 || layerCount > 6) qFatal("Layer count must be between 1 and 6"); } return layerCount; } <|endoftext|>
<commit_before>#include "nevil/arena/robot.hpp" nevil::robot::robot() : Enki::EPuck(EPuck::CAPABILITY_CAMERA) {} nevil::robot::robot(double x, double y, double angle ,const std::string &robot_name, const Enki::Color &color, double max_speed) : Enki::EPuck(EPuck::CAPABILITY_CAMERA) , _initial_angle(angle * M_PI) , _initial_position(Enki::Point(x, y)) , _max_speed(max_speed) , _robot_name(robot_name) { if (max_speed > 12.8) std::cout << "Warning the max speed of Epuck is 12.8." << std::endl; setColor(color); reset_position(); } nevil::robot::~robot() {} void nevil::robot::reset_position() { leftSpeed = 0; rightSpeed = 0; pos = _initial_position; angle = _initial_angle; } /* Color sets for switch and light 0.5 | 0.5 | 0.0 light turned off 1.0 | 1.0 | 0.0 light turned On 0.4 | 0.0 | 1.0 switch turned off 0.4 | 0.5 | 1.0 switch turned On */ const std::vector<double> nevil::robot::_get_sensor_inputs() { //reset the counters std::vector<double> sensor_counter(SENSOR_NUM, 0); // Each color has 6 groups of pixels for (size_t i = 0; i < 6; ++i) { // One group is 10 pixels for (size_t j = 0; j < 10; ++j) { // switch if (camera.image[i * 10 + j].r() == 0.4) ++sensor_counter[i]; // light off if (camera.image[i * 10 + j].r() == 0.5) ++sensor_counter[i + 6]; // light on if (camera.image[i * 10 + j].r() == 1.0) ++sensor_counter[i + 12]; } } // adjust the sensor information for (size_t i = 0; i < SENSOR_NUM; ++i) { if (sensor_counter[i] > 7) sensor_counter[i] = 1; else sensor_counter[i] = 0; } return sensor_counter; } std::string nevil::robot::get_name() const { return _robot_name; } double nevil::robot::_clamp(double val, double min, double max) { if (val < min) return min; else if (val > max) return max; else return val; } void nevil::robot::_set_wheels_speed(double left, double right) { leftSpeed = _clamp(left, -1 * _max_speed, _max_speed); rightSpeed = _clamp(right, -1 * _max_speed, _max_speed); } bool nevil::robot::is_at_switch() const { for (int i = 0; i < 60; ++i) if (camera.image[i].r() != 0.4) return false; return true; } bool nevil::robot::is_at_light() const { for (int i = 0; i < 60; ++i) if (camera.image[i].r() != 1.0) return false; return true; } <commit_msg>cleaning vision input<commit_after>#include "nevil/arena/robot.hpp" nevil::robot::robot() : Enki::EPuck(EPuck::CAPABILITY_CAMERA) {} nevil::robot::robot(double x, double y, double angle ,const std::string &robot_name, const Enki::Color &color, double max_speed) : Enki::EPuck(EPuck::CAPABILITY_CAMERA) , _initial_angle(angle * M_PI) , _initial_position(Enki::Point(x, y)) , _max_speed(max_speed) , _robot_name(robot_name) { if (max_speed > 12.8) std::cout << "Warning the max speed of Epuck is 12.8." << std::endl; setColor(color); reset_position(); } nevil::robot::~robot() {} void nevil::robot::reset_position() { leftSpeed = 0; rightSpeed = 0; pos = _initial_position; angle = _initial_angle; } /* Color sets for switch and light 0.5 | 0.5 | 0.0 light turned off 1.0 | 1.0 | 0.0 light turned On 0.4 | 0.0 | 1.0 switch turned off 0.4 | 0.5 | 1.0 switch turned On */ const std::vector<double> nevil::robot::_get_sensor_inputs() { //reset the counters std::vector<double> sensor_counter(SENSOR_NUM, 0); // Each color has 6 groups of pixels for (size_t i = 0; i < 6; ++i) { // One group is 10 pixels for (size_t j = 0; j < 10; ++j) { double red_value = camera.image[i * 10 + j].r(); // switch if (red_value == 0.4) ++sensor_counter[i]; // light off if (red_value == 0.5) ++sensor_counter[i + 6]; // light on if (red_value == 1.0) ++sensor_counter[i + 12]; } } // adjust the sensor information for (size_t i = 0; i < SENSOR_NUM; ++i) { if (sensor_counter[i] > 7) sensor_counter[i] = 1; else sensor_counter[i] = 0; } return sensor_counter; } std::string nevil::robot::get_name() const { return _robot_name; } double nevil::robot::_clamp(double val, double min, double max) { if (val < min) return min; else if (val > max) return max; else return val; } void nevil::robot::_set_wheels_speed(double left, double right) { leftSpeed = _clamp(left, -1 * _max_speed, _max_speed); rightSpeed = _clamp(right, -1 * _max_speed, _max_speed); } bool nevil::robot::is_at_switch() const { for (int i = 0; i < 60; ++i) if (camera.image[i].r() != 0.4) return false; return true; } bool nevil::robot::is_at_light() const { for (int i = 0; i < 60; ++i) if (camera.image[i].r() != 1.0) return false; return true; } <|endoftext|>
<commit_before>#ifndef MJOLNIR_STRUCTURE_TOPOLOGY_H #define MJOLNIR_STRUCTURE_TOPOLOGY_H #include <mjolnir/util/throw_exception.hpp> #include <algorithm> #include <stdexcept> #include <vector> namespace mjolnir { class StructureTopology { public: typedef std::size_t chain_id_type; enum class connection_kind_type { bond, //! define chain contact, //! does not have effect on the chain (nonbonded contact) }; static constexpr chain_id_type uninitialized() noexcept { return std::numeric_limits<chain_id_type>::max(); } // each node corresponds to the particle having same idx in a system. struct node { node(): chain_id(uninitialized()) {} ~node() = default; node(node const&) = default; node(node&&) = default; node& operator=(node const&) = default; node& operator=(node&&) = default; std::size_t chain_id; std::vector<std::pair<std::size_t, connection_kind_type>> adjacents; }; public: StructureTopology() = default; ~StructureTopology() = default; StructureTopology(const StructureTopology&) = default; StructureTopology(StructureTopology&&) = default; StructureTopology& operator=(const StructureTopology&) = default; StructureTopology& operator=(StructureTopology&&) = default; StructureTopology(const std::size_t N): nodes_(N){}; bool empty() const noexcept {return nodes_.empty();} std::size_t size() const noexcept {return nodes_.size();} void resize(const std::size_t N) {nodes_.resize(N); return;} void add_connection(const std::size_t i, const std::size_t j, const connection_kind_type kind); void erase_connection(const std::size_t i, const std::size_t j); void erase_connection(const std::size_t i, const std::size_t j, const connection_kind_type kind); //! reset chain_id of all the particles void construct_chains(); bool has_connection(const std::size_t i, const std::size_t j); bool has_connection(const std::size_t i, const std::size_t j, const connection_kind_type kind); std::vector<std::size_t> list_adjacent_within(const std::size_t node_idx, const std::size_t dist ) const; std::vector<std::size_t> list_adjacent_within(const std::size_t node_idx, const std::size_t dist, const connection_kind_type kind) const; chain_id_type number_of_chains() const noexcept {return this->num_chains_;} chain_id_type chain_of(const std::size_t idx) const {return nodes_.at(idx).chain_id;} chain_id_type& chain_of(const std::size_t idx) {return nodes_.at(idx).chain_id;} private: void list_adjacent_within(const std::size_t node_idx, const std::size_t dist, std::vector<std::size_t>& out) const; void list_adjacent_within(const std::size_t node_idx, const std::size_t dist, const connection_kind_type kind, std::vector<std::size_t>& out ) const; private: std::size_t num_chains_; std::vector<node> nodes_; }; inline void StructureTopology::add_connection( const std::size_t i, const std::size_t j, connection_kind_type kind) { if(nodes_.size() <= std::max(i, j)) { throw_exception<std::out_of_range>( "mjolnir::StructureTopology::add_connection: size of nodes = ", nodes_.size(), ", i = ", i, ", j = ", j); } { const auto elem = std::make_pair(j, kind); auto& adjs = nodes_[i].adjacents; if(std::find(adjs.cbegin(), adjs.cend(), elem) == adjs.cend()) { adjs.push_back(elem); } } { const auto elem = std::make_pair(i, kind); auto& adjs = nodes_[j].adjacents; if(std::find(adjs.cbegin(), adjs.cend(), elem) == adjs.cend()) { adjs.push_back(elem); } } return ; } inline void StructureTopology::erase_connection( const std::size_t i, const std::size_t j) { if(nodes_.size() <= std::max(i, j)) { throw_exception<std::out_of_range>( "mjolnir::StructureTopology::erase_connection: size of nodes = ", nodes_.size(), ", i = ", i, ", j = ", j); } { auto& adjs = nodes_[i].adjacents; const auto found = std::find_if(adjs.begin(), adjs.end(), [j](const std::pair<std::size_t, connection_kind_type>& x){ return x.first == j; }); if(found != adjs.end()) { adjs.erase(found); } } { auto& adjs = nodes_[j].adjacents; const auto found = std::find_if(adjs.begin(), adjs.end(), [i](const std::pair<std::size_t, connection_kind_type>& x){ return x.first == i; }); if(found != adjs.end()) { adjs.erase(found); } } return ; } inline void StructureTopology::erase_connection( const std::size_t i, const std::size_t j, const connection_kind_type kind) { if(nodes_.size() <= std::max(i, j)) { throw_exception<std::out_of_range>( "mjolnir::StructureTopology::erase_connection: size of nodes = ", nodes_.size(), ", i = ", i, ", j = ", j); } { auto& adjs = nodes_[i].adjacents; const auto found = std::find( adjs.begin(), adjs.end(), std::make_pair(j, kind)); if(found != adjs.end()) { adjs.erase(found); } } { auto& adjs = nodes_[j].adjacents; const auto found = std::find( adjs.begin(), adjs.end(), std::make_pair(i, kind)); if(found != adjs.end()) { adjs.erase(found); } } return ; } inline bool StructureTopology::has_connection( const std::size_t i, const std::size_t j) { if(nodes_.size() <= std::max(i, j)) { throw_exception<std::out_of_range>( "mjolnir::StructureTopology::has_connection: size of nodes = ", nodes_.size(), ", i = ", i, ", j = ", j); } if(i == j) {return true;} // XXX const auto& adjs = nodes_[i].adjacents; const auto found = std::find_if(adjs.cbegin(), adjs.cend(), [j](const std::pair<std::size_t, connection_kind_type>& x){ return x.first == j; }); return found != adjs.cend(); } inline bool StructureTopology::has_connection( const std::size_t i, const std::size_t j, const connection_kind_type kind) { if(nodes_.size() <= std::max(i, j)) { throw_exception<std::out_of_range>( "mjolnir::StructureTopology::has_connection: size of nodes = ", nodes_.size(), ", i = ", i, ", j = ", j); } if(i == j) {return true;} // XXX const auto& adjs = nodes_[i].adjacents; const auto found = std::find(adjs.cbegin(), adjs.cend(), std::make_pair(j, kind)); return found != adjs.cend(); } inline std::vector<std::size_t> StructureTopology::list_adjacent_within( const std::size_t node_idx, const std::size_t dist) const { std::vector<std::size_t> retval = {node_idx}; if(dist == 0) {return retval;} for(auto ik : this->nodes_.at(node_idx).adjacents) { if(std::find(retval.cbegin(), retval.cend(), ik.first) != retval.cend()) { continue; // already assigned. ignore it. } retval.push_back(ik.first); this->list_adjacent_within(ik.first, dist - 1, retval); } std::sort(retval.begin(), retval.end()); const auto new_end = std::unique(retval.begin(), retval.end()); retval.erase(new_end, retval.end()); return retval; } inline std::vector<std::size_t> StructureTopology::list_adjacent_within( const std::size_t node_idx, const std::size_t dist, const connection_kind_type kind) const { std::vector<std::size_t> retval = {node_idx}; if(dist == 0) {return retval;} for(auto ik : this->nodes_.at(node_idx).adjacents) { if(ik.second != kind || std::find(retval.cbegin(), retval.cend(), ik.first) != retval.cend()) { continue; } retval.push_back(ik.first); this->list_adjacent_within(ik.first, dist - 1, kind, retval); } std::sort(retval.begin(), retval.end()); const auto new_end = std::unique(retval.begin(), retval.end()); retval.erase(new_end, retval.end()); return retval; } inline void StructureTopology::list_adjacent_within( const std::size_t node_idx, const std::size_t dist, std::vector<std::size_t>& out) const { if(dist == 0) { if(std::find(out.cbegin(), out.cend(), node_idx) != out.cend()) { out.push_back(node_idx); } return ; } for(auto ik : this->nodes_.at(node_idx).adjacents) { if(std::find(out.cbegin(), out.cend(), ik.first) != out.cend()) { continue; } out.push_back(ik.first); this->list_adjacent_within(ik.first, dist - 1, out); } return; } inline void StructureTopology::list_adjacent_within( const std::size_t node_idx, const std::size_t dist, const connection_kind_type kind, std::vector<std::size_t>& out) const { if(dist == 0) { if(std::find(out.cbegin(), out.cend(), node_idx) != out.cend()) { out.push_back(node_idx); } return; } for(auto ik : this->nodes_.at(node_idx).adjacents) { if(ik.second != kind || std::find(out.cbegin(), out.cend(), ik.first) != out.cend()) { continue; } out.push_back(ik.first); this->list_adjacent_within(ik.first, dist-1, kind, out); } return; } inline void StructureTopology::construct_chain() { if(this->nodes_.empty()){return;} for(auto& node : nodes_) { node.chain_id = uninitialized(); } std::size_t next_chain_id = 0; for(auto& node : nodes_) { // node.chain_id = uninitialized(); // already set as `uninit` for(const auto& edge : node.adjacents) { if(edge.second == connection_kind_type::contact) {continue;} node.chain_id = this->nodes_.at(edge.first).chain_id; if(node.chain_id != uninitialized()) {break;} } if(node.chain_id == uninitialized()) { node.chain_id = next_chain_id++; } } this->num_chains_ = ++next_chain_id; return; } } // mjolnir #endif// MJOLNIR_STRUCTURE_TOPOLOGY_H <commit_msg>fix typo<commit_after>#ifndef MJOLNIR_STRUCTURE_TOPOLOGY_H #define MJOLNIR_STRUCTURE_TOPOLOGY_H #include <mjolnir/util/throw_exception.hpp> #include <algorithm> #include <stdexcept> #include <vector> namespace mjolnir { class StructureTopology { public: typedef std::size_t chain_id_type; enum class connection_kind_type { bond, //! define chain contact, //! does not have effect on the chain (nonbonded contact) }; static constexpr chain_id_type uninitialized() noexcept { return std::numeric_limits<chain_id_type>::max(); } // each node corresponds to the particle having same idx in a system. struct node { node(): chain_id(uninitialized()) {} ~node() = default; node(node const&) = default; node(node&&) = default; node& operator=(node const&) = default; node& operator=(node&&) = default; std::size_t chain_id; std::vector<std::pair<std::size_t, connection_kind_type>> adjacents; }; public: StructureTopology() = default; ~StructureTopology() = default; StructureTopology(const StructureTopology&) = default; StructureTopology(StructureTopology&&) = default; StructureTopology& operator=(const StructureTopology&) = default; StructureTopology& operator=(StructureTopology&&) = default; StructureTopology(const std::size_t N): nodes_(N){}; bool empty() const noexcept {return nodes_.empty();} std::size_t size() const noexcept {return nodes_.size();} void resize(const std::size_t N) {nodes_.resize(N); return;} void add_connection(const std::size_t i, const std::size_t j, const connection_kind_type kind); void erase_connection(const std::size_t i, const std::size_t j); void erase_connection(const std::size_t i, const std::size_t j, const connection_kind_type kind); //! reset chain_id of all the particles void construct_chains(); bool has_connection(const std::size_t i, const std::size_t j); bool has_connection(const std::size_t i, const std::size_t j, const connection_kind_type kind); std::vector<std::size_t> list_adjacent_within(const std::size_t node_idx, const std::size_t dist ) const; std::vector<std::size_t> list_adjacent_within(const std::size_t node_idx, const std::size_t dist, const connection_kind_type kind) const; chain_id_type number_of_chains() const noexcept {return this->num_chains_;} chain_id_type chain_of(const std::size_t idx) const {return nodes_.at(idx).chain_id;} chain_id_type& chain_of(const std::size_t idx) {return nodes_.at(idx).chain_id;} private: void list_adjacent_within(const std::size_t node_idx, const std::size_t dist, std::vector<std::size_t>& out) const; void list_adjacent_within(const std::size_t node_idx, const std::size_t dist, const connection_kind_type kind, std::vector<std::size_t>& out ) const; private: std::size_t num_chains_; std::vector<node> nodes_; }; inline void StructureTopology::add_connection( const std::size_t i, const std::size_t j, connection_kind_type kind) { if(nodes_.size() <= std::max(i, j)) { throw_exception<std::out_of_range>( "mjolnir::StructureTopology::add_connection: size of nodes = ", nodes_.size(), ", i = ", i, ", j = ", j); } { const auto elem = std::make_pair(j, kind); auto& adjs = nodes_[i].adjacents; if(std::find(adjs.cbegin(), adjs.cend(), elem) == adjs.cend()) { adjs.push_back(elem); } } { const auto elem = std::make_pair(i, kind); auto& adjs = nodes_[j].adjacents; if(std::find(adjs.cbegin(), adjs.cend(), elem) == adjs.cend()) { adjs.push_back(elem); } } return ; } inline void StructureTopology::erase_connection( const std::size_t i, const std::size_t j) { if(nodes_.size() <= std::max(i, j)) { throw_exception<std::out_of_range>( "mjolnir::StructureTopology::erase_connection: size of nodes = ", nodes_.size(), ", i = ", i, ", j = ", j); } { auto& adjs = nodes_[i].adjacents; const auto found = std::find_if(adjs.begin(), adjs.end(), [j](const std::pair<std::size_t, connection_kind_type>& x){ return x.first == j; }); if(found != adjs.end()) { adjs.erase(found); } } { auto& adjs = nodes_[j].adjacents; const auto found = std::find_if(adjs.begin(), adjs.end(), [i](const std::pair<std::size_t, connection_kind_type>& x){ return x.first == i; }); if(found != adjs.end()) { adjs.erase(found); } } return ; } inline void StructureTopology::erase_connection( const std::size_t i, const std::size_t j, const connection_kind_type kind) { if(nodes_.size() <= std::max(i, j)) { throw_exception<std::out_of_range>( "mjolnir::StructureTopology::erase_connection: size of nodes = ", nodes_.size(), ", i = ", i, ", j = ", j); } { auto& adjs = nodes_[i].adjacents; const auto found = std::find( adjs.begin(), adjs.end(), std::make_pair(j, kind)); if(found != adjs.end()) { adjs.erase(found); } } { auto& adjs = nodes_[j].adjacents; const auto found = std::find( adjs.begin(), adjs.end(), std::make_pair(i, kind)); if(found != adjs.end()) { adjs.erase(found); } } return ; } inline bool StructureTopology::has_connection( const std::size_t i, const std::size_t j) { if(nodes_.size() <= std::max(i, j)) { throw_exception<std::out_of_range>( "mjolnir::StructureTopology::has_connection: size of nodes = ", nodes_.size(), ", i = ", i, ", j = ", j); } if(i == j) {return true;} // XXX const auto& adjs = nodes_[i].adjacents; const auto found = std::find_if(adjs.cbegin(), adjs.cend(), [j](const std::pair<std::size_t, connection_kind_type>& x){ return x.first == j; }); return found != adjs.cend(); } inline bool StructureTopology::has_connection( const std::size_t i, const std::size_t j, const connection_kind_type kind) { if(nodes_.size() <= std::max(i, j)) { throw_exception<std::out_of_range>( "mjolnir::StructureTopology::has_connection: size of nodes = ", nodes_.size(), ", i = ", i, ", j = ", j); } if(i == j) {return true;} // XXX const auto& adjs = nodes_[i].adjacents; const auto found = std::find(adjs.cbegin(), adjs.cend(), std::make_pair(j, kind)); return found != adjs.cend(); } inline std::vector<std::size_t> StructureTopology::list_adjacent_within( const std::size_t node_idx, const std::size_t dist) const { std::vector<std::size_t> retval = {node_idx}; if(dist == 0) {return retval;} for(auto ik : this->nodes_.at(node_idx).adjacents) { if(std::find(retval.cbegin(), retval.cend(), ik.first) != retval.cend()) { continue; // already assigned. ignore it. } retval.push_back(ik.first); this->list_adjacent_within(ik.first, dist - 1, retval); } std::sort(retval.begin(), retval.end()); const auto new_end = std::unique(retval.begin(), retval.end()); retval.erase(new_end, retval.end()); return retval; } inline std::vector<std::size_t> StructureTopology::list_adjacent_within( const std::size_t node_idx, const std::size_t dist, const connection_kind_type kind) const { std::vector<std::size_t> retval = {node_idx}; if(dist == 0) {return retval;} for(auto ik : this->nodes_.at(node_idx).adjacents) { if(ik.second != kind || std::find(retval.cbegin(), retval.cend(), ik.first) != retval.cend()) { continue; } retval.push_back(ik.first); this->list_adjacent_within(ik.first, dist - 1, kind, retval); } std::sort(retval.begin(), retval.end()); const auto new_end = std::unique(retval.begin(), retval.end()); retval.erase(new_end, retval.end()); return retval; } inline void StructureTopology::list_adjacent_within( const std::size_t node_idx, const std::size_t dist, std::vector<std::size_t>& out) const { if(dist == 0) { if(std::find(out.cbegin(), out.cend(), node_idx) != out.cend()) { out.push_back(node_idx); } return ; } for(auto ik : this->nodes_.at(node_idx).adjacents) { if(std::find(out.cbegin(), out.cend(), ik.first) != out.cend()) { continue; } out.push_back(ik.first); this->list_adjacent_within(ik.first, dist - 1, out); } return; } inline void StructureTopology::list_adjacent_within( const std::size_t node_idx, const std::size_t dist, const connection_kind_type kind, std::vector<std::size_t>& out) const { if(dist == 0) { if(std::find(out.cbegin(), out.cend(), node_idx) != out.cend()) { out.push_back(node_idx); } return; } for(auto ik : this->nodes_.at(node_idx).adjacents) { if(ik.second != kind || std::find(out.cbegin(), out.cend(), ik.first) != out.cend()) { continue; } out.push_back(ik.first); this->list_adjacent_within(ik.first, dist-1, kind, out); } return; } inline void StructureTopology::construct_chains() { if(this->nodes_.empty()){return;} for(auto& node : nodes_) { node.chain_id = uninitialized(); } std::size_t next_chain_id = 0; for(auto& node : nodes_) { // node.chain_id = uninitialized(); // already set as `uninit` for(const auto& edge : node.adjacents) { if(edge.second == connection_kind_type::contact) {continue;} node.chain_id = this->nodes_.at(edge.first).chain_id; if(node.chain_id != uninitialized()) {break;} } if(node.chain_id == uninitialized()) { node.chain_id = next_chain_id++; } } this->num_chains_ = ++next_chain_id; return; } } // mjolnir #endif// MJOLNIR_STRUCTURE_TOPOLOGY_H <|endoftext|>
<commit_before>#include <memory> #include <string> #include <vector> #include "warped.hpp" #include "tclap/ValueArg.h" WARPED_DEFINE_OBJECT_STATE_STRUCT(PingPongState) { unsigned int balls_created_; unsigned int balls_received_; unsigned int balls_sent_; }; class PingPongEvent : public warped::Event { public: PingPongEvent() = default; PingPongEvent(const std::string& receiver_name, unsigned int timestamp, const std::string& creator_name) : creator_name_(creator_name), receiver_name_(receiver_name), timestamp_(timestamp) {} const std::string& receiverName() const { return receiver_name_; } unsigned int timestamp() const { return timestamp_; } std::string creator_name_; std::string receiver_name_; unsigned int timestamp_; WARPED_REGISTER_SERIALIZABLE_MEMBERS(creator_name_, receiver_name_, timestamp_) }; WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(PingPongEvent) class PingPongObject : public warped::SimulationObject { public: PingPongObject(const std::string& name, const std::string& target_name, unsigned int balls_to_create) : SimulationObject(name), state_(), target_name_(target_name), balls_to_create_(balls_to_create) {} warped::ObjectState& getState() { return state_; } std::vector<std::unique_ptr<warped::Event>> createInitialEvents() { std::vector<std::unique_ptr<warped::Event>> v; if (balls_to_create_ > 0) { state_.balls_created_++; state_.balls_sent_++; v.emplace_back(new PingPongEvent {target_name_, 1, name_}); } return v; } std::vector<std::unique_ptr<warped::Event>> receiveEvent(const warped::Event& event) { std::vector<std::unique_ptr<warped::Event>> v; state_.balls_received_++; auto ping_event = static_cast<const PingPongEvent&>(event); std::string creator_name; if (ping_event.creator_name_ == name_) { if (state_.balls_created_ < balls_to_create_) { state_.balls_created_++; creator_name = name_; } else { return v; } } else { creator_name = ping_event.creator_name_; } auto timestamp = ping_event.timestamp_ + 1; v.emplace_back(new PingPongEvent {target_name_, timestamp, creator_name}); state_.balls_sent_++; return v; } PingPongState state_; const std::string target_name_; const unsigned int balls_to_create_; }; int main(int argc, char const* argv[]) { unsigned int num_balls = 10; unsigned int num_objects = 3; unsigned int num_balls_at_once = 1; TCLAP::ValueArg<unsigned int> num_balls_arg("b", "balls", "number of balls an object will create", false, num_balls, "int"); TCLAP::ValueArg<unsigned int> num_objects_arg("o", "objects", "total number of objects", false, num_objects, "int"); TCLAP::ValueArg<unsigned int> num_at_once_arg("a", "num-at-once", "number of objects that will create balls", false, num_balls_at_once, "int"); std::vector<TCLAP::Arg*> cmd_line_args = {&num_balls_arg, &num_objects_arg, &num_at_once_arg}; warped::Simulation simulation {"Ping Pong Simulation", argc, argv, cmd_line_args}; num_balls = num_balls_arg.getValue(); num_objects = num_objects_arg.getValue(); num_balls_at_once = num_at_once_arg.getValue(); std::vector<PingPongObject> objects; for (unsigned int i = 0; i < num_objects; ++i) { std::string name = std::string("Object ") + std::to_string(i + 1); std::string target = std::string("Object ") + std::to_string(((i + 1) % num_objects) + 1); unsigned int balls = i < num_balls_at_once ? num_balls : 0; objects.emplace_back(name, target, balls); } std::vector<warped::SimulationObject*> object_pointers; for (auto& o : objects) { object_pointers.push_back(&o); } simulation.simulate(object_pointers); for (auto& ob : objects) { std::cout << ob.name_ << " received " << ob.state_.balls_received_ << ", sent " << ob.state_.balls_sent_ << ", created " << ob.state_.balls_created_ << "\n"; } return 0; }<commit_msg>update the ping pong model for the new changes in warped kernel - event base class added to serializable members and unique event ptrs changed to shared_ptr<commit_after>#include <memory> #include <string> #include <vector> #include "warped.hpp" #include "tclap/ValueArg.h" WARPED_DEFINE_OBJECT_STATE_STRUCT(PingPongState) { unsigned int balls_created_; unsigned int balls_received_; unsigned int balls_sent_; }; class PingPongEvent : public warped::Event { public: PingPongEvent() = default; PingPongEvent(const std::string& receiver_name, unsigned int timestamp, const std::string& creator_name) : creator_name_(creator_name), receiver_name_(receiver_name), timestamp_(timestamp) {} const std::string& receiverName() const { return receiver_name_; } unsigned int timestamp() const { return timestamp_; } std::string creator_name_; std::string receiver_name_; unsigned int timestamp_; WARPED_REGISTER_SERIALIZABLE_MEMBERS(cereal::base_class<warped::Event>(this), creator_name_, receiver_name_, timestamp_) }; WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(PingPongEvent) class PingPongObject : public warped::SimulationObject { public: PingPongObject(const std::string& name, const std::string& target_name, unsigned int balls_to_create) : SimulationObject(name), state_(), target_name_(target_name), balls_to_create_(balls_to_create) {} warped::ObjectState& getState() { return state_; } std::vector<std::shared_ptr<warped::Event>> createInitialEvents() { std::vector<std::shared_ptr<warped::Event>> v; if (balls_to_create_ > 0) { state_.balls_created_++; state_.balls_sent_++; v.emplace_back(new PingPongEvent {target_name_, 1, name_}); } return v; } std::vector<std::shared_ptr<warped::Event>> receiveEvent(const warped::Event& event) { std::vector<std::shared_ptr<warped::Event>> v; state_.balls_received_++; auto ping_event = static_cast<const PingPongEvent&>(event); std::string creator_name; if (ping_event.creator_name_ == name_) { if (state_.balls_created_ < balls_to_create_) { state_.balls_created_++; creator_name = name_; } else { return v; } } else { creator_name = ping_event.creator_name_; } auto timestamp = ping_event.timestamp_ + 1; v.emplace_back(new PingPongEvent {target_name_, timestamp, creator_name}); state_.balls_sent_++; return v; } PingPongState state_; const std::string target_name_; const unsigned int balls_to_create_; }; int main(int argc, char const* argv[]) { unsigned int num_balls = 10; unsigned int num_objects = 3; unsigned int num_balls_at_once = 1; TCLAP::ValueArg<unsigned int> num_balls_arg("b", "balls", "number of balls an object will create", false, num_balls, "int"); TCLAP::ValueArg<unsigned int> num_objects_arg("o", "objects", "total number of objects", false, num_objects, "int"); TCLAP::ValueArg<unsigned int> num_at_once_arg("a", "num-at-once", "number of objects that will create balls", false, num_balls_at_once, "int"); std::vector<TCLAP::Arg*> cmd_line_args = {&num_balls_arg, &num_objects_arg, &num_at_once_arg}; warped::Simulation simulation {"Ping Pong Simulation", argc, argv, cmd_line_args}; num_balls = num_balls_arg.getValue(); num_objects = num_objects_arg.getValue(); num_balls_at_once = num_at_once_arg.getValue(); std::vector<PingPongObject> objects; for (unsigned int i = 0; i < num_objects; ++i) { std::string name = std::string("Object ") + std::to_string(i + 1); std::string target = std::string("Object ") + std::to_string(((i + 1) % num_objects) + 1); unsigned int balls = i < num_balls_at_once ? num_balls : 0; objects.emplace_back(name, target, balls); } std::vector<warped::SimulationObject*> object_pointers; for (auto& o : objects) { object_pointers.push_back(&o); } simulation.simulate(object_pointers); for (auto& ob : objects) { std::cout << ob.name_ << " received " << ob.state_.balls_received_ << ", sent " << ob.state_.balls_sent_ << ", created " << ob.state_.balls_created_ << "\n"; } return 0; } <|endoftext|>
<commit_before>#include "../includes/Scanner.h" #include "../../Automat/includes/Automat.h" #include "../../Symboltable/includes/Information.h" #include <error.h> #include <errno.h> Scanner::Scanner(char* argv, char* argv2) { if (argv == NULL) { argv = "../input/in.txt"; argv2 = "../output/out.txt"; } else if (argv2 == NULL) { argv2 = "out.txt"; } // TODO: maybe a small check if argv and argv2 are actually ending in .txt or something? buffer = new Buffer(argv); filedesc = open(argv2, O_WRONLY | O_CREAT|O_TRUNC, 0666); symTable = new Symboltable(); symTable->initSymbols(); automat = new Automat(); this->counter = 0; } void Scanner::writeInt(long int value, int filedesc){ char intString[10000]; int j = 0; sprintf(intString, "%ld", value); char * pointer = intString; while ( *(pointer+j) != '\0') { write(filedesc, pointer+j, 1); j++; } } char* Scanner::translateType(int type){ switch (type) { case 1: translatedType = "Identifier "; break; case 2: translatedType = "Integer "; break; case 7: translatedType = "PLUS "; break; case 8: translatedType = "MINUS "; break; case 9: translatedType = "COLON "; break; case 10: translatedType = "STAR "; break; case 11: translatedType = "SMALLER "; break; case 12: translatedType = "GREATER "; break; case 13: translatedType = "EQUALS "; break; case 14: translatedType = "ASSIGNMENT "; break; case 15: translatedType = "WEIRDTHING "; break; case 16: translatedType = "EXCLAMATION "; break; case 17: translatedType = "ANDAND "; break; case 18: translatedType = "SEMICOLON "; break; case 19: translatedType = "STARTBRACKETA "; break; case 20: translatedType = "ENDBRACKETA "; break; case 21: translatedType = "STARTBRACKETB "; break; case 22: translatedType = "ENDBRACKETB "; break; case 23: translatedType = "STARTBRACKETC "; break; case 24: translatedType = "ENDBRACKETC "; break; } return translatedType; } Token* Scanner::nextToken() { char c; int automat_result; Token* token; do { // Lesen bis zum Lexem c = buffer->getChar(); automat_result = automat->handle(c); if (c != '\0' && c != '\n' && c != ' ') { counter++; } // 0 -> Lexem to Token und Step Back // 20 -> Lexem to Token und kein Step Back // -1 -> Error Token // -99 -> End of File if (automat_result == 24) { counter = 0; } } while (automat_result != 0 && automat_result != 20 && automat_result != -1 && automat_result != -99); switch (automat_result) { case 0: { //TODO: Comment why we do this if (c != '\n' && c != ' ') { counter--; } write(filedesc, "Token ", 6); write(filedesc, translateType(automat->gettype()), 15); write(filedesc, " Line: ", 7); writeInt(automat->getline(), filedesc); write(filedesc, " Column: ", 9); writeInt(automat->getcolumn() - counter, filedesc); buffer->stepBack(1); // Integer if (automat->gettype() == 2) { buffer->stepBack(counter); char number[counter]; for (size_t i = 0; i < counter; i++) { number[i] = buffer->getChar(); } long value = strtol(number, NULL, 10); if (errno == ERANGE) { error(0, ERANGE, "LINE: %d Column: %d", automat->getline(), automat->getcolumn() - counter); errno = 0; // TODO: CHECK WHAT TYPE ERROR IS token = new Token(Token::ERROR, automat->getline(), automat->getcolumn() - counter); } token = new Token(Token::INTEGER, automat->getline(), automat->getcolumn() - counter, value); write(filedesc, " ", 1); write(filedesc, number, counter); }else{ // Alles neben Integer buffer->stepBack(counter); char word[counter + 1]; for (size_t i = 0; i < counter; i++) { word[i] = buffer->getChar(); } word[counter] = '\0'; Information* myInformation = new Information(word); // Identifier => in Symboltabelle eintragen if (automat->gettype() == 1) { myInformation->setType(Token::IDENTIFIER); } Key* myKey = symTable->insert(myInformation); Information* info = symTable->lookup(myKey); // Get Token Type from symTable --> information token = new Token(info->getType(), automat->getline(), automat->getcolumn() - counter, info); write(filedesc, " ", 1); write(filedesc, word, counter); } write(filedesc, "\n", 1); counter = 0; } break; case 20: { // write chars into token.... buffer->stepBack(counter); char word[counter + 1]; for (size_t i = 0; i < counter; i++) { word[i] = buffer->getChar(); } word[counter] = '\0'; Information* myInformation = new Information(word); Key* myKey = symTable->insert(myInformation); Information* info = symTable->lookup(myKey); token = new Token(info->getType(), automat->getline(), automat->getcolumn() - counter, info); write(filedesc, "Token ", 6); write(filedesc, translateType(automat->gettype()), 15); write(filedesc, " Line: ", 7); writeInt(automat->getline(), filedesc); write(filedesc, " Column: ", 9); writeInt(automat->getcolumn() - counter, filedesc); write(filedesc, "\n", 1); counter = 0; } break; case -1: { fprintf(stderr, "Error: Type: %d Line: %d Column: %d \n", automat->gettype(), automat->getline(), automat->getcolumn() - counter); // write error lexem into token buffer->stepBack(counter); char word[counter + 1]; for (size_t i = 0; i < counter; i++) { word[i] = buffer->getChar(); } word[counter] = '\0'; Information* myInformation = new Information(word); token = new Token(Token::ERROR, automat->getline(), automat->getcolumn() - counter, myInformation); counter = 0; } break; case -99: { cout << "End of Party. Good Night, sleep well ;)"; cout << '\n'; token = NULL; } break; default: { cout << "Unexpected Error. Exiting..."; cout << '\n'; token = NULL; } } return token; } Scanner::~Scanner() { // TODO Auto-generated destructor stub close(filedesc); } <commit_msg>refactor Scanner<commit_after>#include "../includes/Scanner.h" #include "../../Automat/includes/Automat.h" #include "../../Symboltable/includes/Information.h" #include <error.h> #include <errno.h> Scanner::Scanner(char* argv, char* argv2) { if (argv == NULL) { argv = "../input/in.txt"; argv2 = "../output/out.txt"; } else if (argv2 == NULL) { argv2 = "out.txt"; } buffer = new Buffer(argv); filedesc = open(argv2, O_WRONLY | O_CREAT|O_TRUNC, 0666); symTable = new Symboltable(); symTable->initSymbols(); automat = new Automat(); this->counter = 0; } void Scanner::writeInt(long int value, int filedesc){ char intString[10000]; int j = 0; sprintf(intString, "%ld", value); char * pointer = intString; while ( *(pointer+j) != '\0') { write(filedesc, pointer+j, 1); j++; } } char* Scanner::translateType(int type){ switch (type) { case 1: translatedType = "Identifier "; break; case 2: translatedType = "Integer "; break; case 7: translatedType = "PLUS "; break; case 8: translatedType = "MINUS "; break; case 9: translatedType = "COLON "; break; case 10: translatedType = "STAR "; break; case 11: translatedType = "SMALLER "; break; case 12: translatedType = "GREATER "; break; case 13: translatedType = "EQUALS "; break; case 14: translatedType = "ASSIGNMENT "; break; case 15: translatedType = "WEIRDTHING "; break; case 16: translatedType = "EXCLAMATION "; break; case 17: translatedType = "ANDAND "; break; case 18: translatedType = "SEMICOLON "; break; case 19: translatedType = "STARTBRACKETA "; break; case 20: translatedType = "ENDBRACKETA "; break; case 21: translatedType = "STARTBRACKETB "; break; case 22: translatedType = "ENDBRACKETB "; break; case 23: translatedType = "STARTBRACKETC "; break; case 24: translatedType = "ENDBRACKETC "; break; } return translatedType; } Token* Scanner::nextToken() { char c; int automat_result; Token* token; do { // Lesen bis zum Lexem c = buffer->getChar(); automat_result = automat->handle(c); if (c != '\0' && c != '\n' && c != ' ') { counter++; } // 0 -> Lexem to Token und Step Back // 20 -> Lexem to Token und kein Step Back // -1 -> Error Token // -99 -> End of File if (automat_result == 24) { counter = 0; } } while (automat_result != 0 && automat_result != 20 && automat_result != -1 && automat_result != -99); switch (automat_result) { case 0: { //TODO: Comment why we do this if (c != '\n' && c != ' ') { counter--; } write(filedesc, "Token ", 6); write(filedesc, translateType(automat->gettype()), 15); write(filedesc, " Line: ", 7); writeInt(automat->getline(), filedesc); write(filedesc, " Column: ", 9); writeInt(automat->getcolumn() - counter, filedesc); buffer->stepBack(1); // Integer if (automat->gettype() == 2) { buffer->stepBack(counter); char number[counter]; for (size_t i = 0; i < counter; i++) { number[i] = buffer->getChar(); } long value = strtol(number, NULL, 10); if (errno == ERANGE) { error(0, ERANGE, "LINE: %d Column: %d", automat->getline(), automat->getcolumn() - counter); errno = 0; // TODO: CHECK WHAT TYPE ERROR IS token = new Token(Token::ERROR, automat->getline(), automat->getcolumn() - counter); } token = new Token(Token::INTEGER, automat->getline(), automat->getcolumn() - counter, value); write(filedesc, " ", 1); write(filedesc, number, counter); }else{ // Alles neben Integer buffer->stepBack(counter); char word[counter + 1]; for (size_t i = 0; i < counter; i++) { word[i] = buffer->getChar(); } word[counter] = '\0'; Information* myInformation = new Information(word); // Identifier => in Symboltabelle eintragen if (automat->gettype() == 1) { myInformation->setType(Token::IDENTIFIER); } Key* myKey = symTable->insert(myInformation); Information* info = symTable->lookup(myKey); // Get Token Type from symTable --> information token = new Token(info->getType(), automat->getline(), automat->getcolumn() - counter, info); write(filedesc, " ", 1); write(filedesc, word, counter); } write(filedesc, "\n", 1); counter = 0; } break; case 20: { // write chars into token.... buffer->stepBack(counter); char word[counter + 1]; for (size_t i = 0; i < counter; i++) { word[i] = buffer->getChar(); } word[counter] = '\0'; Information* myInformation = new Information(word); Key* myKey = symTable->insert(myInformation); Information* info = symTable->lookup(myKey); token = new Token(info->getType(), automat->getline(), automat->getcolumn() - counter, info); write(filedesc, "Token ", 6); write(filedesc, translateType(automat->gettype()), 15); write(filedesc, " Line: ", 7); writeInt(automat->getline(), filedesc); write(filedesc, " Column: ", 9); writeInt(automat->getcolumn() - counter, filedesc); write(filedesc, "\n", 1); counter = 0; } break; case -1: { fprintf(stderr, "Error: Type: %d Line: %d Column: %d \n", automat->gettype(), automat->getline(), automat->getcolumn() - counter); // write error lexem into token buffer->stepBack(counter); char word[counter + 1]; for (size_t i = 0; i < counter; i++) { word[i] = buffer->getChar(); } word[counter] = '\0'; Information* myInformation = new Information(word); token = new Token(Token::ERROR, automat->getline(), automat->getcolumn() - counter, myInformation); counter = 0; } break; case -99: { cout << "End of Party. Good Night, sleep well ;)"; cout << '\n'; token = NULL; } break; default: { cout << "Unexpected Error. Exiting..."; cout << '\n'; token = NULL; } } return token; } Scanner::~Scanner() { // TODO Auto-generated destructor stub close(filedesc); } <|endoftext|>
<commit_before>#include "can/canread.h" #include <stdlib.h> #include "util/log.h" #include "util/timer.h" #define MS_PER_SECOND 1000 using openxc::util::bitfield::getBitField; namespace time = openxc::util::time; const char* openxc::can::read::ID_FIELD_NAME = "id"; const char* openxc::can::read::DATA_FIELD_NAME = "data"; const char* openxc::can::read::NAME_FIELD_NAME = "name"; const char* openxc::can::read::VALUE_FIELD_NAME = "value"; const char* openxc::can::read::EVENT_FIELD_NAME = "event"; /* Private: Serialize the root JSON object to a string (ending with a newline) * and send it to the pipeline. * * root - The JSON object to send. * pipeline - The pipeline to send on. */ void sendJSON(cJSON* root, Pipeline* pipeline) { char* message = cJSON_PrintUnformatted(root); sendMessage(pipeline, (uint8_t*) message, strlen(message)); cJSON_Delete(root); free(message); } /* Private: Combine the given name and value into a JSON object (conforming to * the OpenXC standard) and send it out to the pipeline. * * name - The value for the name field of the OpenXC message. * value - The numerical, string or booelan for the value field of the OpenXC * message. * event - (Optional) The event for the event field of the OpenXC message. * pipeline - The pipeline to send on. */ void sendJSONMessage(const char* name, cJSON* value, cJSON* event, Pipeline* pipeline) { using openxc::can::read::NAME_FIELD_NAME; using openxc::can::read::VALUE_FIELD_NAME; using openxc::can::read::EVENT_FIELD_NAME; cJSON *root = cJSON_CreateObject(); cJSON_AddStringToObject(root, NAME_FIELD_NAME, name); cJSON_AddItemToObject(root, VALUE_FIELD_NAME, value); if(event != NULL) { cJSON_AddItemToObject(root, EVENT_FIELD_NAME, event); } sendJSON(root, pipeline); } /* Private: Return the period in ms given the frequency in hertz. */ float frequencyToPeriod(float frequency) { return 1 / frequency * MS_PER_SECOND; } float openxc::can::read::preTranslate(CanSignal* signal, uint64_t data, bool* send) { float value = decodeSignal(signal, data); float timeSinceSend = time::systemTimeMs() - signal->lastSendTime; if(!signal->received || signal->maxFrequency == 0 || timeSinceSend >= frequencyToPeriod(signal->maxFrequency) || (value != signal->lastValue && signal->forceSendChanged)) { if(send && (!signal->received || signal->sendSame || value != signal->lastValue)) { signal->received = true; } else { *send = false; } signal->lastSendTime = time::systemTimeMs(); } else { *send = false; } return value; } void openxc::can::read::postTranslate(CanSignal* signal, float value) { signal->lastValue = value; } float openxc::can::read::decodeSignal(CanSignal* signal, uint64_t data) { uint64_t rawValue = getBitField(data, signal->bitPosition, signal->bitSize, true); return rawValue * signal->factor + signal->offset; } float openxc::can::read::passthroughHandler(CanSignal* signal, CanSignal* signals, int signalCount, float value, bool* send) { return value; } bool openxc::can::read::booleanHandler(CanSignal* signal, CanSignal* signals, int signalCount, float value, bool* send) { return value == 0.0 ? false : true; } float openxc::can::read::ignoreHandler(CanSignal* signal, CanSignal* signals, int signalCount, float value, bool* send) { *send = false; return value; } const char* openxc::can::read::stateHandler(CanSignal* signal, CanSignal* signals, int signalCount, float value, bool* send) { CanSignalState* signalState = lookupSignalState(value, signal, signals, signalCount); if(signalState != NULL) { return signalState->name; } debug("No signal state found for value %d", value); *send = false; return NULL; } void openxc::can::read::sendNumericalMessage(const char* name, float value, Pipeline* pipeline) { sendJSONMessage(name, cJSON_CreateNumber(value), NULL, pipeline); } void openxc::can::read::sendBooleanMessage(const char* name, bool value, Pipeline* pipeline) { sendJSONMessage(name, cJSON_CreateBool(value), NULL, pipeline); } void openxc::can::read::sendStringMessage(const char* name, const char* value, Pipeline* pipeline) { sendJSONMessage(name, cJSON_CreateString(value), NULL, pipeline); } void openxc::can::read::sendEventedFloatMessage(const char* name, const char* value, float event, Pipeline* pipeline) { sendJSONMessage(name, cJSON_CreateString(value), cJSON_CreateNumber(event), pipeline); } void openxc::can::read::sendEventedBooleanMessage(const char* name, const char* value, bool event, Pipeline* pipeline) { sendJSONMessage(name, cJSON_CreateString(value), cJSON_CreateBool(event), pipeline); } void openxc::can::read::sendEventedStringMessage(const char* name, const char* value, const char* event, Pipeline* pipeline) { sendJSONMessage(name, cJSON_CreateString(value), cJSON_CreateString(event), pipeline); } void openxc::can::read::passthroughMessage(Pipeline* pipeline, int id, uint64_t data) { cJSON *root = cJSON_CreateObject(); cJSON_AddNumberToObject(root, ID_FIELD_NAME, id); char encodedData[67]; union { uint64_t whole; uint8_t bytes[8]; } combined; combined.whole = data; sprintf(encodedData, "0x%02x%02x%02x%02x%02x%02x%02x%02x", combined.bytes[0], combined.bytes[1], combined.bytes[2], combined.bytes[3], combined.bytes[4], combined.bytes[5], combined.bytes[6], combined.bytes[7]); cJSON_AddStringToObject(root, DATA_FIELD_NAME, encodedData); sendJSON(root, pipeline); } void openxc::can::read::translateSignal(Pipeline* pipeline, CanSignal* signal, uint64_t data, float (*handler)(CanSignal*, CanSignal*, int, float, bool*), CanSignal* signals, int signalCount) { bool send = true; float value = preTranslate(signal, data, &send); float processedValue = handler(signal, signals, signalCount, value, &send); if(send) { sendNumericalMessage(signal->genericName, processedValue, pipeline); } postTranslate(signal, value); } void openxc::can::read::translateSignal(Pipeline* pipeline, CanSignal* signal, uint64_t data, const char* (*handler)(CanSignal*, CanSignal*, int, float, bool*), CanSignal* signals, int signalCount) { bool send = true; float value = preTranslate(signal, data, &send); const char* stringValue = handler(signal, signals, signalCount, value, &send); if(stringValue == NULL) { debug("No valid string returned from handler for %s", signal->genericName); } else if(send) { sendStringMessage(signal->genericName, stringValue, pipeline); } postTranslate(signal, value); } void openxc::can::read::translateSignal(Pipeline* pipeline, CanSignal* signal, uint64_t data, bool (*handler)(CanSignal*, CanSignal*, int, float, bool*), CanSignal* signals, int signalCount) { bool send = true; float value = preTranslate(signal, data, &send); bool booleanValue = handler(signal, signals, signalCount, value, &send); if(send) { sendBooleanMessage(signal->genericName, booleanValue, pipeline); } postTranslate(signal, value); } void openxc::can::read::translateSignal(Pipeline* pipeline, CanSignal* signal, uint64_t data, CanSignal* signals, int signalCount) { translateSignal(pipeline, signal, data, passthroughHandler, signals, signalCount); } <commit_msg>Silence noisy log output when states are not matched.<commit_after>#include "can/canread.h" #include <stdlib.h> #include "util/log.h" #include "util/timer.h" #define MS_PER_SECOND 1000 using openxc::util::bitfield::getBitField; namespace time = openxc::util::time; const char* openxc::can::read::ID_FIELD_NAME = "id"; const char* openxc::can::read::DATA_FIELD_NAME = "data"; const char* openxc::can::read::NAME_FIELD_NAME = "name"; const char* openxc::can::read::VALUE_FIELD_NAME = "value"; const char* openxc::can::read::EVENT_FIELD_NAME = "event"; /* Private: Serialize the root JSON object to a string (ending with a newline) * and send it to the pipeline. * * root - The JSON object to send. * pipeline - The pipeline to send on. */ void sendJSON(cJSON* root, Pipeline* pipeline) { char* message = cJSON_PrintUnformatted(root); sendMessage(pipeline, (uint8_t*) message, strlen(message)); cJSON_Delete(root); free(message); } /* Private: Combine the given name and value into a JSON object (conforming to * the OpenXC standard) and send it out to the pipeline. * * name - The value for the name field of the OpenXC message. * value - The numerical, string or booelan for the value field of the OpenXC * message. * event - (Optional) The event for the event field of the OpenXC message. * pipeline - The pipeline to send on. */ void sendJSONMessage(const char* name, cJSON* value, cJSON* event, Pipeline* pipeline) { using openxc::can::read::NAME_FIELD_NAME; using openxc::can::read::VALUE_FIELD_NAME; using openxc::can::read::EVENT_FIELD_NAME; cJSON *root = cJSON_CreateObject(); cJSON_AddStringToObject(root, NAME_FIELD_NAME, name); cJSON_AddItemToObject(root, VALUE_FIELD_NAME, value); if(event != NULL) { cJSON_AddItemToObject(root, EVENT_FIELD_NAME, event); } sendJSON(root, pipeline); } /* Private: Return the period in ms given the frequency in hertz. */ float frequencyToPeriod(float frequency) { return 1 / frequency * MS_PER_SECOND; } float openxc::can::read::preTranslate(CanSignal* signal, uint64_t data, bool* send) { float value = decodeSignal(signal, data); float timeSinceSend = time::systemTimeMs() - signal->lastSendTime; if(!signal->received || signal->maxFrequency == 0 || timeSinceSend >= frequencyToPeriod(signal->maxFrequency) || (value != signal->lastValue && signal->forceSendChanged)) { if(send && (!signal->received || signal->sendSame || value != signal->lastValue)) { signal->received = true; } else { *send = false; } signal->lastSendTime = time::systemTimeMs(); } else { *send = false; } return value; } void openxc::can::read::postTranslate(CanSignal* signal, float value) { signal->lastValue = value; } float openxc::can::read::decodeSignal(CanSignal* signal, uint64_t data) { uint64_t rawValue = getBitField(data, signal->bitPosition, signal->bitSize, true); return rawValue * signal->factor + signal->offset; } float openxc::can::read::passthroughHandler(CanSignal* signal, CanSignal* signals, int signalCount, float value, bool* send) { return value; } bool openxc::can::read::booleanHandler(CanSignal* signal, CanSignal* signals, int signalCount, float value, bool* send) { return value == 0.0 ? false : true; } float openxc::can::read::ignoreHandler(CanSignal* signal, CanSignal* signals, int signalCount, float value, bool* send) { *send = false; return value; } const char* openxc::can::read::stateHandler(CanSignal* signal, CanSignal* signals, int signalCount, float value, bool* send) { CanSignalState* signalState = lookupSignalState(value, signal, signals, signalCount); if(signalState != NULL) { return signalState->name; } *send = false; return NULL; } void openxc::can::read::sendNumericalMessage(const char* name, float value, Pipeline* pipeline) { sendJSONMessage(name, cJSON_CreateNumber(value), NULL, pipeline); } void openxc::can::read::sendBooleanMessage(const char* name, bool value, Pipeline* pipeline) { sendJSONMessage(name, cJSON_CreateBool(value), NULL, pipeline); } void openxc::can::read::sendStringMessage(const char* name, const char* value, Pipeline* pipeline) { sendJSONMessage(name, cJSON_CreateString(value), NULL, pipeline); } void openxc::can::read::sendEventedFloatMessage(const char* name, const char* value, float event, Pipeline* pipeline) { sendJSONMessage(name, cJSON_CreateString(value), cJSON_CreateNumber(event), pipeline); } void openxc::can::read::sendEventedBooleanMessage(const char* name, const char* value, bool event, Pipeline* pipeline) { sendJSONMessage(name, cJSON_CreateString(value), cJSON_CreateBool(event), pipeline); } void openxc::can::read::sendEventedStringMessage(const char* name, const char* value, const char* event, Pipeline* pipeline) { sendJSONMessage(name, cJSON_CreateString(value), cJSON_CreateString(event), pipeline); } void openxc::can::read::passthroughMessage(Pipeline* pipeline, int id, uint64_t data) { cJSON *root = cJSON_CreateObject(); cJSON_AddNumberToObject(root, ID_FIELD_NAME, id); char encodedData[67]; union { uint64_t whole; uint8_t bytes[8]; } combined; combined.whole = data; sprintf(encodedData, "0x%02x%02x%02x%02x%02x%02x%02x%02x", combined.bytes[0], combined.bytes[1], combined.bytes[2], combined.bytes[3], combined.bytes[4], combined.bytes[5], combined.bytes[6], combined.bytes[7]); cJSON_AddStringToObject(root, DATA_FIELD_NAME, encodedData); sendJSON(root, pipeline); } void openxc::can::read::translateSignal(Pipeline* pipeline, CanSignal* signal, uint64_t data, float (*handler)(CanSignal*, CanSignal*, int, float, bool*), CanSignal* signals, int signalCount) { bool send = true; float value = preTranslate(signal, data, &send); float processedValue = handler(signal, signals, signalCount, value, &send); if(send) { sendNumericalMessage(signal->genericName, processedValue, pipeline); } postTranslate(signal, value); } void openxc::can::read::translateSignal(Pipeline* pipeline, CanSignal* signal, uint64_t data, const char* (*handler)(CanSignal*, CanSignal*, int, float, bool*), CanSignal* signals, int signalCount) { bool send = true; float value = preTranslate(signal, data, &send); const char* stringValue = handler(signal, signals, signalCount, value, &send); if(stringValue != NULL && send) { sendStringMessage(signal->genericName, stringValue, pipeline); } postTranslate(signal, value); } void openxc::can::read::translateSignal(Pipeline* pipeline, CanSignal* signal, uint64_t data, bool (*handler)(CanSignal*, CanSignal*, int, float, bool*), CanSignal* signals, int signalCount) { bool send = true; float value = preTranslate(signal, data, &send); bool booleanValue = handler(signal, signals, signalCount, value, &send); if(send) { sendBooleanMessage(signal->genericName, booleanValue, pipeline); } postTranslate(signal, value); } void openxc::can::read::translateSignal(Pipeline* pipeline, CanSignal* signal, uint64_t data, CanSignal* signals, int signalCount) { translateSignal(pipeline, signal, data, passthroughHandler, signals, signalCount); } <|endoftext|>
<commit_before>/* Copyright (c) 2012 Stanford University * Copyright (c) 2015 Diego Ongaro * * Permission to use, copy, modify, and 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(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <string.h> #include "build/Protocol/Client.pb.h" #include "Core/Time.h" #include "RPC/Buffer.h" #include "RPC/ProtoBuf.h" #include "RPC/ServerRPC.h" #include "Server/RaftConsensus.h" #include "Server/ClientService.h" #include "Server/Globals.h" #include "Server/StateMachine.h" namespace LogCabin { namespace Server { ClientService::ClientService(Globals& globals) : globals(globals) { } ClientService::~ClientService() { } void ClientService::handleRPC(RPC::ServerRPC rpc) { using Protocol::Client::OpCode; // Call the appropriate RPC handler based on the request's opCode. switch (rpc.getOpCode()) { case OpCode::GET_SERVER_STATS: getServerStats(std::move(rpc)); break; case OpCode::GET_SUPPORTED_RPC_VERSIONS: getSupportedRPCVersions(std::move(rpc)); break; case OpCode::GET_CONFIGURATION: getConfiguration(std::move(rpc)); break; case OpCode::SET_CONFIGURATION: setConfiguration(std::move(rpc)); break; case OpCode::OPEN_SESSION: openSession(std::move(rpc)); break; case OpCode::READ_ONLY_TREE: readOnlyTreeRPC(std::move(rpc)); break; case OpCode::READ_WRITE_TREE: readWriteTreeRPC(std::move(rpc)); break; default: rpc.rejectInvalidRequest(); } } std::string ClientService::getName() const { return "ClientService"; } /** * Place this at the top of each RPC handler. Afterwards, 'request' will refer * to the protocol buffer for the request with all required fields set. * 'response' will be an empty protocol buffer for you to fill in the response. */ #define PRELUDE(rpcClass) \ Protocol::Client::rpcClass::Request request; \ Protocol::Client::rpcClass::Response response; \ if (!rpc.getRequest(request)) \ return; ////////// RPC handlers ////////// void ClientService::getServerStats(RPC::ServerRPC rpc) { PRELUDE(GetServerStats); *response.mutable_server_stats() = globals.serverStats.getCurrent(); rpc.reply(response); } void ClientService::getSupportedRPCVersions(RPC::ServerRPC rpc) { PRELUDE(GetSupportedRPCVersions); response.set_min_version(1); response.set_max_version(1); rpc.reply(response); } typedef RaftConsensus::ClientResult Result; typedef Protocol::Client::Command Command; typedef Protocol::Client::CommandResponse CommandResponse; std::pair<Result, uint64_t> ClientService::submit(RPC::ServerRPC& rpc, const google::protobuf::Message& command) { // TODO(ongaro): Switch from string to binary format. This is probably // really slow to serialize. std::string cmdStr = Core::ProtoBuf::dumpString(command); std::pair<Result, uint64_t> result = globals.raft->replicate(cmdStr); if (result.first == Result::RETRY || result.first == Result::NOT_LEADER) { Protocol::Client::Error error; error.set_error_code(Protocol::Client::Error::NOT_LEADER); std::string leaderHint = globals.raft->getLeaderHint(); if (!leaderHint.empty()) error.set_leader_hint(leaderHint); rpc.returnError(error); } return result; } Result ClientService::catchUpStateMachine(RPC::ServerRPC& rpc) { std::pair<Result, uint64_t> result = globals.raft->getLastCommittedId(); if (result.first == Result::RETRY || result.first == Result::NOT_LEADER) { Protocol::Client::Error error; error.set_error_code(Protocol::Client::Error::NOT_LEADER); std::string leaderHint = globals.raft->getLeaderHint(); if (!leaderHint.empty()) error.set_leader_hint(leaderHint); rpc.returnError(error); return result.first; } globals.stateMachine->wait(result.second); return result.first; } bool ClientService::getResponse(RPC::ServerRPC& rpc, uint64_t entryId, const Protocol::Client::ExactlyOnceRPCInfo& rpcInfo, Protocol::Client::CommandResponse& response) { globals.stateMachine->wait(entryId); bool ok = globals.stateMachine->getResponse(rpcInfo, response); if (!ok) { Protocol::Client::Error error; error.set_error_code(Protocol::Client::Error::SESSION_EXPIRED); rpc.returnError(error); return false; } return true; } void ClientService::openSession(RPC::ServerRPC rpc) { PRELUDE(OpenSession); Command command; command.set_nanoseconds_since_epoch(Core::Time::getTimeNanos()); *command.mutable_open_session() = request; std::pair<Result, uint64_t> result = submit(rpc, command); if (result.first != Result::SUCCESS) return; response.set_client_id(result.second); rpc.reply(response); } void ClientService::getConfiguration(RPC::ServerRPC rpc) { PRELUDE(GetConfiguration); Protocol::Raft::SimpleConfiguration configuration; uint64_t id; Result result = globals.raft->getConfiguration(configuration, id); if (result == Result::RETRY || result == Result::NOT_LEADER) { Protocol::Client::Error error; error.set_error_code(Protocol::Client::Error::NOT_LEADER); std::string leaderHint = globals.raft->getLeaderHint(); if (!leaderHint.empty()) error.set_leader_hint(leaderHint); rpc.returnError(error); return; } response.set_id(id); for (auto it = configuration.servers().begin(); it != configuration.servers().end(); ++it) { Protocol::Client::Server* server = response.add_servers(); server->set_server_id(it->server_id()); server->set_address(it->address()); } rpc.reply(response); } void ClientService::setConfiguration(RPC::ServerRPC rpc) { PRELUDE(SetConfiguration); Protocol::Raft::SimpleConfiguration newConfiguration; for (auto it = request.new_servers().begin(); it != request.new_servers().end(); ++it) { Protocol::Raft::Server* s = newConfiguration.add_servers(); s->set_server_id(it->server_id()); s->set_address(it->address()); } Result result = globals.raft->setConfiguration( request.old_id(), newConfiguration); if (result == Result::SUCCESS) { response.mutable_ok(); } else if (result == Result::RETRY || result == Result::NOT_LEADER) { Protocol::Client::Error error; error.set_error_code(Protocol::Client::Error::NOT_LEADER); std::string leaderHint = globals.raft->getLeaderHint(); if (!leaderHint.empty()) error.set_leader_hint(leaderHint); rpc.returnError(error); return; } else if (result == Result::FAIL) { // TODO(ongaro): can't distinguish changed from bad response.mutable_configuration_changed(); } rpc.reply(response); } void ClientService::readOnlyTreeRPC(RPC::ServerRPC rpc) { PRELUDE(ReadOnlyTree); if (catchUpStateMachine(rpc) != Result::SUCCESS) return; globals.stateMachine->readOnlyTreeRPC(request, response); rpc.reply(response); } void ClientService::readWriteTreeRPC(RPC::ServerRPC rpc) { PRELUDE(ReadWriteTree); Command command; command.set_nanoseconds_since_epoch(Core::Time::getTimeNanos()); *command.mutable_tree() = request; std::pair<Result, uint64_t> result = submit(rpc, command); if (result.first != Result::SUCCESS) return; CommandResponse commandResponse; if (!getResponse(rpc, result.second, request.exactly_once(), commandResponse)) { return; } rpc.reply(commandResponse.tree()); } } // namespace LogCabin::Server } // namespace LogCabin <commit_msg>Close #3: ClientService shoud log on bad opcode<commit_after>/* Copyright (c) 2012 Stanford University * Copyright (c) 2015 Diego Ongaro * * Permission to use, copy, modify, and 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(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <string.h> #include "build/Protocol/Client.pb.h" #include "Core/Time.h" #include "RPC/Buffer.h" #include "RPC/ProtoBuf.h" #include "RPC/ServerRPC.h" #include "Server/RaftConsensus.h" #include "Server/ClientService.h" #include "Server/Globals.h" #include "Server/StateMachine.h" namespace LogCabin { namespace Server { ClientService::ClientService(Globals& globals) : globals(globals) { } ClientService::~ClientService() { } void ClientService::handleRPC(RPC::ServerRPC rpc) { using Protocol::Client::OpCode; // Call the appropriate RPC handler based on the request's opCode. switch (rpc.getOpCode()) { case OpCode::GET_SERVER_STATS: getServerStats(std::move(rpc)); break; case OpCode::GET_SUPPORTED_RPC_VERSIONS: getSupportedRPCVersions(std::move(rpc)); break; case OpCode::GET_CONFIGURATION: getConfiguration(std::move(rpc)); break; case OpCode::SET_CONFIGURATION: setConfiguration(std::move(rpc)); break; case OpCode::OPEN_SESSION: openSession(std::move(rpc)); break; case OpCode::READ_ONLY_TREE: readOnlyTreeRPC(std::move(rpc)); break; case OpCode::READ_WRITE_TREE: readWriteTreeRPC(std::move(rpc)); break; default: WARNING("Received RPC request with unknown opcode %u: " "rejecting it as invalid request", rpc.getOpCode()); rpc.rejectInvalidRequest(); } } std::string ClientService::getName() const { return "ClientService"; } /** * Place this at the top of each RPC handler. Afterwards, 'request' will refer * to the protocol buffer for the request with all required fields set. * 'response' will be an empty protocol buffer for you to fill in the response. */ #define PRELUDE(rpcClass) \ Protocol::Client::rpcClass::Request request; \ Protocol::Client::rpcClass::Response response; \ if (!rpc.getRequest(request)) \ return; ////////// RPC handlers ////////// void ClientService::getServerStats(RPC::ServerRPC rpc) { PRELUDE(GetServerStats); *response.mutable_server_stats() = globals.serverStats.getCurrent(); rpc.reply(response); } void ClientService::getSupportedRPCVersions(RPC::ServerRPC rpc) { PRELUDE(GetSupportedRPCVersions); response.set_min_version(1); response.set_max_version(1); rpc.reply(response); } typedef RaftConsensus::ClientResult Result; typedef Protocol::Client::Command Command; typedef Protocol::Client::CommandResponse CommandResponse; std::pair<Result, uint64_t> ClientService::submit(RPC::ServerRPC& rpc, const google::protobuf::Message& command) { // TODO(ongaro): Switch from string to binary format. This is probably // really slow to serialize. std::string cmdStr = Core::ProtoBuf::dumpString(command); std::pair<Result, uint64_t> result = globals.raft->replicate(cmdStr); if (result.first == Result::RETRY || result.first == Result::NOT_LEADER) { Protocol::Client::Error error; error.set_error_code(Protocol::Client::Error::NOT_LEADER); std::string leaderHint = globals.raft->getLeaderHint(); if (!leaderHint.empty()) error.set_leader_hint(leaderHint); rpc.returnError(error); } return result; } Result ClientService::catchUpStateMachine(RPC::ServerRPC& rpc) { std::pair<Result, uint64_t> result = globals.raft->getLastCommittedId(); if (result.first == Result::RETRY || result.first == Result::NOT_LEADER) { Protocol::Client::Error error; error.set_error_code(Protocol::Client::Error::NOT_LEADER); std::string leaderHint = globals.raft->getLeaderHint(); if (!leaderHint.empty()) error.set_leader_hint(leaderHint); rpc.returnError(error); return result.first; } globals.stateMachine->wait(result.second); return result.first; } bool ClientService::getResponse(RPC::ServerRPC& rpc, uint64_t entryId, const Protocol::Client::ExactlyOnceRPCInfo& rpcInfo, Protocol::Client::CommandResponse& response) { globals.stateMachine->wait(entryId); bool ok = globals.stateMachine->getResponse(rpcInfo, response); if (!ok) { Protocol::Client::Error error; error.set_error_code(Protocol::Client::Error::SESSION_EXPIRED); rpc.returnError(error); return false; } return true; } void ClientService::openSession(RPC::ServerRPC rpc) { PRELUDE(OpenSession); Command command; command.set_nanoseconds_since_epoch(Core::Time::getTimeNanos()); *command.mutable_open_session() = request; std::pair<Result, uint64_t> result = submit(rpc, command); if (result.first != Result::SUCCESS) return; response.set_client_id(result.second); rpc.reply(response); } void ClientService::getConfiguration(RPC::ServerRPC rpc) { PRELUDE(GetConfiguration); Protocol::Raft::SimpleConfiguration configuration; uint64_t id; Result result = globals.raft->getConfiguration(configuration, id); if (result == Result::RETRY || result == Result::NOT_LEADER) { Protocol::Client::Error error; error.set_error_code(Protocol::Client::Error::NOT_LEADER); std::string leaderHint = globals.raft->getLeaderHint(); if (!leaderHint.empty()) error.set_leader_hint(leaderHint); rpc.returnError(error); return; } response.set_id(id); for (auto it = configuration.servers().begin(); it != configuration.servers().end(); ++it) { Protocol::Client::Server* server = response.add_servers(); server->set_server_id(it->server_id()); server->set_address(it->address()); } rpc.reply(response); } void ClientService::setConfiguration(RPC::ServerRPC rpc) { PRELUDE(SetConfiguration); Protocol::Raft::SimpleConfiguration newConfiguration; for (auto it = request.new_servers().begin(); it != request.new_servers().end(); ++it) { Protocol::Raft::Server* s = newConfiguration.add_servers(); s->set_server_id(it->server_id()); s->set_address(it->address()); } Result result = globals.raft->setConfiguration( request.old_id(), newConfiguration); if (result == Result::SUCCESS) { response.mutable_ok(); } else if (result == Result::RETRY || result == Result::NOT_LEADER) { Protocol::Client::Error error; error.set_error_code(Protocol::Client::Error::NOT_LEADER); std::string leaderHint = globals.raft->getLeaderHint(); if (!leaderHint.empty()) error.set_leader_hint(leaderHint); rpc.returnError(error); return; } else if (result == Result::FAIL) { // TODO(ongaro): can't distinguish changed from bad response.mutable_configuration_changed(); } rpc.reply(response); } void ClientService::readOnlyTreeRPC(RPC::ServerRPC rpc) { PRELUDE(ReadOnlyTree); if (catchUpStateMachine(rpc) != Result::SUCCESS) return; globals.stateMachine->readOnlyTreeRPC(request, response); rpc.reply(response); } void ClientService::readWriteTreeRPC(RPC::ServerRPC rpc) { PRELUDE(ReadWriteTree); Command command; command.set_nanoseconds_since_epoch(Core::Time::getTimeNanos()); *command.mutable_tree() = request; std::pair<Result, uint64_t> result = submit(rpc, command); if (result.first != Result::SUCCESS) return; CommandResponse commandResponse; if (!getResponse(rpc, result.second, request.exactly_once(), commandResponse)) { return; } rpc.reply(commandResponse.tree()); } } // namespace LogCabin::Server } // namespace LogCabin <|endoftext|>
<commit_before>#include "ofMain.h" #include "MiniFont.h" float pxToMm = 1. / 10.; float carWidth = 2600, tireWidth = 550, tireHeight = 180, tireSpacing = 845; float directionSize = 10000, triangleSide = 50000; float outerEllipseWidth = 4600, outerEllipseHeight = 3480; float innerEllipseWidth = 3840, innerEllipseHeight = 2720; float peopleRadius = 10; float offsetAmount = 600; class DraggableCircle { protected: bool selected; ofVec2f position; static int idCount; int id; public: DraggableCircle() :selected(false) { } virtual void setup() { id = idCount++; ofAddListener(ofEvents().mousePressed, this, &DraggableCircle::mousePressed); ofAddListener(ofEvents().mouseMoved, this, &DraggableCircle::mouseMoved); ofAddListener(ofEvents().mouseDragged, this, &DraggableCircle::mouseDragged); ofAddListener(ofEvents().draw, this, &DraggableCircle::draw); } bool getSelected() const { return selected; } ofVec2f& getPosition() { return position; } void mousePressed(ofMouseEventArgs& e) { mouseMoved(e); } void mouseMoved(ofMouseEventArgs& e) { selected = position.distance(e) < peopleRadius; } void mouseDragged(ofMouseEventArgs& e) { if(selected) { position.set(e); } } virtual void draw(ofEventArgs& e) { ofPushStyle(); ofFill(); ofSetColor(255); ofCircle(position, peopleRadius); if(selected) { ofSetColor(ofColor::red); ofNoFill(); ofCircle(position, peopleRadius * 2); } MiniFont::drawHighlight(ofToString(id), position); ofPopStyle(); } }; int DraggableCircle::idCount = 0; class Person : public DraggableCircle { public: float leftAngle, rightAngle; float startAngle, startTime; float pulseAngle; bool direction; Person() :leftAngle(0) ,rightAngle(0) ,startAngle(0) ,startTime(0), direction(false) { } virtual void setup(ofVec2f position) { DraggableCircle::setup(); this->position = position; ofAddListener(ofEvents().update, this, &Person::update); } void update(ofEventArgs& update) { float a = leftAngle, b = rightAngle; if(b < a) { b += 360; } pulseAngle = MAX(pulseAngle, leftAngle); pulseAngle = MIN(pulseAngle, rightAngle); } float getPulseAngle() { return pulseAngle; } ofVec2f getWorldPosition() const { return position - ofGetWindowSize() / 2; } float getAngle() const { return getWorldPosition().angle(ofVec2f(1, 0)); } }; bool operator < (const Person& a, const Person& b) { return a.getAngle() < b.getAngle(); } class ofApp : public ofBaseApp { public: vector<Person> people; void setup() { ofSetCircleResolution(64); ofSetLineWidth(2); MiniFont::setup(); people.resize(5); for(int i = 0; i < people.size(); i++) { people[i].setup(ofVec2f(ofRandomWidth(), ofRandomHeight())); } } void update() { ofSort(people); } void drawTriangle(ofVec2f center, ofVec2f p1, ofVec2f p2, float side) { p1 = center + (p1 - center).normalize() * side; p2 = center + (p2 - center).normalize() * side; ofTriangle(center, p1, p2); } void draw() { ofBackground(0); ofPushMatrix(); ofTranslate(ofGetWidth() / 2, ofGetHeight() / 2); ofScale(pxToMm, pxToMm); ofRotate(45); drawCar(); ofPopMatrix(); ofPushMatrix(); ofPushStyle(); ofSetColor(ofColor::cyan); ofTranslate(ofGetWidth() / 2, ofGetHeight() / 2); int n = people.size(); for(int i = 0; i < n; i++) { int inext = (i + 1) % n; float a = people[i].getAngle(); float b = people[inext].getAngle(); if(b < a) { b += 360; } float avg = (a + b) / 2; avg = fmodf(avg, 360); people[i].rightAngle = avg; people[inext].leftAngle = avg; ofLine(ofVec2f(100, 0).rotate(-avg), ofVec2f(300, 0).rotate(-avg)); } ofSetColor(ofColor::magenta); for(int i = 0; i < n; i++) { float theta = people[i].getPulseAngle(); ofLine(ofVec2f(150, 0).rotate(-theta), ofVec2f(250, 0).rotate(-theta)); } ofPopStyle(); ofPopMatrix(); MiniFont::drawHighlight(ofToString(mouseX) + " " + ofToString(mouseY), 10, 10); } void drawCar() { ofVec2f flt(-carWidth / 2 - tireWidth / 2, +tireSpacing - tireHeight), brt(carWidth / 2 - tireWidth / 2, -tireSpacing); ofVec2f topCenter = (flt + brt) / 2, topOffsetDirection = (brt - flt).normalize(); ofVec2f topSensorCenter = topCenter + topOffsetDirection * offsetAmount; ofVec2f topSensorDirection = topOffsetDirection.rotate(-90); ofVec2f flb(-carWidth / 2 + tireWidth / 2, +tireSpacing), brb(carWidth / 2 + tireWidth / 2, -tireSpacing + tireHeight); ofVec2f bottomCenter = (flb + brb) / 2, bottomOffsetDirection = (flb - brb).normalize(); ofVec2f bottomSensorCenter = bottomCenter + bottomOffsetDirection * offsetAmount; ofVec2f bottomSensorDirection = bottomOffsetDirection.rotate(-90); ofVec2f bl(+carWidth / 2 - tireWidth / 2, +tireSpacing); ofVec2f br(+carWidth / 2 + tireWidth / 2, +tireSpacing - tireHeight); ofVec2f tl(-carWidth / 2 - tireWidth / 2, -tireSpacing + tireHeight); ofVec2f tr(-carWidth / 2 + tireWidth / 2, -tireSpacing); ofPushStyle(); ofSetColor(ofColor::yellow); ofLine(bottomSensorCenter, bottomSensorCenter + bottomSensorDirection * directionSize); ofLine(topSensorCenter, topSensorCenter + topSensorDirection * directionSize); ofPopStyle(); ofPushStyle(); ofFill(); ofSetColor(ofColor::red, 64); drawTriangle(bottomSensorCenter, flb, bl, triangleSide); drawTriangle(bottomSensorCenter, brb, br, triangleSide); drawTriangle(topSensorCenter, flt, tl, triangleSide); drawTriangle(topSensorCenter, brt, tr, triangleSide); ofPopStyle(); ofPushStyle(); ofFill(); ofSetColor(255); ofCircle(topSensorCenter, 50); ofCircle(bottomSensorCenter, 50); ofPopStyle(); ofPushStyle(); ofSetColor(255, 128); ofNoFill(); ofEllipse(0, 0, outerEllipseWidth, outerEllipseHeight); // outer ofEllipse(0, 0, innerEllipseWidth, innerEllipseHeight); // inner ofSetRectMode(OF_RECTMODE_CENTER); ofRectRounded(0, 0, 4100, 1690, 300); ofRect(-carWidth / 2, +tireSpacing - tireHeight / 2, tireWidth, tireHeight); ofRect(+carWidth / 2, +tireSpacing - tireHeight / 2, tireWidth, tireHeight); ofRect(-carWidth / 2, -tireSpacing + tireHeight / 2, tireWidth, tireHeight); ofRect(+carWidth / 2, -tireSpacing + tireHeight / 2, tireWidth, tireHeight); ofPopStyle(); } }; int main( ){ ofSetupOpenGL(1280, 720, OF_WINDOW); ofRunApp(new ofApp()); }<commit_msg>almost have correct bounce<commit_after>#include "ofMain.h" #include "MiniFont.h" float pxToMm = 1. / 10.; float carWidth = 2600, tireWidth = 550, tireHeight = 180, tireSpacing = 845; float directionSize = 10000, triangleSide = 50000; float outerEllipseWidth = 4600, outerEllipseHeight = 3480; float innerEllipseWidth = 3840, innerEllipseHeight = 2720; float peopleRadius = 10; float offsetAmount = 600; class DraggableCircle { protected: bool selected; ofVec2f position; static int idCount; int id; public: DraggableCircle() :selected(false) { } virtual void setup() { id = idCount++; ofAddListener(ofEvents().mousePressed, this, &DraggableCircle::mousePressed); ofAddListener(ofEvents().mouseMoved, this, &DraggableCircle::mouseMoved); ofAddListener(ofEvents().mouseDragged, this, &DraggableCircle::mouseDragged); ofAddListener(ofEvents().draw, this, &DraggableCircle::draw); } bool getSelected() const { return selected; } ofVec2f& getPosition() { return position; } void mousePressed(ofMouseEventArgs& e) { mouseMoved(e); } void mouseMoved(ofMouseEventArgs& e) { selected = position.distance(e) < peopleRadius; } void mouseDragged(ofMouseEventArgs& e) { if(selected) { position.set(e); } } virtual void draw(ofEventArgs& e) { ofPushStyle(); ofFill(); ofSetColor(255); ofCircle(position, peopleRadius); if(selected) { ofSetColor(ofColor::red); ofNoFill(); ofCircle(position, peopleRadius * 2); } MiniFont::drawHighlight(ofToString(id), position); ofPopStyle(); } }; int DraggableCircle::idCount = 0; class HasAngle { public: virtual float getAngle() const = 0; ofVec2f getNormal() const { return ofVec2f(1, 0).rotate(getAngle()); } bool operator < (const HasAngle& other) const { return getAngle() < other.getAngle(); } }; class Person : public DraggableCircle, public HasAngle { public: float leftAngle, rightAngle; Person() :leftAngle(0) ,rightAngle(0) { } virtual void setup(ofVec2f position) { DraggableCircle::setup(); this->position = position; } ofVec2f getWorldPosition() const { return position - ofGetWindowSize() / 2; } virtual float getAngle() const { return ofVec2f(1, 0).angle(getWorldPosition()); } }; float ofWrapCenter(float x, float center, float range) { while(x + range < center) { x += range; } while(x - range > center) { x -= range; } return x; } float ofConstrainWrap(float x, float low, float high, float range) { //cout << "snapping " << x << " between " << low << " and " << high << endl; low = ofWrapCenter(low, x, range); high = ofWrapCenter(high, x, range); x = MAX(x, low); x = MIN(x, high); //cout << "snapped " << x << " between " << low << " and " << high << endl; return x; } class Pulse : public HasAngle { public: bool direction; float leftAngle, rightAngle; float startAngle, startTime; float pulseAngle; Pulse() :leftAngle(0) ,rightAngle(0) ,startAngle(0) ,startTime(0) ,direction(false) { } void setup(float angle) { pulseAngle = angle; ofAddListener(ofEvents().update, this, &Pulse::update); } void update(ofEventArgs& update) { //pulseAngle = ofConstrainWrap(pulseAngle, leftAngle, rightAngle, 360); } virtual float getAngle() const { return pulseAngle; } }; class ofApp : public ofBaseApp { public: vector<Person> people; vector<Pulse> pulses; void setup() { ofSetCircleResolution(64); ofSetLineWidth(2); MiniFont::setup(); people.resize(3); pulses.resize(3); for(int i = 0; i < people.size(); i++) { people[i].setup(ofVec2f(ofRandomWidth(), ofRandomHeight())); pulses[i].setup(people[i].getAngle()); } } void update() { ofSort(people); ofSort(pulses); int n = people.size(); for(int i = 0; i < n; i++) { int inext = (i + 1) % n; float a = people[i].getAngle(), b = people[inext].getAngle(); if(b < a) { b += 360; } float avg = (a + b) / 2; avg = fmodf(avg, 360); people[i].rightAngle = avg; people[inext].leftAngle = avg; } // try to determine the relationship between the pulses and people int bestOffset = 0; float bestDistance = 0; ofVec2f curPulse = pulses[0].getNormal(); for(int j = 0; j < n; j++) { ofVec2f curPerson = people[j].getNormal(); float distance = curPerson.distance(curPulse); if(j == 0 || distance < bestDistance) { bestDistance = distance; bestOffset = j; } } int personOffset = 0;//bestOffset; for(int i = 0; i < n; i++) { int personIndex = (i + personOffset) % n; pulses[i].leftAngle = people[personIndex].leftAngle; pulses[i].rightAngle = people[personIndex].rightAngle; float a = pulses[i].leftAngle, b = pulses[i].rightAngle; if(b < a) { b += 360; } float avg = (a + b) / 2; avg = fmodf(avg, 360); pulses[i].pulseAngle = avg; } } void drawTriangle(ofVec2f center, ofVec2f p1, ofVec2f p2, float side) { p1 = center + (p1 - center).normalize() * side; p2 = center + (p2 - center).normalize() * side; ofTriangle(center, p1, p2); } void draw() { ofBackground(0); ofPushMatrix(); ofTranslate(ofGetWidth() / 2, ofGetHeight() / 2); ofScale(pxToMm, pxToMm); ofRotate(45); drawCar(); ofPopMatrix(); ofPushMatrix(); ofPushStyle(); ofSetColor(ofColor::cyan); ofTranslate(ofGetWidth() / 2, ofGetHeight() / 2); int n = people.size(); for(int i = 0; i < n; i++) { ofVec2f normal(1, 0); normal.rotate(people[i].leftAngle); ofLine(100 * normal, 300 * normal); } for(int i = 0; i < n; i++) { ofVec2f curPulse = pulses[i].getNormal(); ofLine(curPulse * 90, ofVec2f(1, 0).rotate(pulses[i].leftAngle) * 90); ofLine(curPulse * 100, ofVec2f(1, 0).rotate(pulses[i].rightAngle) * 100); } ofSetColor(ofColor::magenta); for(int i = 0; i < n; i++) { ofVec2f normal = pulses[i].getNormal(); ofLine(150 * normal, 250 * normal); } ofPopStyle(); ofPopMatrix(); MiniFont::drawHighlight(ofToString(mouseX) + " " + ofToString(mouseY), 10, 10); } void drawCar() { ofVec2f flt(-carWidth / 2 - tireWidth / 2, +tireSpacing - tireHeight), brt(carWidth / 2 - tireWidth / 2, -tireSpacing); ofVec2f topCenter = (flt + brt) / 2, topOffsetDirection = (brt - flt).normalize(); ofVec2f topSensorCenter = topCenter + topOffsetDirection * offsetAmount; ofVec2f topSensorDirection = topOffsetDirection.rotate(-90); ofVec2f flb(-carWidth / 2 + tireWidth / 2, +tireSpacing), brb(carWidth / 2 + tireWidth / 2, -tireSpacing + tireHeight); ofVec2f bottomCenter = (flb + brb) / 2, bottomOffsetDirection = (flb - brb).normalize(); ofVec2f bottomSensorCenter = bottomCenter + bottomOffsetDirection * offsetAmount; ofVec2f bottomSensorDirection = bottomOffsetDirection.rotate(-90); ofVec2f bl(+carWidth / 2 - tireWidth / 2, +tireSpacing); ofVec2f br(+carWidth / 2 + tireWidth / 2, +tireSpacing - tireHeight); ofVec2f tl(-carWidth / 2 - tireWidth / 2, -tireSpacing + tireHeight); ofVec2f tr(-carWidth / 2 + tireWidth / 2, -tireSpacing); ofPushStyle(); ofSetColor(ofColor::yellow); ofLine(bottomSensorCenter, bottomSensorCenter + bottomSensorDirection * directionSize); ofLine(topSensorCenter, topSensorCenter + topSensorDirection * directionSize); ofPopStyle(); ofPushStyle(); ofFill(); ofSetColor(ofColor::red, 64); drawTriangle(bottomSensorCenter, flb, bl, triangleSide); drawTriangle(bottomSensorCenter, brb, br, triangleSide); drawTriangle(topSensorCenter, flt, tl, triangleSide); drawTriangle(topSensorCenter, brt, tr, triangleSide); ofPopStyle(); ofPushStyle(); ofFill(); ofSetColor(255); ofCircle(topSensorCenter, 50); ofCircle(bottomSensorCenter, 50); ofPopStyle(); ofPushStyle(); ofSetColor(255, 128); ofNoFill(); ofEllipse(0, 0, outerEllipseWidth, outerEllipseHeight); // outer ofEllipse(0, 0, innerEllipseWidth, innerEllipseHeight); // inner ofSetRectMode(OF_RECTMODE_CENTER); ofRectRounded(0, 0, 4100, 1690, 300); ofRect(-carWidth / 2, +tireSpacing - tireHeight / 2, tireWidth, tireHeight); ofRect(+carWidth / 2, +tireSpacing - tireHeight / 2, tireWidth, tireHeight); ofRect(-carWidth / 2, -tireSpacing + tireHeight / 2, tireWidth, tireHeight); ofRect(+carWidth / 2, -tireSpacing + tireHeight / 2, tireWidth, tireHeight); ofPopStyle(); } }; int main( ){ ofSetupOpenGL(1280, 720, OF_WINDOW); ofRunApp(new ofApp()); }<|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash 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 <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { 0x3210ce66, 0x3213747b, 0x1717ba83, 0x3210ce66, 0x3213747b, 0x1715cc22, 0xbc8e2769, 0x36f8e397, 0x2a793a5b, 0x3251c027, 0x05fe6003, 0xaf73c92c, 0xd035bf02, 0xc06f4182, 0xa2f32110, }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xbf; pchMessageStart[1] = 0x0c; pchMessageStart[2] = 0x6b; pchMessageStart[3] = 0xbd; vAlertPubKey = ParseHex("048240a8748a80a286b270ba126705ced4f2ce5a7847b3610ea3c06513150dade2a8512ed5ea86320824683fc0818f0ac019214973e677acd1244f6d0571fc5103"); nDefaultPort = 9999; nRPCPort = 9998; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // Dash starting difficulty is 1 / 2^12 nSubsidyHalvingInterval = 210000; // Genesis block const char* pszTimestamp = "Wired 09/Jan/2014 The Grand Experiment Goes Live: Overstock.com Is Now Accepting Bitcoins"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 50 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1390095618; genesis.nBits = 0x1e0ffff0; genesis.nNonce = 28917698; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x00000ffd590b1485b3caadc19b22e6379c733355108f107a430458cdf3407ab6")); assert(genesis.hashMerkleRoot == uint256("0xe0028eb9648db56b1ac77cf090b99048a8007e2bb64b68f092c03c7f56a662c7")); vSeeds.push_back(CDNSSeedData("dashpay.io", "dnsseed.dashpay.io")); vSeeds.push_back(CDNSSeedData("dash.qa", "dnsseed.dash.qa")); vSeeds.push_back(CDNSSeedData("masternode.io", "dnsseed.masternode.io")); base58Prefixes[PUBKEY_ADDRESS] = list_of( 76); // Dash addresses start with 'X' base58Prefixes[SCRIPT_ADDRESS] = list_of( 16); // Dash script addresses start with '7' base58Prefixes[SECRET_KEY] = list_of(204); // Dash private keys start with '7' or 'X' base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x02)(0xFE)(0x52)(0xF8); // Dash BIP32 pubkeys start with 'drkv' base58Prefixes[EXT_SECRET_KEY] = list_of(0x02)(0xFE)(0x52)(0xCC); // Dash BIP32 prvkeys start with 'drkp' base58Prefixes[EXT_COIN_TYPE] = list_of(0x80000005); // Dash BIP44 coin type is '5' // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. 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 (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xce; pchMessageStart[1] = 0xe2; pchMessageStart[2] = 0xca; pchMessageStart[3] = 0xff; vAlertPubKey = ParseHex("04517d8a699cb43d3938d7b24faaff7cda448ca4ea267723ba614784de661949bf632d6304316b244646dea079735b9a6fc4af804efb4752075b9fe2245e14e412"); nDefaultPort = 19999; nRPCPort = 19998; strDataDir = "testnet3"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1390666206; genesis.nNonce = 3861367235; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x00000bafbc94add76cb75e2ec92894837288a481e5c005f6563d91623bf8bc2c")); vFixedSeeds.clear(); vSeeds.clear(); vSeeds.push_back(CDNSSeedData("dashpay.io", "testnet-seed.dashpay.io")); vSeeds.push_back(CDNSSeedData("dash.qa", "testnet-seed.dash.qa")); vSeeds.push_back(CDNSSeedData("masternode.io", "test.dnsseed.masternode.io")); base58Prefixes[PUBKEY_ADDRESS] = list_of(139); // Testnet dash addresses start with 'x' or 'y' base58Prefixes[SCRIPT_ADDRESS] = list_of( 19); // Testnet dash script addresses start with '8' or '9' base58Prefixes[SECRET_KEY] = list_of(239); // Testnet private keys start with '9' or 'c' (Bitcoin defaults) base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x3a)(0x80)(0x61)(0xa0); // Testnet dash BIP32 pubkeys start with 'DRKV' base58Prefixes[EXT_SECRET_KEY] = list_of(0x3a)(0x80)(0x58)(0x37); // Testnet dash BIP32 prvkeys start with 'DRKP' base58Prefixes[EXT_COIN_TYPE] = list_of(0x80000001); // Testnet dash BIP44 coin type is '5' (All coin's testnet default) } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfc; pchMessageStart[1] = 0xc1; pchMessageStart[2] = 0xb7; pchMessageStart[3] = 0xdc; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1417713337; genesis.nBits = 0x207fffff; genesis.nNonce = 1096447; nDefaultPort = 19994; strDataDir = "regtest"; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e")); 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>changed seeders<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash 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 <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { 0x3210ce66, 0x3213747b, 0x1717ba83, 0x3210ce66, 0x3213747b, 0x1715cc22, 0xbc8e2769, 0x36f8e397, 0x2a793a5b, 0x3251c027, 0x05fe6003, 0xaf73c92c, 0xd035bf02, 0xc06f4182, 0xa2f32110, }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xbf; pchMessageStart[1] = 0x0c; pchMessageStart[2] = 0x6b; pchMessageStart[3] = 0xbd; vAlertPubKey = ParseHex("048240a8748a80a286b270ba126705ced4f2ce5a7847b3610ea3c06513150dade2a8512ed5ea86320824683fc0818f0ac019214973e677acd1244f6d0571fc5103"); nDefaultPort = 9999; nRPCPort = 9998; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // Dash starting difficulty is 1 / 2^12 nSubsidyHalvingInterval = 210000; // Genesis block const char* pszTimestamp = "Wired 09/Jan/2014 The Grand Experiment Goes Live: Overstock.com Is Now Accepting Bitcoins"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 50 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1390095618; genesis.nBits = 0x1e0ffff0; genesis.nNonce = 28917698; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x00000ffd590b1485b3caadc19b22e6379c733355108f107a430458cdf3407ab6")); assert(genesis.hashMerkleRoot == uint256("0xe0028eb9648db56b1ac77cf090b99048a8007e2bb64b68f092c03c7f56a662c7")); vSeeds.push_back(CDNSSeedData("masternode.io", "dnsseed.masternode.io")); vSeeds.push_back(CDNSSeedData("darkcoin.qa", "dnsseed.darkcoin.qa")); vSeeds.push_back(CDNSSeedData("darkcoin.io", "dnsseed.darkcoin.io")); base58Prefixes[PUBKEY_ADDRESS] = list_of( 76); // Dash addresses start with 'X' base58Prefixes[SCRIPT_ADDRESS] = list_of( 16); // Dash script addresses start with '7' base58Prefixes[SECRET_KEY] = list_of(204); // Dash private keys start with '7' or 'X' base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x02)(0xFE)(0x52)(0xF8); // Dash BIP32 pubkeys start with 'drkv' base58Prefixes[EXT_SECRET_KEY] = list_of(0x02)(0xFE)(0x52)(0xCC); // Dash BIP32 prvkeys start with 'drkp' base58Prefixes[EXT_COIN_TYPE] = list_of(0x80000005); // Dash BIP44 coin type is '5' // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. 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 (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xce; pchMessageStart[1] = 0xe2; pchMessageStart[2] = 0xca; pchMessageStart[3] = 0xff; vAlertPubKey = ParseHex("04517d8a699cb43d3938d7b24faaff7cda448ca4ea267723ba614784de661949bf632d6304316b244646dea079735b9a6fc4af804efb4752075b9fe2245e14e412"); nDefaultPort = 19999; nRPCPort = 19998; strDataDir = "testnet3"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1390666206; genesis.nNonce = 3861367235; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x00000bafbc94add76cb75e2ec92894837288a481e5c005f6563d91623bf8bc2c")); vFixedSeeds.clear(); vSeeds.clear(); /*vSeeds.push_back(CDNSSeedData("dashpay.io", "testnet-seed.dashpay.io")); vSeeds.push_back(CDNSSeedData("dash.qa", "testnet-seed.dash.qa")); *///legacy seeders vSeeds.push_back(CDNSSeedData("darkcoin.qa", "testnet-seed.darkcoin.qa")); vSeeds.push_back(CDNSSeedData("masternode.io", "test.dnsseed.masternode.io")); vSeeds.push_back(CDNSSeedData("darkcoin.io", "testnet-seed.darkcoin.io")); base58Prefixes[PUBKEY_ADDRESS] = list_of(139); // Testnet dash addresses start with 'x' or 'y' base58Prefixes[SCRIPT_ADDRESS] = list_of( 19); // Testnet dash script addresses start with '8' or '9' base58Prefixes[SECRET_KEY] = list_of(239); // Testnet private keys start with '9' or 'c' (Bitcoin defaults) base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x3a)(0x80)(0x61)(0xa0); // Testnet dash BIP32 pubkeys start with 'DRKV' base58Prefixes[EXT_SECRET_KEY] = list_of(0x3a)(0x80)(0x58)(0x37); // Testnet dash BIP32 prvkeys start with 'DRKP' base58Prefixes[EXT_COIN_TYPE] = list_of(0x80000001); // Testnet dash BIP44 coin type is '5' (All coin's testnet default) } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfc; pchMessageStart[1] = 0xc1; pchMessageStart[2] = 0xb7; pchMessageStart[3] = 0xdc; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1417713337; genesis.nBits = 0x207fffff; genesis.nNonce = 1096447; nDefaultPort = 19994; strDataDir = "regtest"; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e")); 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>// Copyright (c) 2010 Satoshi Nakamoto // 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 "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" // // Main network // // Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x18; pchMessageStart[1] = 0x2d; pchMessageStart[2] = 0x43; pchMessageStart[3] = 0xf3; vAlertPubKey = ParseHex("044153e2e67649872cc674f07e4a3dc1ae53dcd7aadc36bff5dba46ce0d41e551a780457a7b6656c83acc69496efed4b7d436351d07d726a2edc023a304e271872"); nDefaultPort = 15814; nRPCPort = 15815; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. // Genesis info: //Found Genesis, Nonce: 45707, Hash: 000007d69ba0f79b4823effb06b08663e2e4c51ed03aaeb547e2e0b83fd37b73 //Gensis Hash Merkle: 73513debc549137a47f2afb73173a2d2b4b0c13f57a57387ae3849a928e1e08d const char* pszTimestamp = "12 Feb 2017 Whitecoin switches to POSv3"; std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].SetEmpty(); CTransaction txNew(1, 1486939650, vin, vout, 0); genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1486939650; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 45707; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x000007d69ba0f79b4823effb06b08663e2e4c51ed03aaeb547e2e0b83fd37b73")); assert(genesis.hashMerkleRoot == uint256("0x73513debc549137a47f2afb73173a2d2b4b0c13f57a57387ae3849a928e1e08d")); vSeeds.push_back(CDNSSeedData("oizopower.nl", "dnsseed.oizopower.nl")); vSeeds.push_back(CDNSSeedData("dnsseed-cn", "dnsseed-cn.whitecoin.info")); vSeeds.push_back(CDNSSeedData("seed1", "seed1.oizopower.nl")); vSeeds.push_back(CDNSSeedData("seed2", "seed2.oizopower.nl")); vSeeds.push_back(CDNSSeedData("seed3", "seed3.oizopower.nl")); vSeeds.push_back(CDNSSeedData("xwcseeder", "xwcseeder.ftc-c.com")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 73); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 87); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 73+128); base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0x7F)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0x94)(0xED).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nLastPOWBlock = 10000; } 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. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x31; pchMessageStart[1] = 0x56; pchMessageStart[2] = 0x9c; pchMessageStart[3] = 0xe7; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16); vAlertPubKey = ParseHex("043693201c0fe5a136889b1036ce7aa2cc4ef7d9dfc06e049b73112744256ab446d753b5031aad5e353cb33417737e74159de7e70c3b07879eb14f98714a93d482"); nDefaultPort = 24070; nRPCPort = 24071; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 216178; hashGenesisBlock = genesis.GetHash(); //assert(hashGenesisBlock == uint256("0x0000724595fb3b9609d441cbfb9577615c292abf07d996d3edabc48de843642d")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 111); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 239); base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test)); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0x7b; pchMessageStart[1] = 0x92; pchMessageStart[2] = 0xb3; pchMessageStart[3] = 0xee; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1411111111; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 2; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 18444; strDataDir = "regtest"; //assert(hashGenesisBlock == uint256("0x523dda6d336047722cbaf1c5dce622298af791bac21b33bf6e2d5048b2a13e3d")); 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>Change vAlertPubKey<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // 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 "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" // // Main network // // Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x18; pchMessageStart[1] = 0x2d; pchMessageStart[2] = 0x43; pchMessageStart[3] = 0xf3; vAlertPubKey = ParseHex("04bf1c0874e989ca090e7eb5d5dd8a04224f2db5cc80d28a256ee676a33396f21622aacb06a9159eaf02ada44238f935f12dd35dad2f6f9075e325ee1219c88533"); nDefaultPort = 15814; nRPCPort = 15815; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. // Genesis info: //Found Genesis, Nonce: 45707, Hash: 000007d69ba0f79b4823effb06b08663e2e4c51ed03aaeb547e2e0b83fd37b73 //Gensis Hash Merkle: 73513debc549137a47f2afb73173a2d2b4b0c13f57a57387ae3849a928e1e08d const char* pszTimestamp = "12 Feb 2017 Whitecoin switches to POSv3"; std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].SetEmpty(); CTransaction txNew(1, 1486939650, vin, vout, 0); genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1486939650; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 45707; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x000007d69ba0f79b4823effb06b08663e2e4c51ed03aaeb547e2e0b83fd37b73")); assert(genesis.hashMerkleRoot == uint256("0x73513debc549137a47f2afb73173a2d2b4b0c13f57a57387ae3849a928e1e08d")); vSeeds.push_back(CDNSSeedData("oizopower.nl", "dnsseed.oizopower.nl")); vSeeds.push_back(CDNSSeedData("dnsseed-cn", "dnsseed-cn.whitecoin.info")); vSeeds.push_back(CDNSSeedData("seed1", "seed1.oizopower.nl")); vSeeds.push_back(CDNSSeedData("seed2", "seed2.oizopower.nl")); vSeeds.push_back(CDNSSeedData("seed3", "seed3.oizopower.nl")); vSeeds.push_back(CDNSSeedData("xwcseeder", "xwcseeder.ftc-c.com")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 73); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 87); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 73+128); base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0x7F)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0x94)(0xED).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nLastPOWBlock = 10000; } 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. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x31; pchMessageStart[1] = 0x56; pchMessageStart[2] = 0x9c; pchMessageStart[3] = 0xe7; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16); vAlertPubKey = ParseHex("043693201c0fe5a136889b1036ce7aa2cc4ef7d9dfc06e049b73112744256ab446d753b5031aad5e353cb33417737e74159de7e70c3b07879eb14f98714a93d482"); nDefaultPort = 24070; nRPCPort = 24071; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 216178; hashGenesisBlock = genesis.GetHash(); //assert(hashGenesisBlock == uint256("0x0000724595fb3b9609d441cbfb9577615c292abf07d996d3edabc48de843642d")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 111); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 239); base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test)); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0x7b; pchMessageStart[1] = 0x92; pchMessageStart[2] = 0xb3; pchMessageStart[3] = 0xee; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1411111111; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 2; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 18444; strDataDir = "regtest"; //assert(hashGenesisBlock == uint256("0x523dda6d336047722cbaf1c5dce622298af791bac21b33bf6e2d5048b2a13e3d")); 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>// Copyright (c) 2010 Satoshi Nakamoto // 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 "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" // // Main network // // Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xa2; pchMessageStart[1] = 0x3d; pchMessageStart[2] = 0x2f; pchMessageStart[3] = 0xf3; vAlertPubKey = ParseHex("04d244288a8c6ebbf491443ebfa1207275d71cb009f201c118b00cf8e77641c7f1e63e330ba909842c009af375c0f5c1c7368e8d7e2066168c40ce3cb629cf212f"); nDefaultPort = 23230; nRPCPort = 23231; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); const char* pszTimestamp = "China Buying Sparks Bitcoin Surge"; std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].nValue = 1 * COIN; vout[0].SetEmpty(); CTransaction txNew(1, 1465182929, vin, vout, 0); genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1465182929; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 213507; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x000007156509515339b8d7ba056ca7c448a3c2be2eade1bc80440b3b4350bab5")); assert(genesis.hashMerkleRoot == uint256("0x5e0da22e4c99ae49acabe6ca26cee59b3192787bc71cc3c4c1ec1726c21d0db4")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,33); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,137); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,161); base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,40); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >(); vSeeds.push_back(CDNSSeedData("seeds", "nodes.exclusivecoin.pw")); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nPoolMaxTransactions = 3; //strSporkKey = "046f78dcf911fbd61910136f7f0f8d90578f68d0b3ac973b5040fb7afb501b5939f39b108b0569dca71488f5bbf498d92e4d1194f6f941307ffd95f75e76869f0e"; //strMasternodePaymentsPubKey = "046f78dcf911fbd61910136f7f0f8d90578f68d0b3ac973b5040fb7afb501b5939f39b108b0569dca71488f5bbf498d92e4d1194f6f941307ffd95f75e76869f0e"; strDarksendPoolDummyAddress = "TcYM6qFTC9i1CHb4GoHTQchF7Z2Qru73gv"; nLastPOWBlock = 6000; nPOSStartBlock = 3001; } 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. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x2f; pchMessageStart[1] = 0xca; pchMessageStart[2] = 0x4d; pchMessageStart[3] = 0x3e; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16); vAlertPubKey = ParseHex("04cc24ab003c828cdd9cf4db2ebbde8e1cecb3bbfa8b3127fcb9dd9b84d44112080827ed7c49a648af9fe788ff42e316aee665879c553f099e55299d6b54edd7e0"); nDefaultPort = 27170; nRPCPort = 27171; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nBits = 520159231; genesis.nNonce = 35117; vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,33); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,137); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,161); base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,40); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; 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; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <commit_msg>change DarksendPoolDummyAddress<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // 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 "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" // // Main network // // Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xa2; pchMessageStart[1] = 0x3d; pchMessageStart[2] = 0x2f; pchMessageStart[3] = 0xf3; vAlertPubKey = ParseHex("04d244288a8c6ebbf491443ebfa1207275d71cb009f201c118b00cf8e77641c7f1e63e330ba909842c009af375c0f5c1c7368e8d7e2066168c40ce3cb629cf212f"); nDefaultPort = 23230; nRPCPort = 23231; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); const char* pszTimestamp = "China Buying Sparks Bitcoin Surge"; std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].nValue = 1 * COIN; vout[0].SetEmpty(); CTransaction txNew(1, 1465182929, vin, vout, 0); genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1465182929; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 213507; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x000007156509515339b8d7ba056ca7c448a3c2be2eade1bc80440b3b4350bab5")); assert(genesis.hashMerkleRoot == uint256("0x5e0da22e4c99ae49acabe6ca26cee59b3192787bc71cc3c4c1ec1726c21d0db4")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,33); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,137); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,161); base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,40); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >(); vSeeds.push_back(CDNSSeedData("seeds", "nodes.exclusivecoin.pw")); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nPoolMaxTransactions = 3; //strSporkKey = "046f78dcf911fbd61910136f7f0f8d90578f68d0b3ac973b5040fb7afb501b5939f39b108b0569dca71488f5bbf498d92e4d1194f6f941307ffd95f75e76869f0e"; //strMasternodePaymentsPubKey = "046f78dcf911fbd61910136f7f0f8d90578f68d0b3ac973b5040fb7afb501b5939f39b108b0569dca71488f5bbf498d92e4d1194f6f941307ffd95f75e76869f0e"; strDarksendPoolDummyAddress = "EV3pnsexEyBtNUMut8dV1KRNfHtJf6YbmR"; nLastPOWBlock = 6000; nPOSStartBlock = 3001; } 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. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x2f; pchMessageStart[1] = 0xca; pchMessageStart[2] = 0x4d; pchMessageStart[3] = 0x3e; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16); vAlertPubKey = ParseHex("04cc24ab003c828cdd9cf4db2ebbde8e1cecb3bbfa8b3127fcb9dd9b84d44112080827ed7c49a648af9fe788ff42e316aee665879c553f099e55299d6b54edd7e0"); nDefaultPort = 27170; nRPCPort = 27171; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nBits = 520159231; genesis.nNonce = 35117; vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,33); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,137); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,161); base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,40); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; 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; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // 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 "assert.h" #include "chainparams.h" #include "core.h" #include "protocol.h" #include "util.h" // // Main network // unsigned int pnSeed[] = { 0x12346678 }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xb5; pchMessageStart[2] = 0xdf; pchMessageStart[3] = 0xdb; vAlertPubKey = ParseHex("043a314ee36a4796baeb6a488e38f62c45f2dc69331cfc49b2a867fa95467f4e3aac21a03bebe8f977d7f29fb4487a5947a98cc38d3c48dd04c261899f4384fd6c"); nDefaultPort = 15660; nRPCPort = 15661; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); nSubsidyHalvingInterval = 172800; // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. const char* pszTimestamp = "9/05/2013 @ 5:10PM: Virgin Galactic's SpaceShipTwo Succeeds In Second Rocket-Powered Flight."; 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 = 128 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678aaaa0fe55482f1967f1a67130b7105cd6a000e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1378495795; genesis.nBits = 0x1e0fffff; genesis.nNonce = 285333548; //// debug print hashGenesisBlock = genesis.GetHash(); /* while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()) { if (++genesis.nNonce==0) break; hashGenesisBlock = genesis.GetHash(); } */ printf("hashGenesisBlock = %s\n", hashGenesisBlock.ToString().c_str()); printf("hashMerkleRoot = %s\n", genesis.hashMerkleRoot.ToString().c_str()); printf("%x\n", bnProofOfWorkLimit.GetCompact()); genesis.print(); assert(hashGenesisBlock == uint256("0x000000e02a1a674989cc114a50fea6d46e9fd18620129418589364b75f3292ac")); assert(genesis.hashMerkleRoot == uint256("0xaee5ee4074090a7564fd6a51e16a9e0ef4656d14fe4798be3e13d085cbbf7577")); vSeeds.push_back(CDNSSeedData("bitcoin.sipa.be", "seed.bitcoin.sipa.be")); vSeeds.push_back(CDNSSeedData("bluematt.me", "dnsseed.bluematt.me")); vSeeds.push_back(CDNSSeedData("xf2.org", "bitseed.xf2.org")); vSeeds.push_back(CDNSSeedData("dashjr.org", "dnsseed.bitcoin.dashjr.org")); base58Prefixes[PUBKEY_ADDRESS] = 127; base58Prefixes[SCRIPT_ADDRESS] = 9; base58Prefixes[SECRET_KEY] = 224; // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' const int64 nTwoDays = 2 * 24 * 60 * 60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays; 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 (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0x05; pchMessageStart[1] = 0xfe; pchMessageStart[2] = 0xa9; pchMessageStart[3] = 0x01; vAlertPubKey = ParseHex("043a314ee36a4796baeb6a488e38f62c45f2dc69331cfc49b2a867fa95467f4e3aac21a03bebe8f977d7f29fb4487a5947a98cc38d3c48dd04c261899f4384fd6c"); nDefaultPort = 28077; nRPCPort = 28078; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1378495253; genesis.nNonce = 0; //// debug print hashGenesisBlock = genesis.GetHash(); //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){ // if (++genesis.nNonce==0) break; // hashGenesisBlock = genesis.GetHash(); //} printf("hashGenesisBlock-testnet = %s\n", hashGenesisBlock.ToString().c_str()); printf("hashMerkleRoot-testnet = %s\n", genesis.hashMerkleRoot.ToString().c_str()); genesis.print(); assert(hashGenesisBlock == uint256("0xa6e7e253dd963065e18841baf1f2b3617ff4ee144132e51f86d16096f55f0040")); vFixedSeeds.clear(); vSeeds.clear(); // vSeeds.push_back(CDNSSeedData("tigercoin.test", "test.tigercoin.org")); base58Prefixes[PUBKEY_ADDRESS] = 77; base58Prefixes[SCRIPT_ADDRESS] = 177; base58Prefixes[SECRET_KEY] = 239; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0x0f; pchMessageStart[2] = 0xa5; pchMessageStart[3] = 0x5a; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1396688602; genesis.nBits = 0x207fffff; genesis.nNonce = 3; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 28444; strDataDir = "regtest"; //// debug print hashGenesisBlock = genesis.GetHash(); //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){ // if (++genesis.nNonce==0) break; // hashGenesisBlock = genesis.GetHash(); //} printf("%s\n", hashGenesisBlock.ToString().c_str()); printf("%s\n", genesis.hashMerkleRoot.ToString().c_str()); genesis.print(); // assert(hashGenesisBlock == uint256("0x13d8d31dde96874006da503dd2b63fa68c698dc823334359e417aa3a92f80433")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. base58Prefixes[PUBKEY_ADDRESS] = 0; base58Prefixes[SCRIPT_ADDRESS] = 5; base58Prefixes[SECRET_KEY] = 128; } 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>New test chain<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // 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 "assert.h" #include "chainparams.h" #include "core.h" #include "protocol.h" #include "util.h" // // Main network // unsigned int pnSeed[] = { 0x12346678 }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xb5; pchMessageStart[2] = 0xdf; pchMessageStart[3] = 0xdb; vAlertPubKey = ParseHex("043a314ee36a4796baeb6a488e38f62c45f2dc69331cfc49b2a867fa95467f4e3aac21a03bebe8f977d7f29fb4487a5947a98cc38d3c48dd04c261899f4384fd6c"); nDefaultPort = 15660; nRPCPort = 15661; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); nSubsidyHalvingInterval = 172800; // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. const char* pszTimestamp = "9/05/2013 @ 5:10PM: Virgin Galactic's SpaceShipTwo Succeeds In Second Rocket-Powered Flight."; 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 = 128 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678aaaa0fe55482f1967f1a67130b7105cd6a000e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1378495795; genesis.nBits = 0x1e0fffff; genesis.nNonce = 285333548; //// debug print hashGenesisBlock = genesis.GetHash(); /* while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()) { if (++genesis.nNonce==0) break; hashGenesisBlock = genesis.GetHash(); } */ printf("hashGenesisBlock = %s\n", hashGenesisBlock.ToString().c_str()); printf("hashMerkleRoot = %s\n", genesis.hashMerkleRoot.ToString().c_str()); printf("%x\n", bnProofOfWorkLimit.GetCompact()); genesis.print(); assert(hashGenesisBlock == uint256("0x000000e02a1a674989cc114a50fea6d46e9fd18620129418589364b75f3292ac")); assert(genesis.hashMerkleRoot == uint256("0xaee5ee4074090a7564fd6a51e16a9e0ef4656d14fe4798be3e13d085cbbf7577")); vSeeds.push_back(CDNSSeedData("bitcoin.sipa.be", "seed.bitcoin.sipa.be")); vSeeds.push_back(CDNSSeedData("bluematt.me", "dnsseed.bluematt.me")); vSeeds.push_back(CDNSSeedData("xf2.org", "bitseed.xf2.org")); vSeeds.push_back(CDNSSeedData("dashjr.org", "dnsseed.bitcoin.dashjr.org")); base58Prefixes[PUBKEY_ADDRESS] = 127; base58Prefixes[SCRIPT_ADDRESS] = 9; base58Prefixes[SECRET_KEY] = 224; // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' const int64 nTwoDays = 2 * 24 * 60 * 60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays; 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 (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0x05; pchMessageStart[1] = 0xfe; pchMessageStart[2] = 0xa9; pchMessageStart[3] = 0x01; vAlertPubKey = ParseHex("043a314ee36a4796baeb6a488e38f62c45f2dc69331cfc49b2a867fa95467f4e3aac21a03bebe8f977d7f29fb4487a5947a98cc38d3c48dd04c261899f4384fd6c"); nDefaultPort = 28077; nRPCPort = 28078; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1439972967; genesis.nNonce = 4224972; //// debug print hashGenesisBlock = genesis.GetHash(); //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){ // if (++genesis.nNonce==0) break; // hashGenesisBlock = genesis.GetHash(); //} printf("hashGenesisBlock-testnet = %s\n", hashGenesisBlock.ToString().c_str()); printf("hashMerkleRoot-testnet = %s\n", genesis.hashMerkleRoot.ToString().c_str()); genesis.print(); assert(hashGenesisBlock == uint256("0xa6e7e253dd963065e18841baf1f2b3617ff4ee144132e51f86d16096f55f0040")); vFixedSeeds.clear(); vSeeds.clear(); // vSeeds.push_back(CDNSSeedData("tigercoin.test", "test.tigercoin.org")); base58Prefixes[PUBKEY_ADDRESS] = 77; base58Prefixes[SCRIPT_ADDRESS] = 177; base58Prefixes[SECRET_KEY] = 239; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0x0f; pchMessageStart[2] = 0xa5; pchMessageStart[3] = 0x5a; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1396688602; genesis.nBits = 0x207fffff; genesis.nNonce = 3; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 28444; strDataDir = "regtest"; //// debug print hashGenesisBlock = genesis.GetHash(); //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){ // if (++genesis.nNonce==0) break; // hashGenesisBlock = genesis.GetHash(); //} printf("%s\n", hashGenesisBlock.ToString().c_str()); printf("%s\n", genesis.hashMerkleRoot.ToString().c_str()); genesis.print(); // assert(hashGenesisBlock == uint256("0x13d8d31dde96874006da503dd2b63fa68c698dc823334359e417aa3a92f80433")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. base58Prefixes[PUBKEY_ADDRESS] = 0; base58Prefixes[SCRIPT_ADDRESS] = 5; base58Prefixes[SECRET_KEY] = 128; } 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>// Copyright (c) 2010 Satoshi Nakamoto // 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 "assert.h" #include "chainparams.h" #include "core.h" #include "protocol.h" #include "util.h" // // Main network // unsigned int pnSeed[] = { 0x12345678 }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0xa3; pchMessageStart[1] = 0xd2; pchMessageStart[2] = 0x7a; pchMessageStart[3] = 0x03; vAlertPubKey = ParseHex("04c5788ca1e268a7474763fa965210b6fa6b04a45f52d21056c62fb19a2de991aa15aa1d1c516f34d2a0016f51a87959c89f51a148db30c839f71bc525dde8c480"); nDefaultPort = 21994; nRPCPort = 21995; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); nSubsidyHalvingInterval = 175320; // 6 months // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. const char* pszTimestamp = "11-03-14 - Malaysia says missing jet made it far from last reported position"; 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 = 64 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04becedf6ebadd4596964d890f677f8d2e74fdcc313c6416434384a66d6d8758d1c92de272dc6713e4a81d98841dfdfdc95e204ba915447d2fe9313435c78af3e8") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1390078220; genesis.nBits = 0x1e0fffff; genesis.nNonce = 2099366979; //// debug print hashGenesisBlock = genesis.GetHash(); //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){ // if (++genesis.nNonce==0) break; // hashGenesisBlock = genesis.GetHash(); //} printf("%s\n", hashGenesisBlock.ToString().c_str()); printf("%s\n", genesis.hashMerkleRoot.ToString().c_str()); printf("%x\n", bnProofOfWorkLimit.GetCompact()); genesis.print(); assert(hashGenesisBlock == uint256("0x00000f639db5734b2b861ef8dbccc33aebd7de44d13de000a12d093bcc866c64")); assert(genesis.hashMerkleRoot == uint256("0xfa6ef9872494fa9662cf0fecf8c0135a6932e76d7a8764e1155207f3205c7c88")); vSeeds.push_back(CDNSSeedData("piastrecoin.no-ip.biz", "piastrecoin.no-ip.biz")); vSeeds.push_back(CDNSSeedData("piastrecoin.zapto.org", "piastrecoin.zapto.org")); base58Prefixes[PUBKEY_ADDRESS] = 38; base58Prefixes[SCRIPT_ADDRESS] = 4; base58Prefixes[SECRET_KEY] = 28 + 128; // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' const int64 nTwoDays = 2 * 24 * 60 * 60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays; 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 (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0xfb; pchMessageStart[1] = 0xc2; pchMessageStart[2] = 0x11; pchMessageStart[3] = 0x02; vAlertPubKey = ParseHex("040d3090a194381599d0f53f89ec60b9ec77f0e7b61978ef445142c8a4f1e154ca3441a5e46e12910540352edbd8af43fc1ee1da9a935c1c252fe7426c323d3d32"); nDefaultPort = 21994; nRPCPort = 21995; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1388868139; genesis.nNonce = 423087994; //// debug print hashGenesisBlock = genesis.GetHash(); //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){ // if (++genesis.nNonce==0) break; // hashGenesisBlock = genesis.GetHash(); //} printf("%s\n", hashGenesisBlock.ToString().c_str()); printf("%s\n", genesis.hashMerkleRoot.ToString().c_str()); genesis.print(); assert(hashGenesisBlock == uint256("0x0000082f5939c2154dbcba35f784530d12e9d72472fcfaf29674ea312cdf4c83")); vFixedSeeds.clear(); vSeeds.clear(); // vSeeds.push_back(CDNSSeedData("testseed1.piastrecoin.org", "testseed1.piastrecoin.org")); base58Prefixes[PUBKEY_ADDRESS] = 80; base58Prefixes[SCRIPT_ADDRESS] = 44; base58Prefixes[SECRET_KEY] = 80 + 128; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfc; pchMessageStart[1] = 0x1f; pchMessageStart[2] = 0xc3; pchMessageStart[3] = 0x56; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1296688602; genesis.nBits = 0x207fffff; genesis.nNonce = 3; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 18444; strDataDir = "regtest"; //// debug print hashGenesisBlock = genesis.GetHash(); //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){ // if (++genesis.nNonce==0) break; // hashGenesisBlock = genesis.GetHash(); // } // printf("%s\n", hashGenesisBlock.ToString().c_str()); // printf("%s\n", genesis.hashMerkleRoot.ToString().c_str()); // genesis.print(); // assert(hashGenesisBlock == uint256("0x13d8d31dde96874006da503dd2b63fa68c698dc823334359e417aa3a92f80433")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. base58Prefixes[PUBKEY_ADDRESS] = 0; base58Prefixes[SCRIPT_ADDRESS] = 5; base58Prefixes[SECRET_KEY] = 128; } 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>Add Merkel<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // 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 "assert.h" #include "chainparams.h" #include "core.h" #include "protocol.h" #include "util.h" // // Main network // unsigned int pnSeed[] = { 0x12345678 }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0xa3; pchMessageStart[1] = 0xd2; pchMessageStart[2] = 0x7a; pchMessageStart[3] = 0x03; vAlertPubKey = ParseHex("04c5788ca1e268a7474763fa965210b6fa6b04a45f52d21056c62fb19a2de991aa15aa1d1c516f34d2a0016f51a87959c89f51a148db30c839f71bc525dde8c480"); nDefaultPort = 21994; nRPCPort = 21995; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); nSubsidyHalvingInterval = 175320; // 6 months // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. const char* pszTimestamp = "11-03-14 - Malaysia says missing jet made it far from last reported position"; 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 = 64 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04becedf6ebadd4596964d890f677f8d2e74fdcc313c6416434384a66d6d8758d1c92de272dc6713e4a81d98841dfdfdc95e204ba915447d2fe9313435c78af3e8") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1390078220; genesis.nBits = 0x1e0fffff; genesis.nNonce = 2099366979; //// debug print hashGenesisBlock = genesis.GetHash(); //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){ // if (++genesis.nNonce==0) break; // hashGenesisBlock = genesis.GetHash(); //} printf("%s\n", hashGenesisBlock.ToString().c_str()); printf("%s\n", genesis.hashMerkleRoot.ToString().c_str()); printf("%x\n", bnProofOfWorkLimit.GetCompact()); genesis.print(); assert(hashGenesisBlock == uint256("0x00000f639db5734b2b861ef8dbccc33aebd7de44d13de000a12d093bcc866c64")); assert(genesis.hashMerkleRoot == uint256("0x83169555d8575c36c7803e764eca6328c058a2121b4859566191ed1fe68c8f6e")); vSeeds.push_back(CDNSSeedData("piastrecoin.no-ip.biz", "piastrecoin.no-ip.biz")); vSeeds.push_back(CDNSSeedData("piastrecoin.zapto.org", "piastrecoin.zapto.org")); base58Prefixes[PUBKEY_ADDRESS] = 38; base58Prefixes[SCRIPT_ADDRESS] = 4; base58Prefixes[SECRET_KEY] = 28 + 128; // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' const int64 nTwoDays = 2 * 24 * 60 * 60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays; 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 (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. pchMessageStart[0] = 0xfb; pchMessageStart[1] = 0xc2; pchMessageStart[2] = 0x11; pchMessageStart[3] = 0x02; vAlertPubKey = ParseHex("040d3090a194381599d0f53f89ec60b9ec77f0e7b61978ef445142c8a4f1e154ca3441a5e46e12910540352edbd8af43fc1ee1da9a935c1c252fe7426c323d3d32"); nDefaultPort = 21994; nRPCPort = 21995; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1388868139; genesis.nNonce = 423087994; //// debug print hashGenesisBlock = genesis.GetHash(); //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){ // if (++genesis.nNonce==0) break; // hashGenesisBlock = genesis.GetHash(); //} printf("%s\n", hashGenesisBlock.ToString().c_str()); printf("%s\n", genesis.hashMerkleRoot.ToString().c_str()); genesis.print(); assert(hashGenesisBlock == uint256("0x0000082f5939c2154dbcba35f784530d12e9d72472fcfaf29674ea312cdf4c83")); vFixedSeeds.clear(); vSeeds.clear(); // vSeeds.push_back(CDNSSeedData("testseed1.piastrecoin.org", "testseed1.piastrecoin.org")); base58Prefixes[PUBKEY_ADDRESS] = 80; base58Prefixes[SCRIPT_ADDRESS] = 44; base58Prefixes[SECRET_KEY] = 80 + 128; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfc; pchMessageStart[1] = 0x1f; pchMessageStart[2] = 0xc3; pchMessageStart[3] = 0x56; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1296688602; genesis.nBits = 0x207fffff; genesis.nNonce = 3; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 18444; strDataDir = "regtest"; //// debug print hashGenesisBlock = genesis.GetHash(); //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){ // if (++genesis.nNonce==0) break; // hashGenesisBlock = genesis.GetHash(); // } // printf("%s\n", hashGenesisBlock.ToString().c_str()); // printf("%s\n", genesis.hashMerkleRoot.ToString().c_str()); // genesis.print(); // assert(hashGenesisBlock == uint256("0x13d8d31dde96874006da503dd2b63fa68c698dc823334359e417aa3a92f80433")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. base58Prefixes[PUBKEY_ADDRESS] = 0; base58Prefixes[SCRIPT_ADDRESS] = 5; base58Prefixes[SECRET_KEY] = 128; } 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>// 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; }; bool fEnabled = true; // 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("0x00000f164a6ba5027216402d8949af9de59c21732c85314ffc7120c54893d854")) ; static const CCheckpointData data = { &mapCheckpoints, 1387868253, // * UNIX timestamp of last checkpoint block 0, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 2880 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x00000ff105e2ca2ef840320f1ba9a64295c654935c1afb980bc34c89cb93b8bc")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1374901773, 0, 2880 }; const CCheckpointData &Checkpoints() { if (TestNet()) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (!fEnabled) 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 (!fEnabled) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (!fEnabled) 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>Adding checkpoints<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; }; bool fEnabled = true; // 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("0x00000f164a6ba5027216402d8949af9de59c21732c85314ffc7120c54893d854")) ( 500, uint256("0x00000000000068cb8984730adf865acdc5767a8d556f1284db6d11fc7c75333a")) ( 1324, uint256("0x00000000000085a7dbdec3b0225258f065d1612407fd2d4e5e961c08b94cf025")) ( 25000, uint256("0x0000000000309b623ab2128c8235b2d1a56da540454caa4903f0933d0bfdc9dd")) ( 32000, uint256("0x0000000000f5fbe05a99c723ac03110bd50b43116ecce0bc8a1243b691be4d6d")) ; static const CCheckpointData data = { &mapCheckpoints, 1387868253, // * UNIX timestamp of last checkpoint block 0, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 2880 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x00000ff105e2ca2ef840320f1ba9a64295c654935c1afb980bc34c89cb93b8bc")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1374901773, 0, 2880 }; const CCheckpointData &Checkpoints() { if (TestNet()) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (!fEnabled) 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 (!fEnabled) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (!fEnabled) 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 //TODO: add more checkpoints ( 0, uint256("0xa12f227d13837f1ef7a4fb5aa35922893f9bdb335907a3d070728664c13d2899")) ( 2, uint256("0xdad976aa92fc3541e31cf541fed0dda2125e4b4adb4c8de04dad96c97229dad8")) ( 8, uint256("0xbeb761843385c06afb3270735755bbb649ecd754c7cc4d813cd1aaa30dfe0fc2")) ( 30, uint256("0x2ad37a5b3a89992ae485072738d7a5d4cfbe94deb5af4459ea90650d76a62b19")) ( 41, uint256("0x5c53d4a7f1a3ad4fa7dae52648c6f994cef2f7969c6b3ee135855ee0f039d262")) ( 400, uint256("0x7145983fc3f1346c95af7a3b1720c0b01c926f9379dc3ecc2a6d9c0d180f8226")) ( 800, uint256("0x0e42f9edb41c08aff6a735f1fd33918d28ae505a6131984380729fbded363cef")) ( 1337, uint256("0x5ea56c7f7b89da5be25ef99cc1d0b788b8936ed6e4371c2955b0d52ce5d80123")) ( 3000, uint256("0x2e407195d4fc5571fe450e1c9ed9ce76407f547803a03dbc5410e129f12d7d15")) ( 3427, uint256("0x9f013ec43391a52f417cbb10cdabdbec3d0091780cb2ca6be86dfee2e92eca73")) ( 3445, uint256("0x9227548be2dc2cfde8a0c32b56c1be471011e804b3a83876c45de98a2bfed6d8")) ; 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 added<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 //TODO: add more checkpoints ( 0, uint256("0xa12f227d13837f1ef7a4fb5aa35922893f9bdb335907a3d070728664c13d2899")) ( 2, uint256("0xdad976aa92fc3541e31cf541fed0dda2125e4b4adb4c8de04dad96c97229dad8")) ( 8, uint256("0xbeb761843385c06afb3270735755bbb649ecd754c7cc4d813cd1aaa30dfe0fc2")) ( 30, uint256("0x2ad37a5b3a89992ae485072738d7a5d4cfbe94deb5af4459ea90650d76a62b19")) ( 41, uint256("0x5c53d4a7f1a3ad4fa7dae52648c6f994cef2f7969c6b3ee135855ee0f039d262")) ( 400, uint256("0x7145983fc3f1346c95af7a3b1720c0b01c926f9379dc3ecc2a6d9c0d180f8226")) ( 800, uint256("0x0e42f9edb41c08aff6a735f1fd33918d28ae505a6131984380729fbded363cef")) ( 1337, uint256("0x5ea56c7f7b89da5be25ef99cc1d0b788b8936ed6e4371c2955b0d52ce5d80123")) ( 3000, uint256("0x2e407195d4fc5571fe450e1c9ed9ce76407f547803a03dbc5410e129f12d7d15")) ( 3427, uint256("0x9f013ec43391a52f417cbb10cdabdbec3d0091780cb2ca6be86dfee2e92eca73")) ( 3445, uint256("0x9227548be2dc2cfde8a0c32b56c1be471011e804b3a83876c45de98a2bfed6d8")) ( 10000, uint256("0xcd335bac144635f468c2b2fd3793e74a2f739c06dfa64aba4d60c72927b59926")) ( 22000, uint256("0x89b8956580c34811c71e1e4a0c79b17f1577d3f93228eca84fad3dbe98313c4e")) ( 35000, uint256("0xc2c43c740a3d98d310337e9dee77500a191d43022f78b75c30cb3536dc639189")) ( 50000, uint256("0xd5943fca0eadf762c0857abcd8c558b002d28cf06e9cb13297c7b542be474308")) ; 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) 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 ( 1, uint256("0x8fe2901fc0999bc86ea2668c58802ee87165438166d18154f1bd4f917bf25e0f")) ( 7, uint256("0x4530df06d98fc77d04dab427630fc63b45f10d2b0ad3ad3a651883938986d629")) ( 7777, uint256("0xae3094030b34a422c44b9832c84fe602d0d528449d6940374bd43b4472b4df5e")) (15420, uint256("0xfded6a374d071f59d738a3009fc4d8461609052c3e7e91aa89146550d179c1b0")) (16000, uint256("0x683517a8cae8530f39e636f010ecd1750665c3d91f57ba71d6556535972ab328")) (77777, uint256("0xf5c98062cb1ad75c792a1851a388447f0edd7cb2271b67ef1241a03c673b7735")) (77778, uint256("0xd13f93f9fdac82ea26ed8f90474ed2449c8c24be50a416e43c323a38573c30e5")) (100000, uint256("0xcc4f0b11e9e17f7a406ac4a71e6e192b9b43e32b300ddecba229c789392497eb")) (106000, uint256("0xbe27545eb8ea31c74878b54d500161873ed035afc2fa1f4e7cfa7e84a232b8f9")) (112800, uint256("0x4dbecbf0368b99c80da8406693f370b754f78a7b6d139a878bc69fb961f86383")) ; static const CCheckpointData data = { &mapCheckpoints, 1376885874, // * UNIX timestamp of last checkpoint block 1859062, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 7000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 5046, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70")) ( 35000, uint256("2af959ab4f12111ce947479bfcef16702485f04afd95210aa90fde7d1e4a64ad")) ; 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) { // TODO: return true; /*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>disable checkpoints<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 ( 1, uint256("0x8fe2901fc0999bc86ea2668c58802ee87165438166d18154f1bd4f917bf25e0f")) ( 7, uint256("0x4530df06d98fc77d04dab427630fc63b45f10d2b0ad3ad3a651883938986d629")) ( 7777, uint256("0xae3094030b34a422c44b9832c84fe602d0d528449d6940374bd43b4472b4df5e")) (15420, uint256("0xfded6a374d071f59d738a3009fc4d8461609052c3e7e91aa89146550d179c1b0")) (16000, uint256("0x683517a8cae8530f39e636f010ecd1750665c3d91f57ba71d6556535972ab328")) (77777, uint256("0xf5c98062cb1ad75c792a1851a388447f0edd7cb2271b67ef1241a03c673b7735")) (77778, uint256("0xd13f93f9fdac82ea26ed8f90474ed2449c8c24be50a416e43c323a38573c30e5")) (100000, uint256("0xcc4f0b11e9e17f7a406ac4a71e6e192b9b43e32b300ddecba229c789392497eb")) (106000, uint256("0xbe27545eb8ea31c74878b54d500161873ed035afc2fa1f4e7cfa7e84a232b8f9")) (112800, uint256("0x4dbecbf0368b99c80da8406693f370b754f78a7b6d139a878bc69fb961f86383")) ; static const CCheckpointData data = { &mapCheckpoints, 1376885874, // * UNIX timestamp of last checkpoint block 1859062, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 7000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 5046, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70")) ( 35000, uint256("2af959ab4f12111ce947479bfcef16702485f04afd95210aa90fde7d1e4a64ad")) ; 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) { // TODO: return true; /*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() { return 0; // TODO: /*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) { return NULL; // TODO: /*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 "txdb.h" #include "main.h" #include "uint256.h" static const int nCheckpointSpan = 500; 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("0x00000b38581f2f7297c2be4689e26dca446cb8c86d23e034791e0833dcea0b8c") ) ; // TestNet checkpoints static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x00000647de02bbb1b56c568085024fbb79e2f27dba79ac20477fb2caae1a610d") ) ; bool CheckHardened(int nHeight, const uint256& hash) { MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints); MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints); if (checkpoints.empty()) return 0; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : 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; } // Automatically select a suitable sync-checkpoint const CBlockIndex* AutoSelectSyncCheckpoint() { const CBlockIndex *pindex = pindexBest; // Search backward for a block within max span and maturity window while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight) pindex = pindex->pprev; return pindex; } // Check against synchronized checkpoint bool CheckSync(int nHeight) { const CBlockIndex* pindexSync = AutoSelectSyncCheckpoint(); if (nHeight <= pindexSync->nHeight) return false; return true; } } <commit_msg>New checkpoint set at height 122000<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 "txdb.h" #include "main.h" #include "uint256.h" static const int nCheckpointSpan = 500; 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("0x00000b38581f2f7297c2be4689e26dca446cb8c86d23e034791e0833dcea0b8c") ) (122000, uint256("0x68a754b45c1062494c1267fe3fe52b6cd071f5a41c82feb2582c40a92af3f573") ) ; // TestNet checkpoints static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x00000647de02bbb1b56c568085024fbb79e2f27dba79ac20477fb2caae1a610d") ) ; bool CheckHardened(int nHeight, const uint256& hash) { MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints); MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints); if (checkpoints.empty()) return 0; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : 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; } // Automatically select a suitable sync-checkpoint const CBlockIndex* AutoSelectSyncCheckpoint() { const CBlockIndex *pindex = pindexBest; // Search backward for a block within max span and maturity window while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight) pindex = pindex->pprev; return pindex; } // Check against synchronized checkpoint bool CheckSync(int nHeight) { const CBlockIndex* pindexSync = AutoSelectSyncCheckpoint(); if (nHeight <= pindexSync->nHeight) return false; 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("0x9677102b58bd0d0888deadf88cf15a3e6e32b0b1c66eacefc668126514995cb3")) ( 1, uint256("0x71cb12dac45a282e46a344d5d12d55dda70ad99e6b1d7f46f50956bbc6ed1ef6")) ; static const CCheckpointData data = { &mapCheckpoints, 1397072478, // * 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, 1389241455, 0, 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>init checkpoints<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("0x9677102b58bd0d0888deadf88cf15a3e6e32b0b1c66eacefc668126514995cb3")) ; static const CCheckpointData data = { &mapCheckpoints, 1396381854, // * UNIX timestamp of last checkpoint block 0, // * 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, 1389241455, 0, 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 ( 100, uint256("0xc3d91cb4726610d422f8652a5a7cc21bd42e1b8009c00462081c81316d9abad6")) ( 10000, uint256("0x7b50ea3b42e613e65ec2aca6797a5780e1c545a617e4a610577fb4b040f0035b")) ( 30000, uint256("0x43e2fe7c700191ddfabe2cd09dfd3fc9eb6331f3c19e59b3e4a87cfa88cac543")) ( 50000, uint256("0x6a4f705b7a34de7dc1b6573b3595fde05c7b4303b35ede20a3b945244adc6c70")) ( 69500, uint256("0x8387b49853928fc67d8b8421fd9214184db590eeecd90a200c9d902d8b42e11f")) ( 80000, uint256("0xa7d7ac0b4b1f5eb56b50ad0693c47f47863b8df81f17514bcb5e59c0a4074eba")) ( 91000, uint256("0x3f135e0e06ae032de5437ae2b981e3ab84c7d22310224a6e53c6e6e769e8f8f0")) (101000, uint256("0xba5948ef9fce38887df24c54366121437d336bd67a4332508248def0032c5d6e")) (111000, uint256("0xbb9cc6e2d9da343774dc4b49be417731991b90ef53a7fa7eb669cce237223c37")) (121000, uint256("0x1d286956120cf256bed13bcc1f5fe79a98347c80f2225ded92bbbdfc1147b5f5")) (136000, uint256("0xb7c7416c40425bc7976c7b6b87734e2fb84855eecd30e3e9673caf8c7f599b5c")) (153000, uint256("0x9f31abd27721e7eb2b58c0a61a117c324a3a6b8f45c82e8963b1bd14166f6510")) ; static const CCheckpointData data = { &mapCheckpoints, 1397792098, // * UNIX timestamp of last checkpoint block 799952, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 7200.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0xed0457370ddafea96096d4c9f5187efceece8d8ab5558194c7eebb06943c8c8c")) ( 610, uint256("0x26c53c6df7d16be2596ef3eaf11c7281b05061d76b8b146413d4899e33ff5e3a")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1399143168, 637, 100 }; 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>updated checkpoints as of May 18, 2014<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 ( 100, uint256("0xc3d91cb4726610d422f8652a5a7cc21bd42e1b8009c00462081c81316d9abad6")) ( 10000, uint256("0x7b50ea3b42e613e65ec2aca6797a5780e1c545a617e4a610577fb4b040f0035b")) ( 30000, uint256("0x43e2fe7c700191ddfabe2cd09dfd3fc9eb6331f3c19e59b3e4a87cfa88cac543")) ( 50000, uint256("0x6a4f705b7a34de7dc1b6573b3595fde05c7b4303b35ede20a3b945244adc6c70")) ( 69500, uint256("0x8387b49853928fc67d8b8421fd9214184db590eeecd90a200c9d902d8b42e11f")) ( 80000, uint256("0xa7d7ac0b4b1f5eb56b50ad0693c47f47863b8df81f17514bcb5e59c0a4074eba")) ( 91000, uint256("0x3f135e0e06ae032de5437ae2b981e3ab84c7d22310224a6e53c6e6e769e8f8f0")) (101000, uint256("0xba5948ef9fce38887df24c54366121437d336bd67a4332508248def0032c5d6e")) (111000, uint256("0xbb9cc6e2d9da343774dc4b49be417731991b90ef53a7fa7eb669cce237223c37")) (121000, uint256("0x1d286956120cf256bed13bcc1f5fe79a98347c80f2225ded92bbbdfc1147b5f5")) (136000, uint256("0xb7c7416c40425bc7976c7b6b87734e2fb84855eecd30e3e9673caf8c7f599b5c")) (153000, uint256("0x9f31abd27721e7eb2b58c0a61a117c324a3a6b8f45c82e8963b1bd14166f6510")) (161000, uint256("0xf7a9069c705516f60878bf6da9bac02c12d0d8984cb90bce03fe34842ba7eb3d")) (170000, uint256("0x827d5ce5ed69153deacab9a2d3c35a7b33cdaa397a6a4a540d538b765182f234")) (181000, uint256("0x69fa48e8b9231f101df79c5b3174feb70bf6da11d88a4ce879a7c9ecb799f46d")) (191000, uint256("0x80a9ea6b375312c376de880b6958459973a95be1dcbf28db1731452a59ef9750")) ; static const CCheckpointData data = { &mapCheckpoints, 1400387941, // * UNIX timestamp of last checkpoint block 875272, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 7200.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0xed0457370ddafea96096d4c9f5187efceece8d8ab5558194c7eebb06943c8c8c")) ( 610, uint256("0x26c53c6df7d16be2596ef3eaf11c7281b05061d76b8b146413d4899e33ff5e3a")) ( 1400, uint256("0x3fc44fd682e0b5f338ca2dc8df8de9b4a72806906338a8c553b3f63f728e2930")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1400366796, 1438, 100 }; 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 // 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("0xedfe5830b53251bfff733600b1cd5c192e761c011b055f07924634818c906438")) ( 100, uint256("0xfc60bb9b4d47bb1db75e6300aa94cce79df11211f4b3f459e03c7ef08018bccd")) ( 1000, uint256("0x497ae9915e9a82bc2e7deb92dff927151328784592be0ea6c3ba8dfacc69e7c8")) ( 10000, uint256("0x1c8939a32354910255cef27b6fbae3a7b3387ac4f64f917830e69e9be57abb8c")) ( 20000, uint256("0x87752dc07e38fe38ef0349c4d22a4384da9c05a484fc07d8b134ec593b4ab081")) ( 40000, uint256("0x828fdcc616c17688515ca7581885ba08750bc75a28da68d6b8b81c18d989ef07")) ( 122500, uint256("0x97fd41dc4f99a9ddb156a5eb489c64319f027bf9e83a7ffdd90f4e45e9c82d66")) ( 300000, uint256("0x7126ab439f3d4598e6baa82ab6845b2989a9ed2470adc81ef0263eb7547f8967")) ( 450000, uint256("0x6c36edb95be3ca362d812889b14337532f0c3ce65a051491da9c21dc80c26506")) ( 525600, uint256("0x1157fc00456783fd55502f31bf94597ee586c4ea2abddd97b576fe98c6364e33")) ( 550000, uint256("0x3ceaf6702ea1bcb4c7282c5dd17826fefa30fca674f9e4662c0668d13282c703")) ; static const CCheckpointData data = { &mapCheckpoints, 1422028391, // * UNIX timestamp of last checkpoint block 642649, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 600.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("523f8a9f38bb5998df20870d8e306a15e75e60935ee37b66df0fd36584a0e48a")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1388512432, 1, 960.0 }; 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("0xedfe5830b53251bfff733600b1cd5c192e761c011b055f07924634818c906438")) ( 100, uint256("0xfc60bb9b4d47bb1db75e6300aa94cce79df11211f4b3f459e03c7ef08018bccd")) ( 1000, uint256("0x497ae9915e9a82bc2e7deb92dff927151328784592be0ea6c3ba8dfacc69e7c8")) ( 10000, uint256("0x1c8939a32354910255cef27b6fbae3a7b3387ac4f64f917830e69e9be57abb8c")) ( 20000, uint256("0x87752dc07e38fe38ef0349c4d22a4384da9c05a484fc07d8b134ec593b4ab081")) ( 40000, uint256("0x828fdcc616c17688515ca7581885ba08750bc75a28da68d6b8b81c18d989ef07")) ( 122500, uint256("0x97fd41dc4f99a9ddb156a5eb489c64319f027bf9e83a7ffdd90f4e45e9c82d66")) ( 300000, uint256("0x7126ab439f3d4598e6baa82ab6845b2989a9ed2470adc81ef0263eb7547f8967")) ( 450000, uint256("0x6c36edb95be3ca362d812889b14337532f0c3ce65a051491da9c21dc80c26506")) ( 525600, uint256("0x1157fc00456783fd55502f31bf94597ee586c4ea2abddd97b576fe98c6364e33")) ( 552500, uint256("0x324a01ae91ba51bc22ca0faf31def5fdb4da722adc54f689fee637cf16c428e9")) ; static const CCheckpointData data = { &mapCheckpoints, 1422180586, // * UNIX timestamp of last checkpoint block 645207, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 600.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("523f8a9f38bb5998df20870d8e306a15e75e60935ee37b66df0fd36584a0e48a")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1388512432, 1, 960.0 }; 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 "dice.h" #include <qDebug> #include <ctime> #include <cstdlib> #include <QMediaPlayer> #include <QFileInfo> #include <QTimeLine> using namespace std; Dice::Dice() { qDebug() << "Dice Created"; srand((unsigned)time(NULL)); value1 = 0; value2 = 0; roll_sound = new QMediaPlayer(); roll_sound->setVolume(100); effect_sound = new QMediaPlayer(); effect_sound->setVolume(100); timeline = new QTimeLine(1000); connect(timeline, SIGNAL(finished()), this, SLOT(afterRollSound())); } Dice::~Dice() { qDebug() << "Dice Destroyed"; delete roll_sound; delete effect_sound; delete timeline; } // Initialize Static Members Dice* Dice::m_inst = NULL; Dice* Dice::getInst() { // create new instance if null if (!m_inst) { m_inst = new Dice(); } return m_inst; } void Dice::delInst() { // delete an instance if (m_inst) { delete m_inst; m_inst = NULL; } return; } // Methods void Dice::roll() { qDebug() << "Dice Rolled"; // value1 = rand() % 6 + 1; // value2 = rand() % 6 + 1; value1 = 4; value2 = 5; emit diceRolled(getValue(),isDouble()); emit firstDiceRolled(value1); emit secondDiceRolled(value2); emit diceRolled(getValue()); emit diceRolled(this); timeline->start(); // play sound roll_sound->setMedia(QUrl::fromLocalFile(QFileInfo("sound/roll.mp3").absoluteFilePath())); roll_sound->play(); } bool Dice::isDouble() { return (value1 == value2); } int Dice::getValue() { return value1 + value2; } int Dice::getFirstDice() { return value1; } int Dice::getSecondDice() { return value2; } void Dice::afterRollSound() { QString path = ""; if(isDouble()) { path += "sound/double.wav"; // emit singal for double popup emit diceDouble(); } else { switch(value1 + value2) { case 2: path += "sound/two.wav"; break; case 3: path += "sound/three.wav"; break; case 4: path += "sound/four.wav"; break; case 5: path += "sound/five.wav"; break; case 6: path += "sound/six.wav"; break; case 7: path += "sound/seven.wav"; break; case 8: path += "sound/eight.wav"; break; case 9: path += "sound/nine.wav"; break; case 10: path += "sound/ten.wav"; break; case 11: path += "sound/eleven.wav"; break; case 12: path += "sound/twelve.wav"; break; } } effect_sound->setMedia(QUrl::fromLocalFile(QFileInfo(path).absoluteFilePath())); effect_sound->play(); } <commit_msg>afterroll event fixed, removed dice test code<commit_after>#include "dice.h" #include <qDebug> #include <ctime> #include <cstdlib> #include <QMediaPlayer> #include <QFileInfo> #include <QTimeLine> using namespace std; Dice::Dice() { qDebug() << "Dice Created"; srand((unsigned)time(NULL)); value1 = 0; value2 = 0; roll_sound = new QMediaPlayer(); roll_sound->setVolume(100); effect_sound = new QMediaPlayer(); effect_sound->setVolume(100); timeline = new QTimeLine(1300); connect(timeline, SIGNAL(finished()), this, SLOT(afterRollSound())); } Dice::~Dice() { qDebug() << "Dice Destroyed"; delete roll_sound; delete effect_sound; delete timeline; } // Initialize Static Members Dice* Dice::m_inst = NULL; Dice* Dice::getInst() { // create new instance if null if (!m_inst) { m_inst = new Dice(); } return m_inst; } void Dice::delInst() { // delete an instance if (m_inst) { delete m_inst; m_inst = NULL; } return; } // Methods void Dice::roll() { qDebug() << "Dice Rolled"; value1 = rand() % 6 + 1; value2 = rand() % 6 + 1; emit diceRolled(getValue(),isDouble()); emit firstDiceRolled(value1); emit secondDiceRolled(value2); emit diceRolled(getValue()); emit diceRolled(this); timeline->start(); // play sound roll_sound->setMedia(QUrl::fromLocalFile(QFileInfo("sound/roll.mp3").absoluteFilePath())); roll_sound->play(); } bool Dice::isDouble() { return (value1 == value2); } int Dice::getValue() { return value1 + value2; } int Dice::getFirstDice() { return value1; } int Dice::getSecondDice() { return value2; } void Dice::afterRollSound() { QString path = ""; if(isDouble()) { path += "sound/double.wav"; // emit singal for double popup emit diceDouble(); } else { switch(value1 + value2) { case 2: path += "sound/two.wav"; break; case 3: path += "sound/three.wav"; break; case 4: path += "sound/four.wav"; break; case 5: path += "sound/five.wav"; break; case 6: path += "sound/six.wav"; break; case 7: path += "sound/seven.wav"; break; case 8: path += "sound/eight.wav"; break; case 9: path += "sound/nine.wav"; break; case 10: path += "sound/ten.wav"; break; case 11: path += "sound/eleven.wav"; break; case 12: path += "sound/twelve.wav"; break; } } effect_sound->setMedia(QUrl::fromLocalFile(QFileInfo(path).absoluteFilePath())); effect_sound->play(); } <|endoftext|>
<commit_before> #include "include/types.h" #include "config.h" #include "debug.h" #include "Mutex.h" #include "Clock.h" #include "ceph_ver.h" #include <errno.h> #include <fstream> #include <iostream> using namespace std; #define _STR(x) #x #define STRINGIFY(x) _STR(x) // debug output Mutex _dout_lock("_dout_lock", false, false /* no lockdep */); ostream *_dout = &std::cout; ostream *_derr = &std::cerr; char _dout_dir[PATH_MAX] = {0}; char _dout_symlink_dir[PATH_MAX] = {0}; char _dout_file[PATH_MAX] = {0}; char _dout_path[PATH_MAX] = {0}; char _dout_rank_symlink_path[PATH_MAX] = {0}; char _dout_name_symlink_path[PATH_MAX] = {0}; char *_dout_symlink_target = 0; // _dout_path or _dout_file bool _dout_is_open = false; bool _dout_need_open = true; std::ofstream _dout_out; static void normalize_relative(const char *from, char *to, int tolen) { if (from[0] == '/') strncpy(to, from, tolen); else { char *c = getcwd(to, tolen); assert(c); strncat(to, "/", tolen); strncat(to, from, tolen); } } static void build_log_paths() { if (g_conf.log_file && g_conf.log_file[0]) { normalize_relative(g_conf.log_file, _dout_path, sizeof(_dout_path)); } else { if (g_conf.log_per_instance) { char hostname[80]; gethostname(hostname, 79); snprintf(_dout_file, sizeof(_dout_file), "%s.%d", hostname, getpid()); } else { snprintf(_dout_file, sizeof(_dout_file), "%s.%s.log", g_conf.type, g_conf.id); } snprintf(_dout_path, sizeof(_dout_path), "%s/%s", _dout_dir, _dout_file); } } static bool log_to_file() { return (g_conf.log_dir || g_conf.log_file) && !g_conf.log_to_stdout; } static int create_symlink(const char *from) { ::unlink(from); int r = ::symlink(_dout_symlink_target, from); if (r) { char buf[80]; *_dout << "---- " << getpid() << " failed to symlink " << _dout_symlink_target << " from " << from << ": " << strerror_r(errno, buf, sizeof(buf)) << std::endl; } return r; } static void rotate_file(const char *fn, int max) { char a[200], b[200]; // rotate out old int n = 0; while (1) { struct stat st; snprintf(a, sizeof(a), "%s.%lld", fn, (long long)n); if (::lstat(a, &st) != 0) break; n++; } while (n >= 0) { if (n) snprintf(a, sizeof(a), "%s.%lld", fn, (long long)n-1); else snprintf(a, sizeof(a), "%s", fn); if (n >= max) { ::unlink(a); *_dout << "---- " << getpid() << " removed " << a << " ----" << std::endl; } else { snprintf(b, sizeof(b), "%s.%lld", fn, (long long)n); ::rename(a, b); *_dout << "---- " << getpid() << " renamed " << a << " -> " << b << " ----" << std::endl; } n--; } } static int create_name_symlink() { int r = 0; if (log_to_file() && g_conf.log_per_instance) { snprintf(_dout_name_symlink_path, sizeof(_dout_name_symlink_path), "%s/%s.%s", _dout_symlink_dir, g_conf.type, g_conf.id); rotate_file(_dout_name_symlink_path, g_conf.log_sym_history); r = create_symlink(_dout_name_symlink_path); } return r; } void _dout_open_log() { bool need_symlink = false; // logging enabled? if (!log_to_file()) { _dout_need_open = false; return; } // calculate log dir, filename, etc. // do this _once_. if (!_dout_path[0]) { // normalize paths normalize_relative(g_conf.log_dir, _dout_dir, sizeof(_dout_dir)); if (!g_conf.log_sym_dir) g_conf.log_sym_dir = strdup(g_conf.log_dir); normalize_relative(g_conf.log_sym_dir, _dout_symlink_dir, sizeof(_dout_symlink_dir)); // make symlink targets absolute or relative? if ((g_conf.log_file && g_conf.log_file[0]) || strcmp(_dout_symlink_dir, _dout_dir) == 0) _dout_symlink_target = _dout_file; else _dout_symlink_target = _dout_path; build_log_paths(); need_symlink = true; } _dout_out.close(); // only truncate if log_per_instance is set. _dout_out.open(_dout_path, g_conf.log_per_instance ? (ios::trunc | ios::out) : (ios::out | ios::ate)); if (!_dout_out.is_open()) { std::cerr << "error opening output file " << _dout_path << std::endl; _dout = &std::cout; } else { _dout_need_open = false; _dout_is_open = true; _dout = &_dout_out; *_dout << g_clock.now() << " --- " << getpid() << " opened log " << _dout_path << " ---" << std::endl; } *_dout << "ceph version " << VERSION << " (" << STRINGIFY(CEPH_GIT_VER) << ")" << std::endl; if (need_symlink) create_name_symlink(); } int dout_rename_output_file() // after calling daemon() { Mutex::Locker l(_dout_lock); if (log_to_file() && g_conf.log_per_instance) { char oldpath[PATH_MAX]; char hostname[80]; gethostname(hostname, 79); strcpy(oldpath, _dout_path); build_log_paths(); *_dout << "---- " << getpid() << " renamed log " << oldpath << " -> " << _dout_path << " ----" << std::endl; ::rename(oldpath, _dout_path); // $type.$id symlink if (g_conf.log_per_instance && _dout_name_symlink_path[0]) create_symlink(_dout_name_symlink_path); if (_dout_rank_symlink_path[0]) create_symlink(_dout_rank_symlink_path); } return 0; } int dout_create_rank_symlink(int64_t n) { Mutex::Locker l(_dout_lock); int r = 0; if (log_to_file() && !(g_conf.log_file && g_conf.log_file[0])) { if (_dout_need_open) _dout_open_log(); snprintf(_dout_rank_symlink_path, sizeof(_dout_rank_symlink_path), "%s/%s%lld", _dout_symlink_dir, g_conf.type, (long long)n); r = create_symlink(_dout_rank_symlink_path); } return r; } <commit_msg>debug: say 'append' or 'new' when opening log<commit_after> #include "include/types.h" #include "config.h" #include "debug.h" #include "Mutex.h" #include "Clock.h" #include "ceph_ver.h" #include <errno.h> #include <fstream> #include <iostream> using namespace std; #define _STR(x) #x #define STRINGIFY(x) _STR(x) // debug output Mutex _dout_lock("_dout_lock", false, false /* no lockdep */); ostream *_dout = &std::cout; ostream *_derr = &std::cerr; char _dout_dir[PATH_MAX] = {0}; char _dout_symlink_dir[PATH_MAX] = {0}; char _dout_file[PATH_MAX] = {0}; char _dout_path[PATH_MAX] = {0}; char _dout_rank_symlink_path[PATH_MAX] = {0}; char _dout_name_symlink_path[PATH_MAX] = {0}; char *_dout_symlink_target = 0; // _dout_path or _dout_file bool _dout_is_open = false; bool _dout_need_open = true; std::ofstream _dout_out; static void normalize_relative(const char *from, char *to, int tolen) { if (from[0] == '/') strncpy(to, from, tolen); else { char *c = getcwd(to, tolen); assert(c); strncat(to, "/", tolen); strncat(to, from, tolen); } } static void build_log_paths() { if (g_conf.log_file && g_conf.log_file[0]) { normalize_relative(g_conf.log_file, _dout_path, sizeof(_dout_path)); } else { if (g_conf.log_per_instance) { char hostname[80]; gethostname(hostname, 79); snprintf(_dout_file, sizeof(_dout_file), "%s.%d", hostname, getpid()); } else { snprintf(_dout_file, sizeof(_dout_file), "%s.%s.log", g_conf.type, g_conf.id); } snprintf(_dout_path, sizeof(_dout_path), "%s/%s", _dout_dir, _dout_file); } } static bool log_to_file() { return (g_conf.log_dir || g_conf.log_file) && !g_conf.log_to_stdout; } static int create_symlink(const char *from) { ::unlink(from); int r = ::symlink(_dout_symlink_target, from); if (r) { char buf[80]; *_dout << "---- " << getpid() << " failed to symlink " << _dout_symlink_target << " from " << from << ": " << strerror_r(errno, buf, sizeof(buf)) << std::endl; } return r; } static void rotate_file(const char *fn, int max) { char a[200], b[200]; // rotate out old int n = 0; while (1) { struct stat st; snprintf(a, sizeof(a), "%s.%lld", fn, (long long)n); if (::lstat(a, &st) != 0) break; n++; } while (n >= 0) { if (n) snprintf(a, sizeof(a), "%s.%lld", fn, (long long)n-1); else snprintf(a, sizeof(a), "%s", fn); if (n >= max) { ::unlink(a); *_dout << "---- " << getpid() << " removed " << a << " ----" << std::endl; } else { snprintf(b, sizeof(b), "%s.%lld", fn, (long long)n); ::rename(a, b); *_dout << "---- " << getpid() << " renamed " << a << " -> " << b << " ----" << std::endl; } n--; } } static int create_name_symlink() { int r = 0; if (log_to_file() && g_conf.log_per_instance) { snprintf(_dout_name_symlink_path, sizeof(_dout_name_symlink_path), "%s/%s.%s", _dout_symlink_dir, g_conf.type, g_conf.id); rotate_file(_dout_name_symlink_path, g_conf.log_sym_history); r = create_symlink(_dout_name_symlink_path); } return r; } void _dout_open_log() { bool need_symlink = false; // logging enabled? if (!log_to_file()) { _dout_need_open = false; return; } // calculate log dir, filename, etc. // do this _once_. if (!_dout_path[0]) { // normalize paths normalize_relative(g_conf.log_dir, _dout_dir, sizeof(_dout_dir)); if (!g_conf.log_sym_dir) g_conf.log_sym_dir = strdup(g_conf.log_dir); normalize_relative(g_conf.log_sym_dir, _dout_symlink_dir, sizeof(_dout_symlink_dir)); // make symlink targets absolute or relative? if ((g_conf.log_file && g_conf.log_file[0]) || strcmp(_dout_symlink_dir, _dout_dir) == 0) _dout_symlink_target = _dout_file; else _dout_symlink_target = _dout_path; build_log_paths(); need_symlink = true; } _dout_out.close(); // only truncate if log_per_instance is set. _dout_out.open(_dout_path, g_conf.log_per_instance ? (ios::trunc | ios::out) : (ios::out | ios::ate)); if (!_dout_out.is_open()) { std::cerr << "error opening output file " << _dout_path << std::endl; _dout = &std::cout; } else { _dout_need_open = false; _dout_is_open = true; _dout = &_dout_out; *_dout << g_clock.now() << " --- " << getpid() << (g_conf.log_per_instance ? " created new log " : " appending to log ") << _dout_path << " ---" << std::endl; } *_dout << "ceph version " << VERSION << " (" << STRINGIFY(CEPH_GIT_VER) << ")" << std::endl; if (need_symlink) create_name_symlink(); } int dout_rename_output_file() // after calling daemon() { Mutex::Locker l(_dout_lock); if (log_to_file() && g_conf.log_per_instance) { char oldpath[PATH_MAX]; char hostname[80]; gethostname(hostname, 79); strcpy(oldpath, _dout_path); build_log_paths(); *_dout << "---- " << getpid() << " renamed log " << oldpath << " -> " << _dout_path << " ----" << std::endl; ::rename(oldpath, _dout_path); // $type.$id symlink if (g_conf.log_per_instance && _dout_name_symlink_path[0]) create_symlink(_dout_name_symlink_path); if (_dout_rank_symlink_path[0]) create_symlink(_dout_rank_symlink_path); } return 0; } int dout_create_rank_symlink(int64_t n) { Mutex::Locker l(_dout_lock); int r = 0; if (log_to_file() && !(g_conf.log_file && g_conf.log_file[0])) { if (_dout_need_open) _dout_open_log(); snprintf(_dout_rank_symlink_path, sizeof(_dout_rank_symlink_path), "%s/%s%lld", _dout_symlink_dir, g_conf.type, (long long)n); r = create_symlink(_dout_rank_symlink_path); } return r; } <|endoftext|>
<commit_before>/** @file * @brief Implementation of interface to the core framework * @copyright MIT License */ #include "AllPix.hpp" #include <chrono> #include <climits> #include <fstream> #include <memory> #include <stdexcept> #include <thread> #include <utility> #include <TROOT.h> #include <TRandom.h> #include <TStyle.h> #include <TSystem.h> #include "core/config/exceptions.h" #include "core/utils/file.h" #include "core/utils/log.h" #include "core/utils/unit.h" using namespace allpix; /** * This class will own the managers for the lifetime of the simulation. Will do early initialization: * - Configure the special header sections. * - Set the log level and log format as requested. * - Load the detector configuration and parse it */ AllPix::AllPix(std::string config_file_name) : terminate_(false), has_run_(false), msg_(std::make_unique<Messenger>()), mod_mgr_(std::make_unique<ModuleManager>()), geo_mgr_(std::make_unique<GeometryManager>()) { // Load the global configuration conf_mgr_ = std::make_unique<ConfigManager>(std::move(config_file_name)); // Configure the standard special sections conf_mgr_->setGlobalHeaderName("AllPix"); conf_mgr_->addGlobalHeaderName(""); conf_mgr_->addIgnoreHeaderName("Ignore"); // Fetch the global configuration Configuration global_config = conf_mgr_->getGlobalConfiguration(); // Set the log level from config if not specified earlier std::string log_level_string; if(Log::getReportingLevel() == LogLevel::NONE) { log_level_string = global_config.get<std::string>("log_level", "INFO"); std::transform(log_level_string.begin(), log_level_string.end(), log_level_string.begin(), ::toupper); try { LogLevel log_level = Log::getLevelFromString(log_level_string); Log::setReportingLevel(log_level); } catch(std::invalid_argument& e) { LOG(ERROR) << "Log level \"" << log_level_string << "\" specified in the configuration is invalid, defaulting to INFO instead"; Log::setReportingLevel(LogLevel::INFO); } } else { log_level_string = Log::getStringFromLevel(Log::getReportingLevel()); } // Set the log format from config std::string log_format_string = global_config.get<std::string>("log_format", "DEFAULT"); std::transform(log_format_string.begin(), log_format_string.end(), log_format_string.begin(), ::toupper); try { LogFormat log_format = Log::getFormatFromString(log_format_string); Log::setFormat(log_format); } catch(std::invalid_argument& e) { LOG(ERROR) << "Log format \"" << log_format_string << "\" specified in the configuration is invalid, using DEFAULT instead"; Log::setFormat(LogFormat::DEFAULT); } // Open log file to write output to if(global_config.has("log_file")) { // NOTE: this stream should be available for the duration of the logging log_file_.open(global_config.getPath("log_file"), std::ios_base::out | std::ios_base::trunc); Log::addStream(log_file_); } // Wait for the first detailed messages until level and format are properly set LOG(TRACE) << "Global log level is set to " << log_level_string; LOG(TRACE) << "Global log format is set to " << log_format_string; } /** * Performs the initialization, including: * - Initialize the random seeder * - Determine and create the output directory * - Include all the defined units * - Load the modules from the configuration */ void AllPix::load() { LOG(TRACE) << "Loading AllPix"; // Put welcome message LOG(STATUS) << "Welcome to AllPix " << ALLPIX_PROJECT_VERSION; // Fetch the global configuration Configuration global_config = conf_mgr_->getGlobalConfiguration(); // Initialize the random seeder std::mt19937_64 seeder; uint64_t seed = 0; if(global_config.has("random_seed")) { // Use provided random seed seed = global_config.get<uint64_t>("random_seed"); seeder.seed(seed); LOG(STATUS) << "Initialized PRNG with configured seed " << seed; } else { // Compute random entropy seed // Use the clock auto clock_seed = static_cast<uint64_t>(std::chrono::high_resolution_clock::now().time_since_epoch().count()); // Use memory location local variable auto mem_seed = reinterpret_cast<uint64_t>(&seed); // NOLINT // Use thread id std::hash<std::thread::id> thrd_hasher; auto thread_seed = thrd_hasher(std::this_thread::get_id()); seed = (clock_seed ^ mem_seed ^ thread_seed); seeder.seed(seed); LOG(STATUS) << "Initialized PRNG with system entropy seed " << seed; } // Initialize ROOT random generator gRandom->SetSeed(seeder()); // Get output directory LOG(TRACE) << "Switching to output directory"; std::string directory = gSystem->pwd(); directory += "/output"; if(global_config.has("output_directory")) { // Use config specified one if available directory = global_config.getPath("output_directory"); } // Set output directory (create if not exists) if(!gSystem->ChangeDirectory(directory.c_str())) { LOG(DEBUG) << "Creating output directory because it does not exists"; try { allpix::create_directories(directory); gSystem->ChangeDirectory(directory.c_str()); } catch(std::invalid_argument& e) { LOG(ERROR) << "Cannot create output directory " << directory << ": " << e.what() << ". Using current directory instead!"; } } // Set the default units to use add_units(); // Set the ROOT style set_style(); // Load the geometry geo_mgr_->load(global_config); // Load the modules from the configuration if(!terminate_) { mod_mgr_->load(msg_.get(), conf_mgr_.get(), geo_mgr_.get(), seeder); } else { LOG(INFO) << "Skip loading modules because termination is requested"; } } /** * Runs the Module::init() method linearly for every module */ void AllPix::init() { if(!terminate_) { LOG(TRACE) << "Initializing AllPix"; mod_mgr_->init(); } else { LOG(INFO) << "Skip initializing modules because termination is requested"; } } /** * Runs every modules Module::run() method linearly for the number of events */ void AllPix::run() { if(!terminate_) { LOG(TRACE) << "Running AllPix"; mod_mgr_->run(); // Set that we have run and want to finalize as well has_run_ = true; } else { LOG(INFO) << "Skip running modules because termination is requested"; } } /** * Runs all modules Module::finalize() method linearly for every module */ void AllPix::finalize() { if(has_run_) { LOG(TRACE) << "Finalizing AllPix"; mod_mgr_->finalize(); } else { LOG(INFO) << "Skip finalizing modules because no module did run"; } } /* * This function can be called safely from any signal handler. Time between the request to terminate * and the actual termination is not always negigible. */ void AllPix::terminate() { terminate_ = true; mod_mgr_->terminate(); } void AllPix::add_units() { LOG(TRACE) << "Adding physical units"; // LENGTH Units::add("nm", 1e-6); Units::add("um", 1e-3); Units::add("mm", 1); Units::add("cm", 1e1); Units::add("dm", 1e2); Units::add("m", 1e3); Units::add("km", 1e6); // TIME Units::add("ps", 1e-3); Units::add("ns", 1); Units::add("us", 1e3); Units::add("ms", 1e6); Units::add("s", 1e9); // TEMPERATURE Units::add("K", 1); // ENERGY Units::add("eV", 1e-6); Units::add("keV", 1e-3); Units::add("MeV", 1); Units::add("GeV", 1e3); // CHARGE Units::add("e", 1); Units::add("C", 1.6021766208e-19); // VOLTAGE // NOTE: fixed by above Units::add("V", 1e-6); Units::add("kV", 1e-3); // ANGLES // NOTE: these are fake units Units::add("deg", 0.01745329252); Units::add("rad", 1); } /** * This style is inspired by the CLICdp plot style */ void AllPix::set_style() { LOG(TRACE) << "Setting ROOT plotting style"; // use plain style as base gROOT->SetStyle("Plain"); TStyle* style = gROOT->GetStyle("Plain"); // Prefer OpenGL if available style->SetCanvasPreferGL(kTRUE); // Set backgrounds style->SetCanvasColor(kWhite); style->SetFrameFillColor(kWhite); style->SetStatColor(kWhite); style->SetPadColor(kWhite); style->SetFillColor(10); style->SetTitleFillColor(kWhite); // SetPaperSize wants width & height in cm: A4 is 20,26 style->SetPaperSize(20, 26); // No yellow border around histogram style->SetDrawBorder(0); // Remove border of canvas* style->SetCanvasBorderMode(0); // Remove border of pads style->SetPadBorderMode(0); style->SetFrameBorderMode(0); style->SetLegendBorderSize(0); // Default text size style->SetTextSize(0.04f); style->SetTitleSize(0.04f, "xyz"); style->SetLabelSize(0.03f, "xyz"); // Title offset: distance between given text and axis style->SetLabelOffset(0.01f, "xyz"); style->SetTitleOffset(1.6f, "yz"); style->SetTitleOffset(1.4f, "x"); // Set font settings short font = 42; // Use a clear font style->SetTitleFont(font); style->SetTitleFontSize(0.06f); style->SetStatFont(font); style->SetStatFontSize(0.07f); style->SetTextFont(font); style->SetLabelFont(font, "xyz"); style->SetTitleFont(font, "xyz"); style->SetTitleBorderSize(0); style->SetStatBorderSize(1); // Set style for markers style->SetMarkerStyle(1); style->SetLineWidth(2); style->SetMarkerSize(1.2f); // Set palette in 2d histogram to nice and colorful one style->SetPalette(1, nullptr); // Disable title by default for histograms style->SetOptTitle(0); // Set statistics style->SetOptStat(0); style->SetOptFit(0); // Number of decimals used for errors style->SetEndErrorSize(5); // Set line width to 2 by default so that histograms are visible when printed small // Idea: emphasize the data, not the frame around style->SetHistLineWidth(2); style->SetFrameLineWidth(2); style->SetFuncWidth(2); style->SetHistLineColor(kBlack); style->SetFuncColor(kRed); style->SetLabelColor(kBlack, "xyz"); // Set the margins style->SetPadBottomMargin(0.18f); style->SetPadTopMargin(0.08f); style->SetPadRightMargin(0.18f); style->SetPadLeftMargin(0.17f); // Set the default number of divisions to show style->SetNdivisions(506, "xy"); // Turn off xy grids style->SetPadGridX(false); style->SetPadGridY(false); // Set the tick mark style style->SetPadTickX(1); style->SetPadTickY(1); style->SetCanvasDefW(800); style->SetCanvasDefH(700); // Force the style gROOT->ForceStyle(); } <commit_msg>ROOT: enable Thread safety<commit_after>/** @file * @brief Implementation of interface to the core framework * @copyright MIT License */ #include "AllPix.hpp" #include <chrono> #include <climits> #include <fstream> #include <memory> #include <stdexcept> #include <thread> #include <utility> #include <TROOT.h> #include <TRandom.h> #include <TStyle.h> #include <TSystem.h> #include "core/config/exceptions.h" #include "core/utils/file.h" #include "core/utils/log.h" #include "core/utils/unit.h" using namespace allpix; /** * This class will own the managers for the lifetime of the simulation. Will do early initialization: * - Configure the special header sections. * - Set the log level and log format as requested. * - Load the detector configuration and parse it */ AllPix::AllPix(std::string config_file_name) : terminate_(false), has_run_(false), msg_(std::make_unique<Messenger>()), mod_mgr_(std::make_unique<ModuleManager>()), geo_mgr_(std::make_unique<GeometryManager>()) { // Load the global configuration conf_mgr_ = std::make_unique<ConfigManager>(std::move(config_file_name)); // Configure the standard special sections conf_mgr_->setGlobalHeaderName("AllPix"); conf_mgr_->addGlobalHeaderName(""); conf_mgr_->addIgnoreHeaderName("Ignore"); // Fetch the global configuration Configuration global_config = conf_mgr_->getGlobalConfiguration(); // Set the log level from config if not specified earlier std::string log_level_string; if(Log::getReportingLevel() == LogLevel::NONE) { log_level_string = global_config.get<std::string>("log_level", "INFO"); std::transform(log_level_string.begin(), log_level_string.end(), log_level_string.begin(), ::toupper); try { LogLevel log_level = Log::getLevelFromString(log_level_string); Log::setReportingLevel(log_level); } catch(std::invalid_argument& e) { LOG(ERROR) << "Log level \"" << log_level_string << "\" specified in the configuration is invalid, defaulting to INFO instead"; Log::setReportingLevel(LogLevel::INFO); } } else { log_level_string = Log::getStringFromLevel(Log::getReportingLevel()); } // Set the log format from config std::string log_format_string = global_config.get<std::string>("log_format", "DEFAULT"); std::transform(log_format_string.begin(), log_format_string.end(), log_format_string.begin(), ::toupper); try { LogFormat log_format = Log::getFormatFromString(log_format_string); Log::setFormat(log_format); } catch(std::invalid_argument& e) { LOG(ERROR) << "Log format \"" << log_format_string << "\" specified in the configuration is invalid, using DEFAULT instead"; Log::setFormat(LogFormat::DEFAULT); } // Open log file to write output to if(global_config.has("log_file")) { // NOTE: this stream should be available for the duration of the logging log_file_.open(global_config.getPath("log_file"), std::ios_base::out | std::ios_base::trunc); Log::addStream(log_file_); } // Wait for the first detailed messages until level and format are properly set LOG(TRACE) << "Global log level is set to " << log_level_string; LOG(TRACE) << "Global log format is set to " << log_format_string; } /** * Performs the initialization, including: * - Initialize the random seeder * - Determine and create the output directory * - Include all the defined units * - Load the modules from the configuration */ void AllPix::load() { LOG(TRACE) << "Loading AllPix"; // Put welcome message LOG(STATUS) << "Welcome to AllPix " << ALLPIX_PROJECT_VERSION; // Fetch the global configuration Configuration global_config = conf_mgr_->getGlobalConfiguration(); // Initialize the random seeder std::mt19937_64 seeder; uint64_t seed = 0; if(global_config.has("random_seed")) { // Use provided random seed seed = global_config.get<uint64_t>("random_seed"); seeder.seed(seed); LOG(STATUS) << "Initialized PRNG with configured seed " << seed; } else { // Compute random entropy seed // Use the clock auto clock_seed = static_cast<uint64_t>(std::chrono::high_resolution_clock::now().time_since_epoch().count()); // Use memory location local variable auto mem_seed = reinterpret_cast<uint64_t>(&seed); // NOLINT // Use thread id std::hash<std::thread::id> thrd_hasher; auto thread_seed = thrd_hasher(std::this_thread::get_id()); seed = (clock_seed ^ mem_seed ^ thread_seed); seeder.seed(seed); LOG(STATUS) << "Initialized PRNG with system entropy seed " << seed; } // Initialize ROOT random generator gRandom->SetSeed(seeder()); // Get output directory LOG(TRACE) << "Switching to output directory"; std::string directory = gSystem->pwd(); directory += "/output"; if(global_config.has("output_directory")) { // Use config specified one if available directory = global_config.getPath("output_directory"); } // Set output directory (create if not exists) if(!gSystem->ChangeDirectory(directory.c_str())) { LOG(DEBUG) << "Creating output directory because it does not exists"; try { allpix::create_directories(directory); gSystem->ChangeDirectory(directory.c_str()); } catch(std::invalid_argument& e) { LOG(ERROR) << "Cannot create output directory " << directory << ": " << e.what() << ". Using current directory instead!"; } } // Enable thread safety for ROOT ROOT::EnableThreadSafety(); // Set the default units to use add_units(); // Set the ROOT style set_style(); // Load the geometry geo_mgr_->load(global_config); // Load the modules from the configuration if(!terminate_) { mod_mgr_->load(msg_.get(), conf_mgr_.get(), geo_mgr_.get(), seeder); } else { LOG(INFO) << "Skip loading modules because termination is requested"; } } /** * Runs the Module::init() method linearly for every module */ void AllPix::init() { if(!terminate_) { LOG(TRACE) << "Initializing AllPix"; mod_mgr_->init(); } else { LOG(INFO) << "Skip initializing modules because termination is requested"; } } /** * Runs every modules Module::run() method linearly for the number of events */ void AllPix::run() { if(!terminate_) { LOG(TRACE) << "Running AllPix"; mod_mgr_->run(); // Set that we have run and want to finalize as well has_run_ = true; } else { LOG(INFO) << "Skip running modules because termination is requested"; } } /** * Runs all modules Module::finalize() method linearly for every module */ void AllPix::finalize() { if(has_run_) { LOG(TRACE) << "Finalizing AllPix"; mod_mgr_->finalize(); } else { LOG(INFO) << "Skip finalizing modules because no module did run"; } } /* * This function can be called safely from any signal handler. Time between the request to terminate * and the actual termination is not always negigible. */ void AllPix::terminate() { terminate_ = true; mod_mgr_->terminate(); } void AllPix::add_units() { LOG(TRACE) << "Adding physical units"; // LENGTH Units::add("nm", 1e-6); Units::add("um", 1e-3); Units::add("mm", 1); Units::add("cm", 1e1); Units::add("dm", 1e2); Units::add("m", 1e3); Units::add("km", 1e6); // TIME Units::add("ps", 1e-3); Units::add("ns", 1); Units::add("us", 1e3); Units::add("ms", 1e6); Units::add("s", 1e9); // TEMPERATURE Units::add("K", 1); // ENERGY Units::add("eV", 1e-6); Units::add("keV", 1e-3); Units::add("MeV", 1); Units::add("GeV", 1e3); // CHARGE Units::add("e", 1); Units::add("C", 1.6021766208e-19); // VOLTAGE // NOTE: fixed by above Units::add("V", 1e-6); Units::add("kV", 1e-3); // ANGLES // NOTE: these are fake units Units::add("deg", 0.01745329252); Units::add("rad", 1); } /** * This style is inspired by the CLICdp plot style */ void AllPix::set_style() { LOG(TRACE) << "Setting ROOT plotting style"; // use plain style as base gROOT->SetStyle("Plain"); TStyle* style = gROOT->GetStyle("Plain"); // Prefer OpenGL if available style->SetCanvasPreferGL(kTRUE); // Set backgrounds style->SetCanvasColor(kWhite); style->SetFrameFillColor(kWhite); style->SetStatColor(kWhite); style->SetPadColor(kWhite); style->SetFillColor(10); style->SetTitleFillColor(kWhite); // SetPaperSize wants width & height in cm: A4 is 20,26 style->SetPaperSize(20, 26); // No yellow border around histogram style->SetDrawBorder(0); // Remove border of canvas* style->SetCanvasBorderMode(0); // Remove border of pads style->SetPadBorderMode(0); style->SetFrameBorderMode(0); style->SetLegendBorderSize(0); // Default text size style->SetTextSize(0.04f); style->SetTitleSize(0.04f, "xyz"); style->SetLabelSize(0.03f, "xyz"); // Title offset: distance between given text and axis style->SetLabelOffset(0.01f, "xyz"); style->SetTitleOffset(1.6f, "yz"); style->SetTitleOffset(1.4f, "x"); // Set font settings short font = 42; // Use a clear font style->SetTitleFont(font); style->SetTitleFontSize(0.06f); style->SetStatFont(font); style->SetStatFontSize(0.07f); style->SetTextFont(font); style->SetLabelFont(font, "xyz"); style->SetTitleFont(font, "xyz"); style->SetTitleBorderSize(0); style->SetStatBorderSize(1); // Set style for markers style->SetMarkerStyle(1); style->SetLineWidth(2); style->SetMarkerSize(1.2f); // Set palette in 2d histogram to nice and colorful one style->SetPalette(1, nullptr); // Disable title by default for histograms style->SetOptTitle(0); // Set statistics style->SetOptStat(0); style->SetOptFit(0); // Number of decimals used for errors style->SetEndErrorSize(5); // Set line width to 2 by default so that histograms are visible when printed small // Idea: emphasize the data, not the frame around style->SetHistLineWidth(2); style->SetFrameLineWidth(2); style->SetFuncWidth(2); style->SetHistLineColor(kBlack); style->SetFuncColor(kRed); style->SetLabelColor(kBlack, "xyz"); // Set the margins style->SetPadBottomMargin(0.18f); style->SetPadTopMargin(0.08f); style->SetPadRightMargin(0.18f); style->SetPadLeftMargin(0.17f); // Set the default number of divisions to show style->SetNdivisions(506, "xy"); // Turn off xy grids style->SetPadGridX(false); style->SetPadGridY(false); // Set the tick mark style style->SetPadTickX(1); style->SetPadTickY(1); style->SetCanvasDefW(800); style->SetCanvasDefH(700); // Force the style gROOT->ForceStyle(); } <|endoftext|>
<commit_before>#include "i_core.h" #include "core/i_position_component.h" #include "core/i_move_component.h" Weapon::Weapon( int32_t Id ) : Item( Id ) , mCooldown( 0.0 ) , mShootCooldown( 1.0 ) , mShootAltCooldown( 1.0 ) , mScatter( 0 ) , mAltScatter( 0 ) { mType = ItemType::Weapon; } void Weapon::Update( double Seconds ) { Item::Update( Seconds ); double cd = mCooldown; cd -= Seconds; if( cd < 0 ) { cd = 0; } mCooldown = cd; } void Weapon::Shoot() { if( !mActor ) { return; } if( mCooldown != 0.0 ) { return; } Projectiles_t Projectiles; ShootImpl( Projectiles ); Scene& Scen( Scene::Get() ); double actorOrientation = mActor->Get<IPositionComponent>()->GetOrientation(); if( mScatter ) { actorOrientation += ( rand() % mScatter - mScatter / 2. ) * 0.01 * boost::math::double_constants::pi; } for( Projectiles_t::iterator i = Projectiles.begin(), e = Projectiles.end(); i != e; ++i ) { Shot& Proj = *i; Opt<IPositionComponent> projPositionC = Proj.Get<IPositionComponent>(); Opt<IPositionComponent> actorPositionC = mActor->Get<IPositionComponent>(); projPositionC->SetX( actorPositionC->GetX() ); projPositionC->SetY( actorPositionC->GetY() ); Proj.SetParent( *mActor ); projPositionC->SetOrientation( projPositionC->GetOrientation() + actorOrientation ); Proj.Get<IMoveComponent>()->SetHeading( projPositionC->GetOrientation() ); Scen.AddActor( &Proj ); } Projectiles.release().release(); mCooldown = mShootCooldown; } void Weapon::ShootAlt() { if( !mActor ) { return; } if( mCooldown != 0.0 ) { return; } Projectiles_t Projectiles; ShootAltImpl( Projectiles ); Scene& Scen( Scene::Get() ); Opt<IPositionComponent> actorPositionC = mActor->Get<IPositionComponent>(); double actorOrientation = actorPositionC->GetOrientation(); if( mAltScatter ) { actorOrientation += ( rand() % mAltScatter - mAltScatter / 2. ) * 0.01 * boost::math::double_constants::pi; } for( Projectiles_t::iterator i = Projectiles.begin(), e = Projectiles.end(); i != e; ++i ) { Shot& Proj = *i; Opt<IPositionComponent> projPositionC = Proj.Get<IPositionComponent>(); projPositionC->SetX( actorPositionC->GetX() ); projPositionC->SetY( actorPositionC->GetY() ); Proj.SetParent( *mActor ); projPositionC->SetOrientation( projPositionC->GetOrientation() + actorOrientation ); Proj.Get<IMoveComponent>()->SetHeading( projPositionC->GetOrientation() ); Scen.AddActor( &Proj ); } Projectiles.release().release(); mCooldown = mShootAltCooldown; } <commit_msg>C: linux build fix for enum type<commit_after>#include "i_core.h" #include "core/i_position_component.h" #include "core/i_move_component.h" Weapon::Weapon( int32_t Id ) : Item( Id ) , mCooldown( 0.0 ) , mShootCooldown( 1.0 ) , mShootAltCooldown( 1.0 ) , mScatter( 0 ) , mAltScatter( 0 ) { mType = Item::Weapon; } void Weapon::Update( double Seconds ) { Item::Update( Seconds ); double cd = mCooldown; cd -= Seconds; if( cd < 0 ) { cd = 0; } mCooldown = cd; } void Weapon::Shoot() { if( !mActor ) { return; } if( mCooldown != 0.0 ) { return; } Projectiles_t Projectiles; ShootImpl( Projectiles ); Scene& Scen( Scene::Get() ); double actorOrientation = mActor->Get<IPositionComponent>()->GetOrientation(); if( mScatter ) { actorOrientation += ( rand() % mScatter - mScatter / 2. ) * 0.01 * boost::math::double_constants::pi; } for( Projectiles_t::iterator i = Projectiles.begin(), e = Projectiles.end(); i != e; ++i ) { Shot& Proj = *i; Opt<IPositionComponent> projPositionC = Proj.Get<IPositionComponent>(); Opt<IPositionComponent> actorPositionC = mActor->Get<IPositionComponent>(); projPositionC->SetX( actorPositionC->GetX() ); projPositionC->SetY( actorPositionC->GetY() ); Proj.SetParent( *mActor ); projPositionC->SetOrientation( projPositionC->GetOrientation() + actorOrientation ); Proj.Get<IMoveComponent>()->SetHeading( projPositionC->GetOrientation() ); Scen.AddActor( &Proj ); } Projectiles.release().release(); mCooldown = mShootCooldown; } void Weapon::ShootAlt() { if( !mActor ) { return; } if( mCooldown != 0.0 ) { return; } Projectiles_t Projectiles; ShootAltImpl( Projectiles ); Scene& Scen( Scene::Get() ); Opt<IPositionComponent> actorPositionC = mActor->Get<IPositionComponent>(); double actorOrientation = actorPositionC->GetOrientation(); if( mAltScatter ) { actorOrientation += ( rand() % mAltScatter - mAltScatter / 2. ) * 0.01 * boost::math::double_constants::pi; } for( Projectiles_t::iterator i = Projectiles.begin(), e = Projectiles.end(); i != e; ++i ) { Shot& Proj = *i; Opt<IPositionComponent> projPositionC = Proj.Get<IPositionComponent>(); projPositionC->SetX( actorPositionC->GetX() ); projPositionC->SetY( actorPositionC->GetY() ); Proj.SetParent( *mActor ); projPositionC->SetOrientation( projPositionC->GetOrientation() + actorOrientation ); Proj.Get<IMoveComponent>()->SetHeading( projPositionC->GetOrientation() ); Scen.AddActor( &Proj ); } Projectiles.release().release(); mCooldown = mShootAltCooldown; } <|endoftext|>
<commit_before>#include "MipsExecutor.h" using namespace std; CMipsExecutor::CMipsExecutor(CMIPS& context) : m_context(context) { } CMipsExecutor::~CMipsExecutor() { Clear(); } void CMipsExecutor::Clear() { for(BlockList::iterator blockIterator(m_blocks.begin()); blockIterator != m_blocks.end(); blockIterator++) { delete *blockIterator; } m_blocks.clear(); m_blockBegin.clear(); m_blockEnd.clear(); } int CMipsExecutor::Execute(int cycles) { CBasicBlock* block = NULL; while(cycles > 0) { #ifdef _PSX uint32 address = m_context.m_pAddrTranslator(&m_context, 0, m_context.m_State.nPC); #else uint32 address = m_context.m_State.nPC; #endif if(block == NULL || address != block->GetBeginAddress()) { CBasicBlock* prevBlock = block; //Check if we can use the hint instead of looking through the map if(prevBlock != NULL) { block = prevBlock->GetBranchHint(); } if(block == NULL || address != block->GetBeginAddress()) { block = FindBlockStartingAt(address); if(block == NULL) { //We need to partition the space and compile the blocks PartitionFunction(address); block = FindBlockStartingAt(address); if(block == NULL) { throw runtime_error("Couldn't create block starting at address."); } } } if(prevBlock != NULL) { prevBlock->SetBranchHint(block); } if(!block->IsCompiled()) { block->Compile(); } } else if(block != NULL) { block->SetSelfLoopCount(block->GetSelfLoopCount() + 1); } cycles -= block->Execute(); if(m_context.m_State.nHasException) break; #ifdef DEBUGGER_INCLUDED if(MustBreak()) break; #endif } return cycles; } bool CMipsExecutor::MustBreak() const { #ifdef DEBUGGER_INCLUDED #ifdef _PSX uint32 currentPc = m_context.m_pAddrTranslator(&m_context, 0, m_context.m_State.nPC); #else uint32 currentPc = m_context.m_State.nPC; #endif CBasicBlock* block = FindBlockAt(currentPc); for(CMIPS::BreakpointSet::const_iterator breakPointIterator(m_context.m_breakpoints.begin()); breakPointIterator != m_context.m_breakpoints.end(); breakPointIterator++) { uint32 breakPointAddress = *breakPointIterator; if(currentPc == breakPointAddress) return true; if(block != NULL) { if(breakPointAddress >= block->GetBeginAddress() && breakPointAddress <= block->GetEndAddress()) return true; } } #endif return false; } CBasicBlock* CMipsExecutor::FindBlockAt(uint32 address) const { BlockBeginMap::const_iterator beginIterator = m_blockBegin.lower_bound(address); if(beginIterator == m_blockBegin.end()) return NULL; { CBasicBlock* block = beginIterator->second; if( address >= block->GetBeginAddress() && address <= block->GetEndAddress()) { return block; } } BlockEndMap::const_iterator endIterator = m_blockEnd.lower_bound(address); if(endIterator == m_blockEnd.end()) return NULL; { CBasicBlock* block = endIterator->second; if( address >= block->GetBeginAddress() && address <= block->GetEndAddress()) { return block; } } if(beginIterator->second != endIterator->second) { return NULL; } return beginIterator->second; } CBasicBlock* CMipsExecutor::FindBlockStartingAt(uint32 address) { BlockBeginMap::const_iterator beginIterator = m_blockBegin.find(address); if(beginIterator == m_blockBegin.end()) return NULL; return beginIterator->second; } void CMipsExecutor::CreateBlock(uint32 start, uint32 end) { { CBasicBlock* block = FindBlockAt(start); if(block != NULL) { //If the block starts and ends at the same place, block already exists and doesn't need //to be re-created uint32 otherBegin = block->GetBeginAddress(); uint32 otherEnd = block->GetEndAddress(); if((otherBegin == start) && (otherEnd == end)) { return; } if(otherEnd == end) { //Repartition the existing block if end of both blocks are the same DeleteBlock(block); CreateBlock(otherBegin, start - 4); assert(FindBlockAt(start) == NULL); } else if(otherBegin == start) { DeleteBlock(block); CreateBlock(end + 4, otherEnd); assert(FindBlockAt(end) == NULL); } else { //Delete the currently existing block otherwise printf("MipsExecutor: Warning. Deleting block at %0.8X.\r\n", block->GetEndAddress()); DeleteBlock(block); } } assert(m_blockBegin.find(start) == m_blockBegin.end()); assert(m_blockEnd.find(end) == m_blockEnd.end()); } assert(FindBlockAt(end) == NULL); { CBasicBlock* block = BlockFactory(m_context, start, end); m_blocks.push_back(block); m_blockBegin[start] = block; m_blockEnd[end] = block; } assert(m_blocks.size() == m_blockBegin.size()); assert(m_blockBegin.size() == m_blockEnd.size()); } void CMipsExecutor::DeleteBlock(CBasicBlock* block) { //Clear any hints that point to this block for(BlockList::const_iterator blockIterator(m_blocks.begin()); blockIterator != m_blocks.end(); blockIterator++) { CBasicBlock* currBlock = (*blockIterator); if(currBlock->GetBranchHint() == block) { currBlock->SetBranchHint(NULL); } } //Remove block from our lists m_blocks.remove(block); m_blockBegin.erase(block->GetBeginAddress()); m_blockEnd.erase(block->GetEndAddress()); assert(m_blocks.size() == m_blockBegin.size()); assert(m_blockBegin.size() == m_blockEnd.size()); delete block; } CBasicBlock* CMipsExecutor::BlockFactory(CMIPS& context, uint32 start, uint32 end) { return new CBasicBlock(context, start, end); } void CMipsExecutor::PartitionFunction(uint32 functionAddress) { typedef std::set<uint32> PartitionPointSet; uint32 endAddress = 0; PartitionPointSet partitionPoints; //Insert begin point partitionPoints.insert(functionAddress); //Find the end for(uint32 address = functionAddress; ; address += 4) { //Probably going too far... if((address - functionAddress) > 0x10000) { printf("MipsExecutor: Warning. Found no JR after a big distance.\r\n"); endAddress = address; partitionPoints.insert(endAddress); break; } uint32 opcode = m_context.m_pMemoryMap->GetInstruction(address); if(opcode == 0x03E00008) { //+4 for delay slot endAddress = address + 4; partitionPoints.insert(endAddress + 4); break; } } //Find partition points within the function for(uint32 address = functionAddress; address <= endAddress; address += 4) { uint32 opcode = m_context.m_pMemoryMap->GetInstruction(address); bool isBranch = m_context.m_pArch->IsInstructionBranch(&m_context, address, opcode); if(isBranch) { partitionPoints.insert(address + 8); uint32 target = m_context.m_pArch->GetInstructionEffectiveAddress(&m_context, address, opcode); if(target > functionAddress && target < endAddress) { partitionPoints.insert(target); } } //SYSCALL or ERET if(opcode == 0x0000000C || opcode == 0x42000018) { partitionPoints.insert(address + 4); } //Check if there's a block already exising that this address if(address != endAddress) { CBasicBlock* possibleBlock = FindBlockStartingAt(address); if(possibleBlock != NULL) { //assert(possibleBlock->GetEndAddress() <= endAddress); //Add its beginning and end in the partition points partitionPoints.insert(possibleBlock->GetBeginAddress()); partitionPoints.insert(possibleBlock->GetEndAddress() + 4); } } } uint32 currentPoint = 0; for(PartitionPointSet::const_iterator pointIterator(partitionPoints.begin()); pointIterator != partitionPoints.end(); pointIterator++) { if(currentPoint != 0) { CreateBlock(currentPoint, *pointIterator - 4); } currentPoint = *pointIterator; } } <commit_msg>Fixed memory corruption bug.<commit_after>#include "MipsExecutor.h" using namespace std; CMipsExecutor::CMipsExecutor(CMIPS& context) : m_context(context) { } CMipsExecutor::~CMipsExecutor() { Clear(); } void CMipsExecutor::Clear() { for(BlockList::iterator blockIterator(m_blocks.begin()); blockIterator != m_blocks.end(); blockIterator++) { delete *blockIterator; } m_blocks.clear(); m_blockBegin.clear(); m_blockEnd.clear(); } int CMipsExecutor::Execute(int cycles) { CBasicBlock* block = NULL; while(cycles > 0) { #ifdef _PSX uint32 address = m_context.m_pAddrTranslator(&m_context, 0, m_context.m_State.nPC); #else uint32 address = m_context.m_State.nPC; #endif if(block == NULL || address != block->GetBeginAddress()) { CBasicBlock* prevBlock = block; //Check if we can use the hint instead of looking through the map if(prevBlock != NULL) { block = prevBlock->GetBranchHint(); } if(block == NULL || address != block->GetBeginAddress()) { block = FindBlockStartingAt(address); if(block == NULL) { //We need to partition the space and compile the blocks PartitionFunction(address); //Invalidate prevBlock because it might have been deleted by PartitionFunction prevBlock = NULL; block = FindBlockStartingAt(address); if(block == NULL) { throw runtime_error("Couldn't create block starting at address."); } } } if(prevBlock != NULL) { prevBlock->SetBranchHint(block); } if(!block->IsCompiled()) { block->Compile(); } } else if(block != NULL) { block->SetSelfLoopCount(block->GetSelfLoopCount() + 1); } cycles -= block->Execute(); if(m_context.m_State.nHasException) break; #ifdef DEBUGGER_INCLUDED if(MustBreak()) break; #endif } return cycles; } bool CMipsExecutor::MustBreak() const { #ifdef DEBUGGER_INCLUDED #ifdef _PSX uint32 currentPc = m_context.m_pAddrTranslator(&m_context, 0, m_context.m_State.nPC); #else uint32 currentPc = m_context.m_State.nPC; #endif CBasicBlock* block = FindBlockAt(currentPc); for(CMIPS::BreakpointSet::const_iterator breakPointIterator(m_context.m_breakpoints.begin()); breakPointIterator != m_context.m_breakpoints.end(); breakPointIterator++) { uint32 breakPointAddress = *breakPointIterator; if(currentPc == breakPointAddress) return true; if(block != NULL) { if(breakPointAddress >= block->GetBeginAddress() && breakPointAddress <= block->GetEndAddress()) return true; } } #endif return false; } CBasicBlock* CMipsExecutor::FindBlockAt(uint32 address) const { BlockBeginMap::const_iterator beginIterator = m_blockBegin.lower_bound(address); if(beginIterator == m_blockBegin.end()) return NULL; { CBasicBlock* block = beginIterator->second; if( address >= block->GetBeginAddress() && address <= block->GetEndAddress()) { return block; } } BlockEndMap::const_iterator endIterator = m_blockEnd.lower_bound(address); if(endIterator == m_blockEnd.end()) return NULL; { CBasicBlock* block = endIterator->second; if( address >= block->GetBeginAddress() && address <= block->GetEndAddress()) { return block; } } if(beginIterator->second != endIterator->second) { return NULL; } return beginIterator->second; } CBasicBlock* CMipsExecutor::FindBlockStartingAt(uint32 address) { BlockBeginMap::const_iterator beginIterator = m_blockBegin.find(address); if(beginIterator == m_blockBegin.end()) return NULL; return beginIterator->second; } void CMipsExecutor::CreateBlock(uint32 start, uint32 end) { { CBasicBlock* block = FindBlockAt(start); if(block != NULL) { //If the block starts and ends at the same place, block already exists and doesn't need //to be re-created uint32 otherBegin = block->GetBeginAddress(); uint32 otherEnd = block->GetEndAddress(); if((otherBegin == start) && (otherEnd == end)) { return; } if(otherEnd == end) { //Repartition the existing block if end of both blocks are the same DeleteBlock(block); CreateBlock(otherBegin, start - 4); assert(FindBlockAt(start) == NULL); } else if(otherBegin == start) { DeleteBlock(block); CreateBlock(end + 4, otherEnd); assert(FindBlockAt(end) == NULL); } else { //Delete the currently existing block otherwise printf("MipsExecutor: Warning. Deleting block at %0.8X.\r\n", block->GetEndAddress()); DeleteBlock(block); } } assert(m_blockBegin.find(start) == m_blockBegin.end()); assert(m_blockEnd.find(end) == m_blockEnd.end()); } assert(FindBlockAt(end) == NULL); { CBasicBlock* block = BlockFactory(m_context, start, end); m_blocks.push_back(block); m_blockBegin[start] = block; m_blockEnd[end] = block; } assert(m_blocks.size() == m_blockBegin.size()); assert(m_blockBegin.size() == m_blockEnd.size()); } void CMipsExecutor::DeleteBlock(CBasicBlock* block) { //Clear any hints that point to this block for(BlockList::const_iterator blockIterator(m_blocks.begin()); blockIterator != m_blocks.end(); blockIterator++) { CBasicBlock* currBlock = (*blockIterator); if(currBlock->GetBranchHint() == block) { currBlock->SetBranchHint(NULL); } } //Remove block from our lists m_blocks.remove(block); m_blockBegin.erase(block->GetBeginAddress()); m_blockEnd.erase(block->GetEndAddress()); assert(m_blocks.size() == m_blockBegin.size()); assert(m_blockBegin.size() == m_blockEnd.size()); delete block; } CBasicBlock* CMipsExecutor::BlockFactory(CMIPS& context, uint32 start, uint32 end) { return new CBasicBlock(context, start, end); } void CMipsExecutor::PartitionFunction(uint32 functionAddress) { typedef std::set<uint32> PartitionPointSet; uint32 endAddress = 0; PartitionPointSet partitionPoints; //Insert begin point partitionPoints.insert(functionAddress); //Find the end for(uint32 address = functionAddress; ; address += 4) { //Probably going too far... if((address - functionAddress) > 0x10000) { printf("MipsExecutor: Warning. Found no JR after a big distance.\r\n"); endAddress = address; partitionPoints.insert(endAddress); break; } uint32 opcode = m_context.m_pMemoryMap->GetInstruction(address); if(opcode == 0x03E00008) { //+4 for delay slot endAddress = address + 4; partitionPoints.insert(endAddress + 4); break; } } //Find partition points within the function for(uint32 address = functionAddress; address <= endAddress; address += 4) { uint32 opcode = m_context.m_pMemoryMap->GetInstruction(address); bool isBranch = m_context.m_pArch->IsInstructionBranch(&m_context, address, opcode); if(isBranch) { partitionPoints.insert(address + 8); uint32 target = m_context.m_pArch->GetInstructionEffectiveAddress(&m_context, address, opcode); if(target > functionAddress && target < endAddress) { partitionPoints.insert(target); } } //SYSCALL or ERET if(opcode == 0x0000000C || opcode == 0x42000018) { partitionPoints.insert(address + 4); } //Check if there's a block already exising that this address if(address != endAddress) { CBasicBlock* possibleBlock = FindBlockStartingAt(address); if(possibleBlock != NULL) { //assert(possibleBlock->GetEndAddress() <= endAddress); //Add its beginning and end in the partition points partitionPoints.insert(possibleBlock->GetBeginAddress()); partitionPoints.insert(possibleBlock->GetEndAddress() + 4); } } } uint32 currentPoint = 0; for(PartitionPointSet::const_iterator pointIterator(partitionPoints.begin()); pointIterator != partitionPoints.end(); pointIterator++) { if(currentPoint != 0) { CreateBlock(currentPoint, *pointIterator - 4); } currentPoint = *pointIterator; } } <|endoftext|>
<commit_before>// // TextUtilties.hpp // SwingGame // // Created by Tim Brier on 25/09/2014. // Copyright (c) 2014 tbrier. All rights reserved. // #ifndef __SwingGame__TextUtilties__ #define __SwingGame__TextUtilties__ // ============================================================================= // Include Files // ----------------------------------------------------------------------------- #include "SFMLIntegration.hpp" #include "Enums.hpp" // ============================================================================= // Class Definition // ----------------------------------------------------------------------------- namespace TextUtilities { // Load or get the desired font CFont * GetFont(EFontType fontType); // Delete all loaded fonts void DeleteFonts(); // Cleanup before quitting void Cleanup(); }; #endif /* defined(__SwingGame__TextUtilties__) */ <commit_msg>Class->namespace<commit_after>// // TextUtilties.hpp // SwingGame // // Created by Tim Brier on 25/09/2014. // Copyright (c) 2014 tbrier. All rights reserved. // #ifndef __SwingGame__TextUtilties__ #define __SwingGame__TextUtilties__ // ============================================================================= // Include Files // ----------------------------------------------------------------------------- #include "SFMLIntegration.hpp" #include "Enums.hpp" // ============================================================================= // Namespace Definition // ----------------------------------------------------------------------------- namespace TextUtilities { // Load or get the desired font CFont * GetFont(EFontType fontType); // Delete all loaded fonts void DeleteFonts(); // Cleanup before quitting void Cleanup(); }; #endif /* defined(__SwingGame__TextUtilties__) */ <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2017 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef POSTGIS_CONNECTION_MANAGER_HPP #define POSTGIS_CONNECTION_MANAGER_HPP #include "connection.hpp" // mapnik #include <mapnik/pool.hpp> #include <mapnik/util/singleton.hpp> // boost #include <memory> #include <boost/optional.hpp> // stl #include <string> #include <sstream> #include <memory> using mapnik::Pool; using mapnik::singleton; using mapnik::CreateStatic; template <typename T> class ConnectionCreator { public: ConnectionCreator(boost::optional<std::string> const& host, boost::optional<std::string> const& port, boost::optional<std::string> const& dbname, boost::optional<std::string> const& user, boost::optional<std::string> const& pass, boost::optional<std::string> const& connect_timeout) : host_(host), port_(port), dbname_(dbname), user_(user), pass_(pass), connect_timeout_(connect_timeout) {} T* operator()() const { return new T(connection_string_safe(),pass_); } inline std::string id() const { return connection_string(); } inline std::string connection_string() const { std::string connect_str = connection_string_safe(); if (pass_ && !pass_->empty()) connect_str += " password=" + *pass_; return connect_str; } inline std::string connection_string_safe() const { std::string connect_str; if (host_ && !host_->empty()) connect_str += "host=" + *host_; if (port_ && !port_->empty()) connect_str += " port=" + *port_; if (dbname_ && !dbname_->empty()) connect_str += " dbname=" + *dbname_; if (user_ && !user_->empty()) connect_str += " user=" + *user_; if (connect_timeout_ && !connect_timeout_->empty()) connect_str +=" connect_timeout=" + *connect_timeout_; return connect_str; } private: boost::optional<std::string> host_; boost::optional<std::string> port_; boost::optional<std::string> dbname_; boost::optional<std::string> user_; boost::optional<std::string> pass_; boost::optional<std::string> connect_timeout_; }; class ConnectionManager : public singleton <ConnectionManager,CreateStatic> { public: using PoolType = Pool<Connection,ConnectionCreator>; private: friend class CreateStatic<ConnectionManager>; using ContType = std::map<std::string,std::shared_ptr<PoolType> >; using HolderType = std::shared_ptr<Connection>; ContType pools_; public: bool registerPool(ConnectionCreator<Connection> const& creator,unsigned initialSize,unsigned maxSize) { ContType::const_iterator itr = pools_.find(creator.id()); if (itr != pools_.end()) { itr->second->set_initial_size(initialSize); itr->second->set_max_size(maxSize); } else { return pools_.insert( std::make_pair(creator.id(), std::make_shared<PoolType>(creator,initialSize,maxSize))).second; } return false; } std::shared_ptr<PoolType> getPool(std::string const& key) { ContType::const_iterator itr=pools_.find(key); if (itr!=pools_.end()) { return itr->second; } static const std::shared_ptr<PoolType> emptyPool; return emptyPool; } ConnectionManager() {} private: ConnectionManager(const ConnectionManager&); ConnectionManager& operator=(const ConnectionManager); }; #endif // POSTGIS_CONNECTION_MANAGER_HPP <commit_msg>postgis: Thread safe ConnectionManager<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2017 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef POSTGIS_CONNECTION_MANAGER_HPP #define POSTGIS_CONNECTION_MANAGER_HPP #include "connection.hpp" // mapnik #include <mapnik/pool.hpp> #include <mapnik/util/singleton.hpp> // boost #include <memory> #include <boost/optional.hpp> // stl #include <string> #include <sstream> #include <memory> using mapnik::Pool; using mapnik::singleton; using mapnik::CreateStatic; template <typename T> class ConnectionCreator { public: ConnectionCreator(boost::optional<std::string> const& host, boost::optional<std::string> const& port, boost::optional<std::string> const& dbname, boost::optional<std::string> const& user, boost::optional<std::string> const& pass, boost::optional<std::string> const& connect_timeout) : host_(host), port_(port), dbname_(dbname), user_(user), pass_(pass), connect_timeout_(connect_timeout) {} T* operator()() const { return new T(connection_string_safe(),pass_); } inline std::string id() const { return connection_string(); } inline std::string connection_string() const { std::string connect_str = connection_string_safe(); if (pass_ && !pass_->empty()) connect_str += " password=" + *pass_; return connect_str; } inline std::string connection_string_safe() const { std::string connect_str; if (host_ && !host_->empty()) connect_str += "host=" + *host_; if (port_ && !port_->empty()) connect_str += " port=" + *port_; if (dbname_ && !dbname_->empty()) connect_str += " dbname=" + *dbname_; if (user_ && !user_->empty()) connect_str += " user=" + *user_; if (connect_timeout_ && !connect_timeout_->empty()) connect_str +=" connect_timeout=" + *connect_timeout_; return connect_str; } private: boost::optional<std::string> host_; boost::optional<std::string> port_; boost::optional<std::string> dbname_; boost::optional<std::string> user_; boost::optional<std::string> pass_; boost::optional<std::string> connect_timeout_; }; class ConnectionManager : public singleton <ConnectionManager,CreateStatic> { public: using PoolType = Pool<Connection,ConnectionCreator>; private: friend class CreateStatic<ConnectionManager>; using ContType = std::map<std::string,std::shared_ptr<PoolType> >; using HolderType = std::shared_ptr<Connection>; ContType pools_; public: bool registerPool(ConnectionCreator<Connection> const& creator,unsigned initialSize,unsigned maxSize) { #ifdef MAPNIK_THREADSAFE std::lock_guard<std::mutex> lock(mutex_); #endif ContType::const_iterator itr = pools_.find(creator.id()); if (itr != pools_.end()) { itr->second->set_initial_size(initialSize); itr->second->set_max_size(maxSize); } else { return pools_.insert( std::make_pair(creator.id(), std::make_shared<PoolType>(creator,initialSize,maxSize))).second; } return false; } std::shared_ptr<PoolType> getPool(std::string const& key) { #ifdef MAPNIK_THREADSAFE std::lock_guard<std::mutex> lock(mutex_); #endif ContType::const_iterator itr=pools_.find(key); if (itr!=pools_.end()) { return itr->second; } static const std::shared_ptr<PoolType> emptyPool; return emptyPool; } ConnectionManager() {} private: ConnectionManager(const ConnectionManager&); ConnectionManager& operator=(const ConnectionManager); }; #endif // POSTGIS_CONNECTION_MANAGER_HPP <|endoftext|>
<commit_before>/* * MIT License * * Copyright (c) 2009-2018 Jingwood, unvell.com. All right reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "stdafx.h" #include "Text.h" D2DLIB_API void DrawString(HANDLE ctx, LPCWSTR text, D2D1_COLOR_F color, LPCWSTR fontName, FLOAT fontSize, D2D1_RECT_F* rect, DWRITE_TEXT_ALIGNMENT halign, DWRITE_PARAGRAPH_ALIGNMENT valign) { RetrieveContext(ctx); IDWriteTextFormat* textFormat = NULL; ID2D1SolidColorBrush* brush = NULL; // Create a DirectWrite text format object. HRESULT hr = context->writeFactory->CreateTextFormat(fontName, NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, fontSize, L"", //locale &textFormat); if (SUCCEEDED(hr)) { textFormat->SetTextAlignment(halign); textFormat->SetParagraphAlignment(valign); // Create a solid color brush. hr = (context->renderTarget)->CreateSolidColorBrush(color, &brush); if (SUCCEEDED(hr) && brush != NULL) { context->renderTarget->DrawText(text, wcslen(text), textFormat, rect, brush); } } SafeRelease(&brush); SafeRelease(&textFormat); } D2DLIB_API HANDLE CreateTextLayout(HANDLE ctx, LPCWSTR text, LPCWSTR fontName, FLOAT fontSize, D2D1_SIZE_F* size) { RetrieveContext(ctx); IDWriteTextFormat* textFormat = NULL; HRESULT hr = context->writeFactory->CreateTextFormat(fontName, NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, fontSize, L"", //locale &textFormat); if (SUCCEEDED(hr) && textFormat != NULL) { IDWriteTextLayout* textLayout; hr = context->writeFactory->CreateTextLayout( text, // The string to be laid out and formatted. wcslen(text), // The length of the string. textFormat, // The text format to apply to the string (contains font information, etc). size->width, // The width of the layout box. size->height, // The height of the layout box. &textLayout // The IDWriteTextLayout interface pointer. ); if (SUCCEEDED(hr) && textLayout != NULL) { return (HANDLE)textLayout; } } SafeRelease(&textFormat); return NULL; } D2DLIB_API void MeasureText(HANDLE ctx, LPCWSTR text, LPCWSTR fontName, FLOAT fontSize, D2D1_SIZE_F* size) { RetrieveContext(ctx); IDWriteTextLayout* textLayout = (IDWriteTextLayout*)CreateTextLayout(ctx, text, fontName, fontSize, size); if (textLayout != NULL) { DWRITE_TEXT_METRICS tm; textLayout->GetMetrics(&tm); size->width = tm.width; size->height = tm.height; } SafeRelease(&textLayout); } void DrawGlyphRun(HANDLE ctx, D2D1_POINT_2F baselineOrigin, const DWRITE_GLYPH_RUN *glyphRun, D2D1_COLOR_F color, DWRITE_MEASURING_MODE measuringMode) { D2DContext* context = reinterpret_cast<D2DContext*>(ctx); } //void DrawTextLayout(HANDLE ctx, D2D1_POINT_2F origin, // [in] IDWriteTextLayout *textLayout, // [in] ID2D1Brush *defaultForegroundBrush, // D2D1_DRAW_TEXT_OPTIONS options = D2D1_DRAW_TEXT_OPTIONS_NONE //) //{ //}<commit_msg>minor code refactoring<commit_after>/* * MIT License * * Copyright (c) 2009-2018 Jingwood, unvell.com. All right reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "stdafx.h" #include "Text.h" D2DLIB_API void DrawString(HANDLE ctx, LPCWSTR text, D2D1_COLOR_F color, LPCWSTR fontName, FLOAT fontSize, D2D1_RECT_F* rect, DWRITE_TEXT_ALIGNMENT halign, DWRITE_PARAGRAPH_ALIGNMENT valign) { RetrieveContext(ctx); ID2D1SolidColorBrush* brush = NULL; IDWriteTextFormat* textFormat = NULL; HRESULT hr = context->writeFactory->CreateTextFormat(fontName, NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, fontSize, L"", //locale &textFormat); if (SUCCEEDED(hr) && textFormat != NULL) { textFormat->SetTextAlignment(halign); textFormat->SetParagraphAlignment(valign); // Create a solid color brush. hr = (context->renderTarget)->CreateSolidColorBrush(color, &brush); if (SUCCEEDED(hr) && brush != NULL) { context->renderTarget->DrawText(text, wcslen(text), textFormat, rect, brush); } } SafeRelease(&brush); SafeRelease(&textFormat); } D2DLIB_API HANDLE CreateTextLayout(HANDLE ctx, LPCWSTR text, LPCWSTR fontName, FLOAT fontSize, D2D1_SIZE_F* size) { RetrieveContext(ctx); IDWriteTextFormat* textFormat = NULL; HRESULT hr = context->writeFactory->CreateTextFormat(fontName, NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, fontSize, L"", //locale &textFormat); if (SUCCEEDED(hr) && textFormat != NULL) { IDWriteTextLayout* textLayout; hr = context->writeFactory->CreateTextLayout( text, // The string to be laid out and formatted. wcslen(text), // The length of the string. textFormat, // The text format to apply to the string (contains font information, etc). size->width, // The width of the layout box. size->height, // The height of the layout box. &textLayout // The IDWriteTextLayout interface pointer. ); if (SUCCEEDED(hr) && textLayout != NULL) { return (HANDLE)textLayout; } } SafeRelease(&textFormat); return NULL; } D2DLIB_API void MeasureText(HANDLE ctx, LPCWSTR text, LPCWSTR fontName, FLOAT fontSize, D2D1_SIZE_F* size) { RetrieveContext(ctx); IDWriteTextLayout* textLayout = (IDWriteTextLayout*)CreateTextLayout(ctx, text, fontName, fontSize, size); if (textLayout != NULL) { DWRITE_TEXT_METRICS tm; textLayout->GetMetrics(&tm); size->width = tm.width; size->height = tm.height; } SafeRelease(&textLayout); } void DrawGlyphRun(HANDLE ctx, D2D1_POINT_2F baselineOrigin, const DWRITE_GLYPH_RUN *glyphRun, D2D1_COLOR_F color, DWRITE_MEASURING_MODE measuringMode) { D2DContext* context = reinterpret_cast<D2DContext*>(ctx); } //void DrawTextLayout(HANDLE ctx, D2D1_POINT_2F origin, // [in] IDWriteTextLayout *textLayout, // [in] ID2D1Brush *defaultForegroundBrush, // D2D1_DRAW_TEXT_OPTIONS options = D2D1_DRAW_TEXT_OPTIONS_NONE //) //{ //}<|endoftext|>
<commit_before>#include "global_include.h" #include "device_impl.h" #include "dronelink_impl.h" #include <unistd.h> namespace dronelink { DeviceImpl::DeviceImpl(DroneLinkImpl *parent) : _mavlink_handler_table(), _timeout_handler_map_mutex(), _timeout_handler_map(), _target_system_id(0), _target_component_id(0), _target_uuid(0), _target_supports_mission_int(false), _parent(parent), _command_result(MAV_RESULT_FAILED), _command_state(CommandState::NONE), _result_callback_data({nullptr, nullptr}), _device_thread(nullptr), _should_exit(false), _timeout_s(DEFAULT_TIMEOUT_S) { using namespace std::placeholders; // for `_1` register_mavlink_message_handler(MAVLINK_MSG_ID_HEARTBEAT, std::bind(&DeviceImpl::process_heartbeat, this, _1), this); register_mavlink_message_handler(MAVLINK_MSG_ID_COMMAND_ACK, std::bind(&DeviceImpl::process_command_ack, this, _1), this); register_mavlink_message_handler(MAVLINK_MSG_ID_AUTOPILOT_VERSION, std::bind(&DeviceImpl::process_autopilot_version, this, _1), this); } DeviceImpl::~DeviceImpl() { _should_exit = true; unregister_all_mavlink_message_handlers(this); if (_device_thread != nullptr) { _device_thread->join(); delete _device_thread; _device_thread = nullptr; } } void DeviceImpl::register_mavlink_message_handler(uint8_t msg_id, mavlink_message_handler_t callback, const void *cookie) { MavlinkHandlerTableEntry entry = {msg_id, callback, cookie}; _mavlink_handler_table.push_back(entry); } void DeviceImpl::unregister_all_mavlink_message_handlers(const void *cookie) { for (auto it = _mavlink_handler_table.begin(); it != _mavlink_handler_table.end(); /* no ++it */) { if (it->cookie == cookie) { it = _mavlink_handler_table.erase(it); } else { ++it; } } } void DeviceImpl::register_timeout_handler(timeout_handler_t callback, const void *cookie) { std::lock_guard<std::mutex> lock(_timeout_handler_map_mutex); dl_time_t future_time = steady_time_in_future(_timeout_s); TimeoutHandlerMapEntry entry = {future_time, callback}; _timeout_handler_map.insert({cookie, entry}); } void DeviceImpl::update_timeout_handler(const void *cookie) { std::lock_guard<std::mutex> lock(_timeout_handler_map_mutex); auto it = _timeout_handler_map.find(cookie); if (it != _timeout_handler_map.end()) { dl_time_t future_time = steady_time_in_future(_timeout_s); it->second.time = future_time; } } void DeviceImpl::unregister_timeout_handler(const void *cookie) { std::lock_guard<std::mutex> lock(_timeout_handler_map_mutex); auto it = _timeout_handler_map.find(cookie); if (it != _timeout_handler_map.end()) { _timeout_handler_map.erase(cookie); } } void DeviceImpl::process_mavlink_message(const mavlink_message_t &message) { for (auto it = _mavlink_handler_table.begin(); it != _mavlink_handler_table.end(); ++it) { if (it->msg_id == message.msgid) { it->callback(message); } } } void DeviceImpl::process_heartbeat(const mavlink_message_t &message) { mavlink_heartbeat_t heartbeat; mavlink_msg_heartbeat_decode(&message, &heartbeat); if (_target_system_id == 0) { _target_system_id = message.sysid; _target_component_id = message.compid; } if (_target_uuid == 0) { request_autopilot_version(); } check_device_thread(); } void DeviceImpl::process_command_ack(const mavlink_message_t &message) { mavlink_command_ack_t command_ack; mavlink_msg_command_ack_decode(&message, &command_ack); // Ignore it if we're not waiting for an ack result. if (_command_state == CommandState::WAITING) { _command_result = (MAV_RESULT)command_ack.result; // Update state after result to avoid a race over _command_result _command_state = CommandState::RECEIVED; if (_command_result == MAV_RESULT_ACCEPTED) { report_result(_result_callback_data, Result::SUCCESS); } else { report_result(_result_callback_data, Result::COMMAND_DENIED); } _result_callback_data.callback = nullptr; _result_callback_data.user = nullptr; } } void DeviceImpl::process_autopilot_version(const mavlink_message_t &message) { mavlink_autopilot_version_t autopilot_version; mavlink_msg_autopilot_version_decode(&message, &autopilot_version); _target_uuid = autopilot_version.uid; _target_supports_mission_int = autopilot_version.capabilities & MAV_PROTOCOL_CAPABILITY_MISSION_INT; } void DeviceImpl::check_device_thread() { if (_device_thread == nullptr) { _device_thread = new std::thread(device_thread, this); } } void DeviceImpl::device_thread(DeviceImpl *parent) { const unsigned heartbeat_interval_us = 1000000; const unsigned timeout_interval_us = 10000; const unsigned heartbeat_multiplier = heartbeat_interval_us / timeout_interval_us; unsigned counter = 0; while (!parent->_should_exit) { if (counter++ % heartbeat_multiplier == 0) { send_heartbeat(parent); } check_timeouts(parent); usleep(timeout_interval_us); } } void DeviceImpl::send_heartbeat(DeviceImpl *parent) { mavlink_message_t message; mavlink_msg_heartbeat_pack(_own_system_id, _own_component_id, &message, MAV_TYPE_GCS, 0, 0, 0, 0); parent->send_message(message); } void DeviceImpl::check_timeouts(DeviceImpl *parent) { timeout_handler_t callback = nullptr; { std::lock_guard<std::mutex> lock(parent->_timeout_handler_map_mutex); for (auto it = parent->_timeout_handler_map.begin(); it != parent->_timeout_handler_map.end(); /* no ++it */) { // If time is passed, call timeout callback. if (it->second.time < steady_time()) { callback = it->second.callback; //Self-destruct before calling to avoid locking issues. parent->_timeout_handler_map.erase(it++); break; } else { ++it; } } } // Now that the lock is out of scope and therefore unlocked, we're safe // to call the callback if set which might in turn register new timeout callbacks. if (callback != nullptr) { callback(); } } Result DeviceImpl::send_message(const mavlink_message_t &message) { return _parent->send_message(message); } void DeviceImpl::request_autopilot_version() { send_command(MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES, {1.0f, NAN, NAN, NAN, NAN, NAN, NAN}); } uint64_t DeviceImpl::get_target_uuid() const { return _target_uuid; } uint8_t DeviceImpl::get_target_system_id() const { return _target_system_id; } uint8_t DeviceImpl::get_target_component_id() const { return _target_component_id; } Result DeviceImpl::send_command(uint16_t command, const DeviceImpl::CommandParams &params) { if (_target_system_id == 0 && _target_component_id == 0) { return Result::DEVICE_NOT_CONNECTED; } if (_command_state == CommandState::WAITING) { return Result::DEVICE_BUSY; } mavlink_message_t message; mavlink_msg_command_long_pack(_own_system_id, _own_component_id, &message, _target_system_id, _target_component_id, command, 0, params.v[0], params.v[1], params.v[2], params.v[3], params.v[4], params.v[5], params.v[6]); Result ret = _parent->send_message(message); if (ret != Result::SUCCESS) { return ret; } return Result::SUCCESS; } Result DeviceImpl::send_command_with_ack(uint16_t command, const DeviceImpl::CommandParams &params) { if (_command_state == CommandState::WAITING) { return Result::DEVICE_BUSY; } // No callback here, so let's make sure it's reset _result_callback_data.callback = nullptr; _result_callback_data.user = nullptr; _command_state = CommandState::WAITING; Result ret = send_command(command, params); if (ret != Result::SUCCESS) { return ret; } const unsigned timeout_us = unsigned(_timeout_s * 1e6); const unsigned wait_time_us = 1000; const unsigned iterations = timeout_us/wait_time_us; // Wait until we have received a result. for (unsigned i = 0; i < iterations; ++i) { if (_command_state == CommandState::RECEIVED) { break; } usleep(wait_time_us); } if (_command_state != CommandState::RECEIVED) { _command_state = CommandState::NONE; return Result::TIMEOUT; } // Reset _command_state = CommandState::NONE; if (_command_result != MAV_RESULT_ACCEPTED) { return Result::COMMAND_DENIED; } return Result::SUCCESS; } void DeviceImpl::send_command_with_ack_async(uint16_t command, const DeviceImpl::CommandParams &params, ResultCallbackData callback_data) { if (_command_state == CommandState::WAITING) { report_result(callback_data, Result::DEVICE_BUSY); } Result ret = send_command(command, params); if (ret != Result::SUCCESS) { report_result(callback_data, ret); // Reset _command_state = CommandState::NONE; return; } _command_state = CommandState::WAITING; _result_callback_data = callback_data; } void DeviceImpl::report_result(ResultCallbackData callback_data, Result result) { // Never use a nullptr as a callback, this is not an error // because in sync mode we don't have a callback set. if (callback_data.callback == nullptr) { return; } callback_data.callback(result, callback_data.user); } } // namespace dronelink <commit_msg>device_impl: just send commands without ack<commit_after>#include "global_include.h" #include "device_impl.h" #include "dronelink_impl.h" #include <unistd.h> namespace dronelink { DeviceImpl::DeviceImpl(DroneLinkImpl *parent) : _mavlink_handler_table(), _timeout_handler_map_mutex(), _timeout_handler_map(), _target_system_id(0), _target_component_id(0), _target_uuid(0), _target_supports_mission_int(false), _parent(parent), _command_result(MAV_RESULT_FAILED), _command_state(CommandState::NONE), _result_callback_data({nullptr, nullptr}), _device_thread(nullptr), _should_exit(false), _timeout_s(DEFAULT_TIMEOUT_S) { using namespace std::placeholders; // for `_1` register_mavlink_message_handler(MAVLINK_MSG_ID_HEARTBEAT, std::bind(&DeviceImpl::process_heartbeat, this, _1), this); register_mavlink_message_handler(MAVLINK_MSG_ID_COMMAND_ACK, std::bind(&DeviceImpl::process_command_ack, this, _1), this); register_mavlink_message_handler(MAVLINK_MSG_ID_AUTOPILOT_VERSION, std::bind(&DeviceImpl::process_autopilot_version, this, _1), this); } DeviceImpl::~DeviceImpl() { _should_exit = true; unregister_all_mavlink_message_handlers(this); if (_device_thread != nullptr) { _device_thread->join(); delete _device_thread; _device_thread = nullptr; } } void DeviceImpl::register_mavlink_message_handler(uint8_t msg_id, mavlink_message_handler_t callback, const void *cookie) { MavlinkHandlerTableEntry entry = {msg_id, callback, cookie}; _mavlink_handler_table.push_back(entry); } void DeviceImpl::unregister_all_mavlink_message_handlers(const void *cookie) { for (auto it = _mavlink_handler_table.begin(); it != _mavlink_handler_table.end(); /* no ++it */) { if (it->cookie == cookie) { it = _mavlink_handler_table.erase(it); } else { ++it; } } } void DeviceImpl::register_timeout_handler(timeout_handler_t callback, const void *cookie) { std::lock_guard<std::mutex> lock(_timeout_handler_map_mutex); dl_time_t future_time = steady_time_in_future(_timeout_s); TimeoutHandlerMapEntry entry = {future_time, callback}; _timeout_handler_map.insert({cookie, entry}); } void DeviceImpl::update_timeout_handler(const void *cookie) { std::lock_guard<std::mutex> lock(_timeout_handler_map_mutex); auto it = _timeout_handler_map.find(cookie); if (it != _timeout_handler_map.end()) { dl_time_t future_time = steady_time_in_future(_timeout_s); it->second.time = future_time; } } void DeviceImpl::unregister_timeout_handler(const void *cookie) { std::lock_guard<std::mutex> lock(_timeout_handler_map_mutex); auto it = _timeout_handler_map.find(cookie); if (it != _timeout_handler_map.end()) { _timeout_handler_map.erase(cookie); } } void DeviceImpl::process_mavlink_message(const mavlink_message_t &message) { for (auto it = _mavlink_handler_table.begin(); it != _mavlink_handler_table.end(); ++it) { if (it->msg_id == message.msgid) { it->callback(message); } } } void DeviceImpl::process_heartbeat(const mavlink_message_t &message) { mavlink_heartbeat_t heartbeat; mavlink_msg_heartbeat_decode(&message, &heartbeat); if (_target_system_id == 0) { _target_system_id = message.sysid; _target_component_id = message.compid; } if (_target_uuid == 0) { request_autopilot_version(); } check_device_thread(); } void DeviceImpl::process_command_ack(const mavlink_message_t &message) { mavlink_command_ack_t command_ack; mavlink_msg_command_ack_decode(&message, &command_ack); // Ignore it if we're not waiting for an ack result. if (_command_state == CommandState::WAITING) { _command_result = (MAV_RESULT)command_ack.result; // Update state after result to avoid a race over _command_result _command_state = CommandState::RECEIVED; if (_command_result == MAV_RESULT_ACCEPTED) { report_result(_result_callback_data, Result::SUCCESS); } else { report_result(_result_callback_data, Result::COMMAND_DENIED); } _result_callback_data.callback = nullptr; _result_callback_data.user = nullptr; } } void DeviceImpl::process_autopilot_version(const mavlink_message_t &message) { mavlink_autopilot_version_t autopilot_version; mavlink_msg_autopilot_version_decode(&message, &autopilot_version); _target_uuid = autopilot_version.uid; _target_supports_mission_int = autopilot_version.capabilities & MAV_PROTOCOL_CAPABILITY_MISSION_INT; } void DeviceImpl::check_device_thread() { if (_device_thread == nullptr) { _device_thread = new std::thread(device_thread, this); } } void DeviceImpl::device_thread(DeviceImpl *parent) { const unsigned heartbeat_interval_us = 1000000; const unsigned timeout_interval_us = 10000; const unsigned heartbeat_multiplier = heartbeat_interval_us / timeout_interval_us; unsigned counter = 0; while (!parent->_should_exit) { if (counter++ % heartbeat_multiplier == 0) { send_heartbeat(parent); } check_timeouts(parent); usleep(timeout_interval_us); } } void DeviceImpl::send_heartbeat(DeviceImpl *parent) { mavlink_message_t message; mavlink_msg_heartbeat_pack(_own_system_id, _own_component_id, &message, MAV_TYPE_GCS, 0, 0, 0, 0); parent->send_message(message); } void DeviceImpl::check_timeouts(DeviceImpl *parent) { timeout_handler_t callback = nullptr; { std::lock_guard<std::mutex> lock(parent->_timeout_handler_map_mutex); for (auto it = parent->_timeout_handler_map.begin(); it != parent->_timeout_handler_map.end(); /* no ++it */) { // If time is passed, call timeout callback. if (it->second.time < steady_time()) { callback = it->second.callback; //Self-destruct before calling to avoid locking issues. parent->_timeout_handler_map.erase(it++); break; } else { ++it; } } } // Now that the lock is out of scope and therefore unlocked, we're safe // to call the callback if set which might in turn register new timeout callbacks. if (callback != nullptr) { callback(); } } Result DeviceImpl::send_message(const mavlink_message_t &message) { return _parent->send_message(message); } void DeviceImpl::request_autopilot_version() { send_command(MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES, {1.0f, NAN, NAN, NAN, NAN, NAN, NAN}); } uint64_t DeviceImpl::get_target_uuid() const { return _target_uuid; } uint8_t DeviceImpl::get_target_system_id() const { return _target_system_id; } uint8_t DeviceImpl::get_target_component_id() const { return _target_component_id; } Result DeviceImpl::send_command(uint16_t command, const DeviceImpl::CommandParams &params) { if (_target_system_id == 0 && _target_component_id == 0) { return Result::DEVICE_NOT_CONNECTED; } // We don't need no ack, just send it. //if (_command_state == CommandState::WAITING) { // return Result::DEVICE_BUSY; //} mavlink_message_t message; mavlink_msg_command_long_pack(_own_system_id, _own_component_id, &message, _target_system_id, _target_component_id, command, 0, params.v[0], params.v[1], params.v[2], params.v[3], params.v[4], params.v[5], params.v[6]); Result ret = _parent->send_message(message); if (ret != Result::SUCCESS) { return ret; } return Result::SUCCESS; } Result DeviceImpl::send_command_with_ack(uint16_t command, const DeviceImpl::CommandParams &params) { if (_command_state == CommandState::WAITING) { return Result::DEVICE_BUSY; } // No callback here, so let's make sure it's reset _result_callback_data.callback = nullptr; _result_callback_data.user = nullptr; _command_state = CommandState::WAITING; Result ret = send_command(command, params); if (ret != Result::SUCCESS) { return ret; } const unsigned timeout_us = unsigned(_timeout_s * 1e6); const unsigned wait_time_us = 1000; const unsigned iterations = timeout_us/wait_time_us; // Wait until we have received a result. for (unsigned i = 0; i < iterations; ++i) { if (_command_state == CommandState::RECEIVED) { break; } usleep(wait_time_us); } if (_command_state != CommandState::RECEIVED) { _command_state = CommandState::NONE; return Result::TIMEOUT; } // Reset _command_state = CommandState::NONE; if (_command_result != MAV_RESULT_ACCEPTED) { return Result::COMMAND_DENIED; } return Result::SUCCESS; } void DeviceImpl::send_command_with_ack_async(uint16_t command, const DeviceImpl::CommandParams &params, ResultCallbackData callback_data) { if (_command_state == CommandState::WAITING) { report_result(callback_data, Result::DEVICE_BUSY); } Result ret = send_command(command, params); if (ret != Result::SUCCESS) { report_result(callback_data, ret); // Reset _command_state = CommandState::NONE; return; } _command_state = CommandState::WAITING; _result_callback_data = callback_data; } void DeviceImpl::report_result(ResultCallbackData callback_data, Result result) { // Never use a nullptr as a callback, this is not an error // because in sync mode we don't have a callback set. if (callback_data.callback == nullptr) { return; } callback_data.callback(result, callback_data.user); } } // namespace dronelink <|endoftext|>
<commit_before><commit_msg>silence annoying log output<commit_after><|endoftext|>
<commit_before>#include "ircd.hpp" #include "tokens.hpp" #include <algorithm> #include <set> #include <debug> #include <timer> #include <kernel/syscalls.hpp> IrcServer::IrcServer( Network& inet_, uint16_t port, const std::string& name, const std::string& netw, motd_func_t mfunc) : inet(inet_), server_name(name), server_network(netw), motd_func(mfunc) { // initialize lookup tables extern void transform_init(); transform_init(); // timeout for clients and servers using namespace std::chrono; Timers::periodic(10s, 5s, delegate<void(uint32_t)>::from<IrcServer, &IrcServer::timeout_handler>(this)); // server listener (although IRC servers usually have many ports open) auto& tcp = inet.tcp(); auto& server_port = tcp.bind(port); server_port.on_connect( [this] (auto csock) { // one more client in total inc_counter(STAT_TOTAL_CONNS); inc_counter(STAT_TOTAL_USERS); inc_counter(STAT_LOCAL_USERS); // possibly set new max users connected if (get_counter(STAT_MAX_USERS) < get_counter(STAT_TOTAL_USERS)) set_counter(STAT_MAX_USERS, get_counter(STAT_LOCAL_USERS)); // in case splitter is bad SET_CRASH_CONTEXT("server_port.on_connect(): %s", csock->remote().to_string().c_str()); debug("*** Received connection from %s\n", csock->remote().to_string().c_str()); /// create client /// size_t clindex = new_client(); auto& client = clients[clindex]; // make sure crucial fields are reset properly client.reset_to(csock); // set up callbacks csock->on_read(128, [this, clindex] (net::tcp::buffer_t buffer, size_t bytes) { auto& client = clients[clindex]; client.read(buffer.get(), bytes); }); csock->on_close( [this, clindex] { // for the case where the client has not voluntarily quit, auto& client = clients[clindex]; // tell everyone that he just disconnected char buff[256]; int len = snprintf(buff, sizeof(buff), ":%s QUIT :%s\r\n", client.nickuserhost().c_str(), "Connection closed"); client.handle_quit(buff, len); // force-free resources client.disable(); }); }); // set timestamp for when the server was started this->created_ts = create_timestamp(); this->created_string = std::string(ctime(&created_ts)); this->cheapstamp = this->created_ts; } size_t IrcServer::new_client() { // use prev dead client if (!free_clients.empty()) { size_t idx = free_clients.back(); free_clients.pop_back(); return idx; } // create new client clients.emplace_back(clients.size(), *this); return clients.size()-1; } size_t IrcServer::new_channel() { // use prev dead channel if (!free_channels.empty()) { size_t idx = free_channels.back(); free_channels.pop_back(); return idx; } // create new channel channels.emplace_back(channels.size(), *this); return channels.size()-1; } #include <kernel/syscalls.hpp> void IrcServer::free_client(Client& client) { // give back the client id free_clients.push_back(client.get_id()); // give back nickname, if any if (!client.nick().empty()) erase_nickname(client.nick()); // one less client in total on server dec_counter(STAT_TOTAL_USERS); dec_counter(STAT_LOCAL_USERS); } IrcServer::uindex_t IrcServer::user_by_name(const std::string& name) const { auto it = h_users.find(name); if (it != h_users.end()) return it->second; return NO_SUCH_CHANNEL; } IrcServer::chindex_t IrcServer::channel_by_name(const std::string& name) const { auto it = h_channels.find(name); if (it != h_channels.end()) return it->second; return NO_SUCH_CHANNEL; } IrcServer::chindex_t IrcServer::create_channel(const std::string& name) { auto ch = new_channel(); get_channel(ch).reset(name); inc_counter(STAT_CHANNELS); return ch; } void IrcServer::free_channel(Channel& ch) { // give back channel id free_channels.push_back(ch.get_id()); // give back channel name erase_channel(ch.name()); // less channels on server/network dec_counter(STAT_CHANNELS); } void IrcServer::user_bcast(uindex_t idx, const std::string& from, uint16_t tk, const std::string& msg) { char buffer[256]; int len = snprintf(buffer, sizeof(buffer), ":%s %03u %s", from.c_str(), tk, msg.c_str()); user_bcast(idx, buffer, len); } void IrcServer::user_bcast(uindex_t idx, const char* buffer, size_t len) { std::set<uindex_t> uset; // add user uset.insert(idx); // for each channel user is in for (auto ch : get_client(idx).channels()) { // insert all users from channel into set for (auto cl : get_channel(ch).clients()) uset.insert(cl); } // broadcast message for (auto cl : uset) get_client(cl).send_raw(buffer, len); } void IrcServer::user_bcast_butone(uindex_t idx, const std::string& from, uint16_t tk, const std::string& msg) { char buffer[256]; int len = snprintf(buffer, sizeof(buffer), ":%s %03u %s", from.c_str(), tk, msg.c_str()); user_bcast_butone(idx, buffer, len); } void IrcServer::user_bcast_butone(uindex_t idx, const char* buffer, size_t len) { std::set<uindex_t> uset; // for each channel user is in for (auto ch : get_client(idx).channels()) { // insert all users from channel into set for (auto cl : get_channel(ch).clients()) uset.insert(cl); } // make sure user is not included uset.erase(idx); // broadcast message for (auto cl : uset) get_client(cl).send_raw(buffer, len); } <commit_msg>Prevent dead client from being disabled twice<commit_after>#include "ircd.hpp" #include "tokens.hpp" #include <algorithm> #include <set> #include <debug> #include <timer> #include <kernel/syscalls.hpp> IrcServer::IrcServer( Network& inet_, uint16_t port, const std::string& name, const std::string& netw, motd_func_t mfunc) : inet(inet_), server_name(name), server_network(netw), motd_func(mfunc) { // initialize lookup tables extern void transform_init(); transform_init(); // timeout for clients and servers using namespace std::chrono; Timers::periodic(10s, 5s, delegate<void(uint32_t)>::from<IrcServer, &IrcServer::timeout_handler>(this)); // server listener (although IRC servers usually have many ports open) auto& tcp = inet.tcp(); auto& server_port = tcp.bind(port); server_port.on_connect( [this] (auto csock) { // one more client in total inc_counter(STAT_TOTAL_CONNS); inc_counter(STAT_TOTAL_USERS); inc_counter(STAT_LOCAL_USERS); // possibly set new max users connected if (get_counter(STAT_MAX_USERS) < get_counter(STAT_TOTAL_USERS)) set_counter(STAT_MAX_USERS, get_counter(STAT_LOCAL_USERS)); // in case splitter is bad SET_CRASH_CONTEXT("server_port.on_connect(): %s", csock->remote().to_string().c_str()); debug("*** Received connection from %s\n", csock->remote().to_string().c_str()); /// create client /// size_t clindex = new_client(); auto& client = clients[clindex]; // make sure crucial fields are reset properly client.reset_to(csock); // set up callbacks csock->on_read(128, [this, clindex] (net::tcp::buffer_t buffer, size_t bytes) { auto& client = clients[clindex]; client.read(buffer.get(), bytes); }); csock->on_close( [this, clindex] { // for the case where the client has not voluntarily quit, auto& client = clients[clindex]; if (UNLIKELY(!client.is_alive())) return; // tell everyone that he just disconnected char buff[128]; int len = snprintf(buff, sizeof(buff), ":%s QUIT :%s\r\n", client.nickuserhost().c_str(), "Connection closed"); client.handle_quit(buff, len); // force-free resources client.disable(); }); }); // set timestamp for when the server was started this->created_ts = create_timestamp(); this->created_string = std::string(ctime(&created_ts)); this->cheapstamp = this->created_ts; } size_t IrcServer::new_client() { // use prev dead client if (!free_clients.empty()) { size_t idx = free_clients.back(); free_clients.pop_back(); return idx; } // create new client clients.emplace_back(clients.size(), *this); return clients.size()-1; } size_t IrcServer::new_channel() { // use prev dead channel if (!free_channels.empty()) { size_t idx = free_channels.back(); free_channels.pop_back(); return idx; } // create new channel channels.emplace_back(channels.size(), *this); return channels.size()-1; } #include <kernel/syscalls.hpp> void IrcServer::free_client(Client& client) { // give back the client id free_clients.push_back(client.get_id()); // give back nickname, if any if (!client.nick().empty()) erase_nickname(client.nick()); // one less client in total on server dec_counter(STAT_TOTAL_USERS); dec_counter(STAT_LOCAL_USERS); } IrcServer::uindex_t IrcServer::user_by_name(const std::string& name) const { auto it = h_users.find(name); if (it != h_users.end()) return it->second; return NO_SUCH_CHANNEL; } IrcServer::chindex_t IrcServer::channel_by_name(const std::string& name) const { auto it = h_channels.find(name); if (it != h_channels.end()) return it->second; return NO_SUCH_CHANNEL; } IrcServer::chindex_t IrcServer::create_channel(const std::string& name) { auto ch = new_channel(); get_channel(ch).reset(name); inc_counter(STAT_CHANNELS); return ch; } void IrcServer::free_channel(Channel& ch) { // give back channel id free_channels.push_back(ch.get_id()); // give back channel name erase_channel(ch.name()); // less channels on server/network dec_counter(STAT_CHANNELS); } void IrcServer::user_bcast(uindex_t idx, const std::string& from, uint16_t tk, const std::string& msg) { char buffer[256]; int len = snprintf(buffer, sizeof(buffer), ":%s %03u %s", from.c_str(), tk, msg.c_str()); user_bcast(idx, buffer, len); } void IrcServer::user_bcast(uindex_t idx, const char* buffer, size_t len) { std::set<uindex_t> uset; // add user uset.insert(idx); // for each channel user is in for (auto ch : get_client(idx).channels()) { // insert all users from channel into set for (auto cl : get_channel(ch).clients()) uset.insert(cl); } // broadcast message for (auto cl : uset) get_client(cl).send_raw(buffer, len); } void IrcServer::user_bcast_butone(uindex_t idx, const std::string& from, uint16_t tk, const std::string& msg) { char buffer[256]; int len = snprintf(buffer, sizeof(buffer), ":%s %03u %s", from.c_str(), tk, msg.c_str()); user_bcast_butone(idx, buffer, len); } void IrcServer::user_bcast_butone(uindex_t idx, const char* buffer, size_t len) { std::set<uindex_t> uset; // for each channel user is in for (auto ch : get_client(idx).channels()) { // insert all users from channel into set for (auto cl : get_channel(ch).clients()) uset.insert(cl); } // make sure user is not included uset.erase(idx); // broadcast message for (auto cl : uset) get_client(cl).send_raw(buffer, len); } <|endoftext|>
<commit_before>#include <pcl/point_cloud.h> #include <pcl_ros/point_cloud.h> #include <ros/publisher.h> #include <ros/ros.h> #include <stdlib.h> #include <Eigen/Core> #include <opencv2/opencv.hpp> #include <opencv2/core/eigen.hpp> #include <pcl_ros/transforms.h> //#include <igvc_msgs> ros::Publisher pointcloud_pub; cv::Mat published_map; // get to work Eigen::Matrix<char, Eigen::Dynamic, Eigen::Dynamic> global_holder; tf::StampedTransform lidar_trans; tf::StampedTransform cam_trans; tf::TransformListener *tf_listener; std::string topics; double resolution; double position [2]; int length; int width; void frame_callback(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &msg, const std::string &topic) { //transform pointcloud into the occupancy grid, no filtering right now bool offMap = false; //cv::Mat frame(msg->points); //make transformed clouds pcl::PointCloud<pcl::PointXYZ>::Ptr transformed = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>()); if (msg->header.frame_id == "/scan/pointcloud") { pcl_ros::transformPointCloud(*msg, *transformed, lidar_trans); } else { pcl_ros::transformPointCloud(*msg, *transformed, cam_trans); } pcl::PointCloud<pcl::PointXYZ>::const_iterator point; for (point = transformed->begin(); point < transformed->points.end(); point++) { int x = (int) std::round((point->x / resolution) + position[0]); int y = (int) std::round((point->y / resolution) + position[1]); if(x > 0 && y > 0 && x < length && y < width) { global_holder(x, y) = 1.0; } else if(!offMap){ ROS_WARN_STREAM("Some points out of range, won't be put on map."); offMap = true; } } //won't work until we make a message to publish //igvc_msgs::map map = new igvc_msgs::map(); //pointcloud_pub.publish(published_map); //pointcloud_pub.publish(&global_map); } int main(int argc, char **argv) { ros::init(argc, argv, "new_mapper"); ros::NodeHandle nh; ros::NodeHandle pNh("~"); std::list<ros::Subscriber> subs; tf_listener = new tf::TransformListener(); double start_x; double start_y; pNh.getParam("topics", topics); pNh.getParam("occupancy_grid_length", length); pNh.getParam("occupancy_grid_width", width); pNh.getParam("qoccupancy_grid_resolution", resolution); pNh.getParam("start_X", start_x); pNh.getParam("start_Y", start_y); length = (int) std::round(length / resolution); width = (int) std::round(width / resolution); position[0] = (int) std::round(start_x / resolution); position[1] = (int) std::round(start_y / resolution); //set up tokens and get list of subscribers std::istringstream iss(topics); std::vector<std::string> tokens{ std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>() }; for (std::string topic : tokens) { ROS_INFO_STREAM("Mapper subscribing to " << topic); subs.push_back(nh.subscribe<pcl::PointCloud<pcl::PointXYZ>>(topic, 1, boost::bind(frame_callback, _1, topic))); } //init transforms ros::Time time = ros::Time::now(); if (tf_listener->waitForTransform("/odom", "/scan/pointcloud", time, ros::Duration(5.0))) { tf_listener->lookupTransform("/odom", "/scan/pointcloud", time, lidar_trans); } if (tf_listener->waitForTransform("/odom", "/usb_cam_center/line_cloud", time, ros::Duration(5.0))) { tf_listener->lookupTransform("/odom", "/usb_cam_center/line_cloud", time, cam_trans); } //TODO: Initialize the map variables, not working //global_map = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>(length, width); published_map = cv::Mat(length, width, CV_8UC1); // I cant instatiate this //https://docs.opencv.org/2.4/doc/tutorials/core/mat_the_basic_image_container/mat_the_basic_image_container.html cv::cv2eigen(published_map, global_holder); // I can't instantiate this either //https://stackoverflow.com/questions/14783329/opencv-cvmat-and-eigenmatrix pointcloud_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>("/map", 1); ros::spin(); } <commit_msg>added eigen map<commit_after>#include <pcl/point_cloud.h> #include <pcl_ros/point_cloud.h> #include <ros/publisher.h> #include <ros/ros.h> #include <stdlib.h> #include <Eigen/Core> #include <opencv2/opencv.hpp> #include <opencv2/core/eigen.hpp> #include <pcl_ros/transforms.h> //#include <igvc_msgs> ros::Publisher pointcloud_pub; cv::Mat* published_map; // get to work tf::StampedTransform lidar_trans; tf::StampedTransform cam_trans; tf::TransformListener *tf_listener; std::string topics; double resolution; double position [2]; int length_y; int width_x; Eigen::Map<Eigen::Matrix<char, Eigen::Dynamic, Eigen::Dynamic>>* eigenRep; void frame_callback(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &msg, const std::string &topic) { //transform pointcloud into the occupancy grid, no filtering right now bool offMap = false; //cv::Mat frame(msg->points); //make transformed clouds pcl::PointCloud<pcl::PointXYZ>::Ptr transformed = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>()); if (msg->header.frame_id == "/scan/pointcloud") { pcl_ros::transformPointCloud(*msg, *transformed, lidar_trans); } else { pcl_ros::transformPointCloud(*msg, *transformed, cam_trans); } pcl::PointCloud<pcl::PointXYZ>::const_iterator point; for (point = transformed->begin(); point < transformed->points.end(); point++) { int x = (int) std::round((point->x / resolution) + position[0]); int y = (int) std::round((point->y / resolution) + position[1]); if(x > 0 && y > 0 && x < length_y && y < width_x) { (*(eigenRep))(x,y) = 1.0; } else if(!offMap){ ROS_WARN_STREAM("Some points out of range, won't be put on map."); offMap = true; } } //won't work until we make a message to publish //igvc_msgs::map map = new igvc_msgs::map(); //pointcloud_pub.publish(published_map); //pointcloud_pub.publish(&global_map); } int main(int argc, char **argv) { ros::init(argc, argv, "new_mapper"); ros::NodeHandle nh; ros::NodeHandle pNh("~"); std::list<ros::Subscriber> subs; tf_listener = new tf::TransformListener(); double start_x; double start_y; pNh.getParam("topics", topics); pNh.getParam("occupancy_grid_length", length_y); pNh.getParam("occupancy_grid_width", width_x); pNh.getParam("qoccupancy_grid_resolution", resolution); pNh.getParam("start_X", start_x); pNh.getParam("start_Y", start_y); length_y = (int) std::round(length_y / resolution); width_x = (int) std::round(width_x / resolution); position[0] = (int) std::round(start_x / resolution); position[1] = (int) std::round(start_y / resolution); //set up tokens and get list of subscribers std::istringstream iss(topics); std::vector<std::string> tokens{ std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>() }; for (std::string topic : tokens) { ROS_INFO_STREAM("Mapper subscribing to " << topic); subs.push_back(nh.subscribe<pcl::PointCloud<pcl::PointXYZ>>(topic, 1, boost::bind(frame_callback, _1, topic))); } //init transforms ros::Time time = ros::Time::now(); if (tf_listener->waitForTransform("/odom", "/scan/pointcloud", time, ros::Duration(5.0))) { tf_listener->lookupTransform("/odom", "/scan/pointcloud", time, lidar_trans); } if (tf_listener->waitForTransform("/odom", "/usb_cam_center/line_cloud", time, ros::Duration(5.0))) { tf_listener->lookupTransform("/odom", "/usb_cam_center/line_cloud", time, cam_trans); } //TODO: Initialize the map variables, not working //global_map = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>(length, width); published_map = new cv::Mat(length_y, width_x, CV_8UC1); // I cant instatiate this //https://docs.opencv.org/2.4/doc/tutorials/core/mat_the_basic_image_container/mat_the_basic_image_container.html eigenRep = new Eigen::Map<Eigen::Matrix<char, Eigen::Dynamic, Eigen::Dynamic>>((char*) published_map, length_y, width_x); //https://stackoverflow.com/questions/14783329/opencv-cvmat-and-eigenmatrix pointcloud_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>("/map", 1); ros::spin(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ScrollHelper.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: oj $ $Date: 2002-07-05 09:28:02 $ * * 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 DBAUI_SCROLLHELPER_HXX #include "ScrollHelper.hxx" #endif #define LISTBOX_SCROLLING_AREA 12 namespace dbaui { // ----------------------------------------------------------------------------- OScrollHelper::OScrollHelper() { } // ----------------------------------------------------------------------------- OScrollHelper::~OScrollHelper() { } // ----------------------------------------------------------------------------- void OScrollHelper::scroll(const Point& _rPoint, const Size& _rOutputSize) { // Scrolling Areas Rectangle aScrollArea( Point(0, _rOutputSize.Height() - LISTBOX_SCROLLING_AREA), Size(_rOutputSize.Width(), LISTBOX_SCROLLING_AREA) ); Link aToCall; // if pointer in bottom area begin scroll if( aScrollArea.IsInside(_rPoint) ) aToCall = m_aUpScroll; else { aScrollArea.SetPos(Point(0,0)); // if pointer in top area begin scroll if( aScrollArea.IsInside(_rPoint) ) aToCall = m_aDownScroll; } if ( aToCall.IsSet() ) aToCall.Call( NULL ); } // ----------------------------------------------------------------------------- } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS ooo19126 (1.2.478); FILE MERGED 2005/09/05 17:33:22 rt 1.2.478.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ScrollHelper.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 14:32:18 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef DBAUI_SCROLLHELPER_HXX #include "ScrollHelper.hxx" #endif #define LISTBOX_SCROLLING_AREA 12 namespace dbaui { // ----------------------------------------------------------------------------- OScrollHelper::OScrollHelper() { } // ----------------------------------------------------------------------------- OScrollHelper::~OScrollHelper() { } // ----------------------------------------------------------------------------- void OScrollHelper::scroll(const Point& _rPoint, const Size& _rOutputSize) { // Scrolling Areas Rectangle aScrollArea( Point(0, _rOutputSize.Height() - LISTBOX_SCROLLING_AREA), Size(_rOutputSize.Width(), LISTBOX_SCROLLING_AREA) ); Link aToCall; // if pointer in bottom area begin scroll if( aScrollArea.IsInside(_rPoint) ) aToCall = m_aUpScroll; else { aScrollArea.SetPos(Point(0,0)); // if pointer in top area begin scroll if( aScrollArea.IsInside(_rPoint) ) aToCall = m_aDownScroll; } if ( aToCall.IsSet() ) aToCall.Call( NULL ); } // ----------------------------------------------------------------------------- } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: TableRowExchange.hxx,v $ * * $Revision: 1.1 $ * * last change: $Author: oj $ $Date: 2001-03-22 07:46:15 $ * * 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 DBAUI_TABLEROW_EXCHANGE_HXX #define DBAUI_TABLEROW_EXCHANGE_HXX #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #ifndef _TRANSFER_HXX #include <svtools/transfer.hxx> #endif namespace dbaui { class OTableRow; class OTableRowExchange : public TransferableHelper { ::std::vector<OTableRow*> m_vTableRow; public: OTableRowExchange(const ::std::vector<OTableRow*>& _rvTableRow); protected: virtual void AddSupportedFormats(); virtual sal_Bool GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor ); virtual sal_Bool WriteObject( SotStorageStreamRef& rxOStm, void* pUserObject, sal_uInt32 nUserObjectId, const ::com::sun::star::datatransfer::DataFlavor& rFlavor ); virtual void ObjectReleased(); }; } #endif // DBAUI_TABLEROW_EXCHANGE_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.1.506); FILE MERGED 2005/09/05 17:34:29 rt 1.1.506.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TableRowExchange.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 15:37:46 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef DBAUI_TABLEROW_EXCHANGE_HXX #define DBAUI_TABLEROW_EXCHANGE_HXX #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #ifndef _TRANSFER_HXX #include <svtools/transfer.hxx> #endif namespace dbaui { class OTableRow; class OTableRowExchange : public TransferableHelper { ::std::vector<OTableRow*> m_vTableRow; public: OTableRowExchange(const ::std::vector<OTableRow*>& _rvTableRow); protected: virtual void AddSupportedFormats(); virtual sal_Bool GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor ); virtual sal_Bool WriteObject( SotStorageStreamRef& rxOStm, void* pUserObject, sal_uInt32 nUserObjectId, const ::com::sun::star::datatransfer::DataFlavor& rFlavor ); virtual void ObjectReleased(); }; } #endif // DBAUI_TABLEROW_EXCHANGE_HXX <|endoftext|>
<commit_before>/***************************************************************************** * interface_widgets.hpp : Custom widgets for the main interface **************************************************************************** * Copyright (C) 2006-2008 the VideoLAN team * $Id$ * * Authors: Clément Stenac <zorglub@videolan.org> * Jean-Baptiste Kempf <jb@videolan.org> * Rafaël Carré <funman@videolanorg> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef _INTFWIDGETS_H_ #define _INTFWIDGETS_H_ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "main_interface.hpp" /* Interface integration */ #include "input_manager.hpp" /* Speed control */ #include "components/controller.hpp" #include "components/controller_widget.hpp" #include "dialogs_provider.hpp" #include "components/info_panels.hpp" #include <QWidget> #include <QFrame> #include <QLabel> #include <QMouseEvent> #include <QPropertyAnimation> #include <QLinkedList> class ResizeEvent; class QPixmap; class QHBoxLayout; class QMenu; class QSlider; /******************** Video Widget ****************/ class VideoWidget : public QFrame { Q_OBJECT public: VideoWidget( intf_thread_t * ); virtual ~VideoWidget(); WId request( int *, int *, unsigned int *, unsigned int *, bool ); void release( void ); int control( void *, int, va_list ); void sync( void ); protected: virtual QPaintEngine *paintEngine() const { return NULL; } private: intf_thread_t *p_intf; QWidget *stable; QLayout *layout; signals: void sizeChanged( int, int ); public slots: void SetSizing( unsigned int, unsigned int ); }; /******************** Background Widget ****************/ class BackgroundWidget : public QWidget { Q_OBJECT public: BackgroundWidget( intf_thread_t * ); void setExpandstoHeight( bool b_expand ) { b_expandPixmap = b_expand; } void setWithArt( bool b_withart_ ) { b_withart = b_withart_; }; private: intf_thread_t *p_intf; QString pixmapUrl; bool b_expandPixmap; bool b_withart; QPropertyAnimation *fadeAnimation; virtual void contextMenuEvent( QContextMenuEvent *event ); protected: void paintEvent( QPaintEvent *e ); virtual void showEvent( QShowEvent * e ); static const int MARGIN = 5; QString defaultArt; public slots: void toggle(){ TOGGLEV( this ); } void updateArt( const QString& ); }; class EasterEggBackgroundWidget : public BackgroundWidget { Q_OBJECT public: EasterEggBackgroundWidget( intf_thread_t * ); virtual ~EasterEggBackgroundWidget(); public slots: void animate(); protected: void paintEvent( QPaintEvent *e ); void showEvent( QShowEvent *e ); void hideEvent( QHideEvent * ); void resizeEvent( QResizeEvent * ); private slots: void spawnFlakes(); void reset(); private: struct flake { QPoint point; bool b_fat; }; QTimer *timer; QLinkedList<flake *> *flakes; int i_rate; int i_speed; bool b_enabled; static const int MAX_FLAKES = 1000; }; #if 0 class VisualSelector : public QFrame { Q_OBJECT public: VisualSelector( intf_thread_t *); virtual ~VisualSelector(); private: intf_thread_t *p_intf; QLabel *current; private slots: void prev(); void next(); }; #endif class ClickableQLabel : public QLabel { Q_OBJECT public: virtual void mouseDoubleClickEvent( QMouseEvent *event ) { Q_UNUSED( event ); emit doubleClicked(); } signals: void doubleClicked(); }; class TimeLabel : public ClickableQLabel { Q_OBJECT public: enum Display { Elapsed, Remaining, Both }; TimeLabel( intf_thread_t *_p_intf, TimeLabel::Display _displayType = TimeLabel::Both ); protected: virtual void mousePressEvent( QMouseEvent *event ) { if( displayType == TimeLabel::Elapsed ) return; toggleTimeDisplay(); event->accept(); } virtual void mouseDoubleClickEvent( QMouseEvent *event ) { if( displayType != TimeLabel::Both ) return; event->accept(); toggleTimeDisplay(); ClickableQLabel::mouseDoubleClickEvent( event ); } private: intf_thread_t *p_intf; bool b_remainingTime; int cachedLength; QTimer *bufTimer; bool buffering; bool showBuffering; float bufVal; TimeLabel::Display displayType; char psz_length[MSTRTIME_MAX_SIZE]; char psz_time[MSTRTIME_MAX_SIZE]; void toggleTimeDisplay(); void paintEvent( QPaintEvent* ); private slots: void setDisplayPosition( float pos, int64_t time, int length ); void setDisplayPosition( float pos ); void updateBuffering( float ); void updateBuffering(); }; class SpeedLabel : public QLabel { Q_OBJECT public: SpeedLabel( intf_thread_t *, QWidget * ); virtual ~SpeedLabel(); protected: virtual void mousePressEvent ( QMouseEvent * event ) { showSpeedMenu( event->pos() ); } private slots: void showSpeedMenu( QPoint ); void setRate( float ); private: intf_thread_t *p_intf; QMenu *speedControlMenu; QString tooltipStringPattern; SpeedControlWidget *speedControl; }; /******************** Speed Control Widgets ****************/ class SpeedControlWidget : public QFrame { Q_OBJECT public: SpeedControlWidget( intf_thread_t *, QWidget * ); void updateControls( float ); private: intf_thread_t* p_intf; QSlider* speedSlider; QDoubleSpinBox* spinBox; int lastValue; public slots: void activateOnState(); private slots: void updateRate( int ); void updateSpinBoxRate( double ); void resetRate(); }; class CoverArtLabel : public QLabel { Q_OBJECT public: CoverArtLabel( QWidget *parent, intf_thread_t * ); void setItem( input_item_t * ); virtual ~CoverArtLabel(); protected: virtual void mouseDoubleClickEvent( QMouseEvent *event ) { if( ! p_item && qobject_cast<MetaPanel *>(this->window()) == NULL ) { THEDP->mediaInfoDialog(); } event->accept(); } private: intf_thread_t *p_intf; input_item_t *p_item; public slots: void showArtUpdate( const QString& ); void showArtUpdate( input_item_t * ); void askForUpdate(); void setArtFromFile(); void clear(); }; #endif <commit_msg>Qt: VideoWidget: remove unimplemented method<commit_after>/***************************************************************************** * interface_widgets.hpp : Custom widgets for the main interface **************************************************************************** * Copyright (C) 2006-2008 the VideoLAN team * $Id$ * * Authors: Clément Stenac <zorglub@videolan.org> * Jean-Baptiste Kempf <jb@videolan.org> * Rafaël Carré <funman@videolanorg> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef _INTFWIDGETS_H_ #define _INTFWIDGETS_H_ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "main_interface.hpp" /* Interface integration */ #include "input_manager.hpp" /* Speed control */ #include "components/controller.hpp" #include "components/controller_widget.hpp" #include "dialogs_provider.hpp" #include "components/info_panels.hpp" #include <QWidget> #include <QFrame> #include <QLabel> #include <QMouseEvent> #include <QPropertyAnimation> #include <QLinkedList> class ResizeEvent; class QPixmap; class QHBoxLayout; class QMenu; class QSlider; /******************** Video Widget ****************/ class VideoWidget : public QFrame { Q_OBJECT public: VideoWidget( intf_thread_t * ); virtual ~VideoWidget(); WId request( int *, int *, unsigned int *, unsigned int *, bool ); void release( void ); void sync( void ); protected: virtual QPaintEngine *paintEngine() const { return NULL; } private: intf_thread_t *p_intf; QWidget *stable; QLayout *layout; signals: void sizeChanged( int, int ); public slots: void SetSizing( unsigned int, unsigned int ); }; /******************** Background Widget ****************/ class BackgroundWidget : public QWidget { Q_OBJECT public: BackgroundWidget( intf_thread_t * ); void setExpandstoHeight( bool b_expand ) { b_expandPixmap = b_expand; } void setWithArt( bool b_withart_ ) { b_withart = b_withart_; }; private: intf_thread_t *p_intf; QString pixmapUrl; bool b_expandPixmap; bool b_withart; QPropertyAnimation *fadeAnimation; virtual void contextMenuEvent( QContextMenuEvent *event ); protected: void paintEvent( QPaintEvent *e ); virtual void showEvent( QShowEvent * e ); static const int MARGIN = 5; QString defaultArt; public slots: void toggle(){ TOGGLEV( this ); } void updateArt( const QString& ); }; class EasterEggBackgroundWidget : public BackgroundWidget { Q_OBJECT public: EasterEggBackgroundWidget( intf_thread_t * ); virtual ~EasterEggBackgroundWidget(); public slots: void animate(); protected: void paintEvent( QPaintEvent *e ); void showEvent( QShowEvent *e ); void hideEvent( QHideEvent * ); void resizeEvent( QResizeEvent * ); private slots: void spawnFlakes(); void reset(); private: struct flake { QPoint point; bool b_fat; }; QTimer *timer; QLinkedList<flake *> *flakes; int i_rate; int i_speed; bool b_enabled; static const int MAX_FLAKES = 1000; }; #if 0 class VisualSelector : public QFrame { Q_OBJECT public: VisualSelector( intf_thread_t *); virtual ~VisualSelector(); private: intf_thread_t *p_intf; QLabel *current; private slots: void prev(); void next(); }; #endif class ClickableQLabel : public QLabel { Q_OBJECT public: virtual void mouseDoubleClickEvent( QMouseEvent *event ) { Q_UNUSED( event ); emit doubleClicked(); } signals: void doubleClicked(); }; class TimeLabel : public ClickableQLabel { Q_OBJECT public: enum Display { Elapsed, Remaining, Both }; TimeLabel( intf_thread_t *_p_intf, TimeLabel::Display _displayType = TimeLabel::Both ); protected: virtual void mousePressEvent( QMouseEvent *event ) { if( displayType == TimeLabel::Elapsed ) return; toggleTimeDisplay(); event->accept(); } virtual void mouseDoubleClickEvent( QMouseEvent *event ) { if( displayType != TimeLabel::Both ) return; event->accept(); toggleTimeDisplay(); ClickableQLabel::mouseDoubleClickEvent( event ); } private: intf_thread_t *p_intf; bool b_remainingTime; int cachedLength; QTimer *bufTimer; bool buffering; bool showBuffering; float bufVal; TimeLabel::Display displayType; char psz_length[MSTRTIME_MAX_SIZE]; char psz_time[MSTRTIME_MAX_SIZE]; void toggleTimeDisplay(); void paintEvent( QPaintEvent* ); private slots: void setDisplayPosition( float pos, int64_t time, int length ); void setDisplayPosition( float pos ); void updateBuffering( float ); void updateBuffering(); }; class SpeedLabel : public QLabel { Q_OBJECT public: SpeedLabel( intf_thread_t *, QWidget * ); virtual ~SpeedLabel(); protected: virtual void mousePressEvent ( QMouseEvent * event ) { showSpeedMenu( event->pos() ); } private slots: void showSpeedMenu( QPoint ); void setRate( float ); private: intf_thread_t *p_intf; QMenu *speedControlMenu; QString tooltipStringPattern; SpeedControlWidget *speedControl; }; /******************** Speed Control Widgets ****************/ class SpeedControlWidget : public QFrame { Q_OBJECT public: SpeedControlWidget( intf_thread_t *, QWidget * ); void updateControls( float ); private: intf_thread_t* p_intf; QSlider* speedSlider; QDoubleSpinBox* spinBox; int lastValue; public slots: void activateOnState(); private slots: void updateRate( int ); void updateSpinBoxRate( double ); void resetRate(); }; class CoverArtLabel : public QLabel { Q_OBJECT public: CoverArtLabel( QWidget *parent, intf_thread_t * ); void setItem( input_item_t * ); virtual ~CoverArtLabel(); protected: virtual void mouseDoubleClickEvent( QMouseEvent *event ) { if( ! p_item && qobject_cast<MetaPanel *>(this->window()) == NULL ) { THEDP->mediaInfoDialog(); } event->accept(); } private: intf_thread_t *p_intf; input_item_t *p_item; public slots: void showArtUpdate( const QString& ); void showArtUpdate( input_item_t * ); void askForUpdate(); void setArtFromFile(); void clear(); }; #endif <|endoftext|>
<commit_before>// This file is part of Poseidon. // Copyleft 2020, LH_Mouse. All wrongs reserved. #include "../precompiled.hpp" #include "abstract_tls_socket.hpp" #include "socket_address.hpp" #include "../utilities.hpp" #include <netinet/tcp.h> namespace poseidon { namespace { IO_Result do_translate_ssl_error(const char* func, ::SSL* ssl, int ret) { int err = ::SSL_get_error(ssl, ret); switch(err) { case SSL_ERROR_NONE: case SSL_ERROR_ZERO_RETURN: // normal closure return io_result_eof; case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_ACCEPT: // retry return io_result_again; case SSL_ERROR_SYSCALL: // syscall errno err = errno; if(err == 0) return io_result_eof; if(err == EINTR) return io_result_not_eof; POSEIDON_SSL_THROW("irrecoverable SSL I/O error\n" "[`$1()` returned `$2`; errno: $3]", func, ret, noadl::format_errno(err)); default: POSEIDON_SSL_THROW("irrecoverable SSL error\n" "[`$1()` returned `$2`]", func, ret); } } } // namespace Abstract_TLS_Socket:: ~Abstract_TLS_Socket() { } void Abstract_TLS_Socket:: do_set_common_options() { // Disables Nagle algorithm. static constexpr int yes[] = { -1 }; int res = ::setsockopt(this->get_fd(), IPPROTO_TCP, TCP_NODELAY, yes, sizeof(yes)); ROCKET_ASSERT(res == 0); // This can be overwritten if `async_connect()` is called later. ::SSL_set_accept_state(this->m_ssl); } void Abstract_TLS_Socket:: do_stream_preconnect_nolock() { ::SSL_set_connect_state(this->m_ssl); } IO_Result Abstract_TLS_Socket:: do_stream_read_nolock(void* data, size_t size) { int nread = ::SSL_read(this->m_ssl, data, static_cast<int>(::rocket::min(size, UINT_MAX / 2))); if(nread > 0) return static_cast<IO_Result>(nread); return do_translate_ssl_error("SSL_read", this->m_ssl, nread); } IO_Result Abstract_TLS_Socket:: do_stream_write_nolock(const void* data, size_t size) { int nwritten = ::SSL_write(this->m_ssl, data, static_cast<int>(::rocket::min(size, UINT_MAX / 2))); if(nwritten > 0) return static_cast<IO_Result>(nwritten); return do_translate_ssl_error("SSL_write", this->m_ssl, nwritten); } IO_Result Abstract_TLS_Socket:: do_stream_preshutdown_nolock() { int ret = ::SSL_shutdown(this->m_ssl); if(ret == 0) ret = ::SSL_shutdown(this->m_ssl); if(ret == 1) return io_result_eof; return do_translate_ssl_error("SSL_shutdown", this->m_ssl, ret); } void Abstract_TLS_Socket:: do_on_async_establish() { POSEIDON_LOG_INFO("Secure TCP connection established: local '$1', remote '$2'", this->get_local_address(), this->get_remote_address()); } void Abstract_TLS_Socket:: do_on_async_shutdown(int err) { POSEIDON_LOG_INFO("Secure TCP connection closed: local '$1', $2", this->get_local_address(), noadl::format_errno(err)); } } // namespace poseidon <commit_msg>network/abstract_tls_socket: Cleanup<commit_after>// This file is part of Poseidon. // Copyleft 2020, LH_Mouse. All wrongs reserved. #include "../precompiled.hpp" #include "abstract_tls_socket.hpp" #include "socket_address.hpp" #include "../utilities.hpp" #include <netinet/tcp.h> namespace poseidon { namespace { IO_Result do_translate_ssl_error(const char* func, ::SSL* ssl, int ret) { int err = ::SSL_get_error(ssl, ret); switch(err) { case SSL_ERROR_NONE: case SSL_ERROR_ZERO_RETURN: // normal closure return io_result_eof; case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_ACCEPT: // retry return io_result_again; case SSL_ERROR_SYSCALL: // syscall errno err = errno; if(err == 0) return io_result_eof; if(err == EINTR) return io_result_not_eof; POSEIDON_SSL_THROW("irrecoverable SSL I/O error\n" "[`$1()` returned `$2`; $3]", func, ret, noadl::format_errno(err)); default: POSEIDON_SSL_THROW("irrecoverable SSL error\n" "[`$1()` returned `$2`]", func, ret); } } } // namespace Abstract_TLS_Socket:: ~Abstract_TLS_Socket() { } void Abstract_TLS_Socket:: do_set_common_options() { // Disables Nagle algorithm. static constexpr int yes[] = { -1 }; int res = ::setsockopt(this->get_fd(), IPPROTO_TCP, TCP_NODELAY, yes, sizeof(yes)); ROCKET_ASSERT(res == 0); // This can be overwritten if `async_connect()` is called later. ::SSL_set_accept_state(this->m_ssl); } void Abstract_TLS_Socket:: do_stream_preconnect_nolock() { ::SSL_set_connect_state(this->m_ssl); } IO_Result Abstract_TLS_Socket:: do_stream_read_nolock(void* data, size_t size) { int nread = ::SSL_read(this->m_ssl, data, static_cast<int>(::rocket::min(size, UINT_MAX / 2))); if(nread > 0) return static_cast<IO_Result>(nread); return do_translate_ssl_error("SSL_read", this->m_ssl, nread); } IO_Result Abstract_TLS_Socket:: do_stream_write_nolock(const void* data, size_t size) { int nwritten = ::SSL_write(this->m_ssl, data, static_cast<int>(::rocket::min(size, UINT_MAX / 2))); if(nwritten > 0) return static_cast<IO_Result>(nwritten); return do_translate_ssl_error("SSL_write", this->m_ssl, nwritten); } IO_Result Abstract_TLS_Socket:: do_stream_preshutdown_nolock() { int ret = ::SSL_shutdown(this->m_ssl); if(ret == 0) ret = ::SSL_shutdown(this->m_ssl); if(ret == 1) return io_result_eof; return do_translate_ssl_error("SSL_shutdown", this->m_ssl, ret); } void Abstract_TLS_Socket:: do_on_async_establish() { POSEIDON_LOG_INFO("Secure TCP connection established: local '$1', remote '$2'", this->get_local_address(), this->get_remote_address()); } void Abstract_TLS_Socket:: do_on_async_shutdown(int err) { POSEIDON_LOG_INFO("Secure TCP connection closed: local '$1', $2", this->get_local_address(), noadl::format_errno(err)); } } // namespace poseidon <|endoftext|>
<commit_before>/* * Logger.cpp * * Created on: May 31, 2017 * Author: liebman */ #include "Logger.h" #ifdef DEBUG_LOGGER #define DBP_BUF_SIZE 256 unsigned int snprintf(char*, unsigned int, ...); #define dbprintf(...) {char dbp_buf[DBP_BUF_SIZE]; snprintf(dbp_buf, DBP_BUF_SIZE-1, __VA_ARGS__); Serial.print(dbp_buf);} #define dbprintln(x) Serial.println(x) #define dbflush() Serial.flush() #else #define dbprintf(...) #define dbprint(x) #define dbprintln(x) #define dbflush() #endif Logger::Logger() { _host = NULL; _port = 0; } void Logger::begin() { begin(LOGGER_DEFAULT_BAUD); } void Logger::begin(long int baud) { Serial.begin(baud); } void Logger::end() { #ifdef USE_TCP _client.stop(); #endif } void Logger::setNetworkLogger(const char* host, uint16_t port) { _host = host; _port = port; } void Logger::println(const char* message) { Serial.println(message); send(message); } extern int vsnprintf(char* buffer, size_t size, const char* fmt, va_list args); void Logger::printf(const char* fmt, ...) { va_list argp; va_start(argp, fmt); vsnprintf(_buffer, LOGGER_BUFFER_SIZE-1, fmt, argp); va_end(argp); Serial.print(_buffer); send(_buffer); } void Logger::flush() { Serial.flush(); } void Logger::send(const char* message) { // if we are not configured for TCP then just return if (_host == NULL) { return; } IPAddress ip; if (!WiFi.isConnected()) { dbprintln("Logger::log: not connected!"); return; } if (!WiFi.hostByName(_host, ip)) { dbprintf("Logger::log failed to resolve address for:%s\n", _host); return; } #ifdef USE_TCP if (!_client.connected()) { if(!_client.connect(ip, _port)) { dbprintf("Logger::send failed to connect!\n"); return; } } if (_client.write(message) != strlen(message)) { dbprintf("Logger::write failed to write message: %s\n", message); return; } _client.flush(); #else _udp.beginPacket(ip, _port); _udp.write(message); if (!_udp.endPacket()) { dbprintln("Logger::log failed to send packet!"); } #endif } Logger logger; <commit_msg>make sure newline is sent to TCP!<commit_after>/* * Logger.cpp * * Created on: May 31, 2017 * Author: liebman */ #include "Logger.h" #ifdef DEBUG_LOGGER #define DBP_BUF_SIZE 256 unsigned int snprintf(char*, unsigned int, ...); #define dbprintf(...) {char dbp_buf[DBP_BUF_SIZE]; snprintf(dbp_buf, DBP_BUF_SIZE-1, __VA_ARGS__); Serial.print(dbp_buf);} #define dbprintln(x) Serial.println(x) #define dbflush() Serial.flush() #else #define dbprintf(...) #define dbprint(x) #define dbprintln(x) #define dbflush() #endif Logger::Logger() { _host = NULL; _port = 0; } void Logger::begin() { begin(LOGGER_DEFAULT_BAUD); } void Logger::begin(long int baud) { Serial.begin(baud); } void Logger::end() { #ifdef USE_TCP _client.stop(); #endif } void Logger::setNetworkLogger(const char* host, uint16_t port) { _host = host; _port = port; } void Logger::println(const char* message) { snprintf(_buffer, LOGGER_BUFFER_SIZE-1, "%s\n", message); Serial.print(_buffer); send(_buffer); } extern int vsnprintf(char* buffer, size_t size, const char* fmt, va_list args); void Logger::printf(const char* fmt, ...) { va_list argp; va_start(argp, fmt); vsnprintf(_buffer, LOGGER_BUFFER_SIZE-1, fmt, argp); va_end(argp); Serial.print(_buffer); send(_buffer); } void Logger::flush() { Serial.flush(); } void Logger::send(const char* message) { // if we are not configured for TCP then just return if (_host == NULL) { return; } IPAddress ip; if (!WiFi.isConnected()) { dbprintln("Logger::log: not connected!"); return; } if (!WiFi.hostByName(_host, ip)) { dbprintf("Logger::log failed to resolve address for:%s\n", _host); return; } #ifdef USE_TCP if (!_client.connected()) { if(!_client.connect(ip, _port)) { dbprintf("Logger::send failed to connect!\n"); return; } } if (_client.write(message) != strlen(message)) { dbprintf("Logger::write failed to write message: %s\n", message); return; } _client.flush(); #else _udp.beginPacket(ip, _port); _udp.write(message); if (!_udp.endPacket()) { dbprintln("Logger::log failed to send packet!"); } #endif } Logger logger; <|endoftext|>
<commit_before>// Copyright 2015 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 "flutter/flow/layers/clip_rrect_layer.h" namespace flow { ClipRRectLayer::ClipRRectLayer() {} ClipRRectLayer::~ClipRRectLayer() {} void ClipRRectLayer::Preroll(PrerollContext* context, const SkMatrix& matrix) { PrerollChildren(context, matrix); if (!context->child_paint_bounds.intersect(clip_rrect_.getBounds())) context->child_paint_bounds.setEmpty(); set_paint_bounds(context->child_paint_bounds); } void ClipRRectLayer::Paint(PaintContext& context) { TRACE_EVENT0("flutter", "ClipRRectLayer::Paint"); SkAutoCanvasRestore save(&context.canvas, false); context.canvas.saveLayer(&paint_bounds(), nullptr); context.canvas.clipRRect(clip_rrect_); PaintChildren(context); } } // namespace flow <commit_msg>Force anti-aliasing on clipRRect calls. (#2982)<commit_after>// Copyright 2015 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 "flutter/flow/layers/clip_rrect_layer.h" namespace flow { ClipRRectLayer::ClipRRectLayer() {} ClipRRectLayer::~ClipRRectLayer() {} void ClipRRectLayer::Preroll(PrerollContext* context, const SkMatrix& matrix) { PrerollChildren(context, matrix); if (!context->child_paint_bounds.intersect(clip_rrect_.getBounds())) context->child_paint_bounds.setEmpty(); set_paint_bounds(context->child_paint_bounds); } void ClipRRectLayer::Paint(PaintContext& context) { TRACE_EVENT0("flutter", "ClipRRectLayer::Paint"); SkAutoCanvasRestore save(&context.canvas, false); context.canvas.saveLayer(&paint_bounds(), nullptr); context.canvas.clipRRect(clip_rrect_, SkRegion::kIntersect_Op, true); PaintChildren(context); } } // namespace flow <|endoftext|>
<commit_before>/************************************************************************************ ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file g_sys.cpp * @version * @brief * @author duye * @date 2014-03-04 * @note * * 1. 2014-03-04 duye Created this file * */ #include <unistd.h> #include <stdarg.h> #include <sys/time.h> #include <stdio.h> #include <string.h> #include <g_sys.h> using namespace gsys; void System::sleep(const GUint64 time) { ::sleep(time); } void System::usleep(const GUint64 time) { ::usleep(time); } GUint64 System::pformat(GInt8* buffer, const GUint64 size, const GInt8* args, ...) { va_list vaList; va_start(vaList, args); GUint64 strLen = vsnprintf(buffer, size, args, vaList); va_end(vaList); return strLen; } GResult System::shell(const GInt8* cmd) { G_ASSERT(cmd != NULL); FILE* retStream = popen(cmd, "r"); if (retStream == NULL) { return G_NO; } pclose(retStream); return G_YES; } GResult System::shell(const GInt8* cmd, GInt8* buffer, const GUint32 size) { G_ASSERT(cmd != NULL && buffer != NULL && size > 0); FILE* retStream = popen(cmd, "r"); if (retStream == NULL) { return G_NO; } memset(buffer, 0, size); fread(buffer, sizeof(GInt8), size, retStream); pclose(retStream); return G_YES; } GUint64 System::getSysTime() { struct timeval now; struct timezone tz; if (gettimeofday(&now, &tz) < 0) { return 0; } return (GUint64)(now.tv_sec) * 1000000 + now.tv_usec; } GResult System::getSysTime(const GInt8* format, GInt8* buffer, const GUint32 size) { struct timeval now; struct timezone tz; if (gettimeofday(&now, &tz) < 0) { return 0; } } <commit_msg>Update g_sys.cpp<commit_after>/************************************************************************************ ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file g_sys.cpp * @version * @brief * @author duye * @date 2014-03-04 * @note * * 1. 2014-03-04 duye Created this file * */ #include <unistd.h> #include <stdarg.h> #include <sys/time.h> #include <stdio.h> #include <string.h> #include <g_sys.h> using namespace gsys; void System::sleep(const GUint64 time) { ::sleep(time); } void System::usleep(const GUint64 time) { ::usleep(time); } GUint64 System::pformat(GInt8* buffer, const GUint64 size, const GInt8* args, ...) { va_list vaList; va_start(vaList, args); GUint64 strLen = vsnprintf(buffer, size, args, vaList); va_end(vaList); return strLen; } GResult System::shell(const GInt8* cmd) { G_ASSERT(cmd != NULL); FILE* retStream = popen(cmd, "r"); if (retStream == NULL) { return G_NO; } pclose(retStream); return G_YES; } GResult System::shell(const GInt8* cmd, GInt8* buffer, const GUint32 size) { G_ASSERT(cmd != NULL && buffer != NULL && size > 0); FILE* retStream = popen(cmd, "r"); if (retStream == NULL) { return G_NO; } memset(buffer, 0, size); fread(buffer, sizeof(GInt8), size, retStream); pclose(retStream); return G_YES; } GUint64 System::getSysTime() { struct timeval now; struct timezone tz; if (gettimeofday(&now, &tz) < 0) { return 0; } return (GUint64)(now.tv_sec) * 1000000 + now.tv_usec; } GResult System::getSysTime(const GInt8* format, GInt8* buffer, const GUint32 size) { struct timeval tv; struct tm tm; size_t len = 28; gettimeofday(&tv, NULL); localtime_r(&tv.tv_sec, &tm); strftime(buf, len, "%Y-%m-%d %H:%M:%S", &tm); len = strlen(buf); sprintf(buf + len, ".%06.6d", (int)(tv.tv_usec)); return buf; } <|endoftext|>
<commit_before>#pragma once #include "LinearContainer.hpp" namespace morda{ /** * @brief Horizontal container widget. * Row is a horizontal variant of linear container. From GUI scripts it can be instantiated as "Row". */ class Row : public LinearContainer{ public: Row(const stob::Node* chain) : Widget(chain), LinearContainer(chain, false) {} Row(const Row&) = delete; Row& operator=(const Row&) = delete; }; } <commit_msg>stuff<commit_after>#pragma once #include "LinearContainer.hpp" namespace morda{ /** * @brief Horizontal container widget. * Row is a horizontal variant of linear container. From GUI scripts it can be instantiated as "Row". */ class Row : public LinearContainer{ public: Row(const puu::forest& desc) : widget(desc), LinearContainer(desc, false) {} Row(const stob::Node* chain) : Row(stob_to_puu(chain)){} Row(const Row&) = delete; Row& operator=(const Row&) = delete; }; } <|endoftext|>
<commit_before> class TEveProjectionManager; class TEveGeoShape; class TEveElement; class TEveElementList; TEveProjectionManager * proj = 0; TEveGeoShape * geom = 0; void tpc_tracks(const char *input=0) { // // // if (input){ TString ipath(input); if (ipath.Contains(".zip")){ gSystem->Exec("rm TPC*"); gSystem->Exec("rm AliESD*"); if (ipath.Contains("root:/")){ char command[1000]; sprintf(command,"xrdcp %s in.zip",input); gSystem->Exec(command); } if (ipath.Contains("alien:/")){ char command[1000]; sprintf(command,"alien_cp %s in.zip",input); gSystem->Exec(command); } gSystem->Exec("unzip in.zip"); } } TEveUtil::LoadMacro("alieve_init.C"); alieve_init(".", -1); TEveUtil::LoadMacro("geom_gentle.C"); TEveUtil::LoadMacro("primary_vertex.C"); TEveUtil::LoadMacro("esd_tracks.C"); TEveUtil::LoadMacro("its_clusters.C+"); TEveUtil::LoadMacro("tpc_clusters.C+"); TEveViewer* nv = gEve->SpawnNewViewer("NLT Projected"); TEveScene* ns = gEve->SpawnNewScene("NLT"); nv->AddScene(ns); TGLViewer* v = nv->GetGLViewer(); v->SetCurrentCamera(TGLViewer::kCameraOrthoXOY); TGLCameraMarkupStyle* mup = v->GetCameraMarkup(); if(mup) mup->SetShow(kFALSE); TEveTrackCounter* g_trkcnt = new TEveTrackCounter("Primary Counter"); gEve->AddToListTree(g_trkcnt, kFALSE); TEveProjectionManager* p = new TEveProjectionManager; proj = p; gEve->AddToListTree(p, kTRUE); gEve->AddElement(proj, ns); // geometry TEveGeoShape* gg = geom_gentle(); geom = gg; // event gEvent->AddNewEventCommand("on_new_event();"); gEvent->GotoEvent(0); gEve->Redraw3D(kTRUE); } /**************************************************************************/ void on_new_event() { try { //TEvePointSet* itsc = its_clusters(); //itsc->SetMarkerColor(5); TEvePointSet* tpcc = tpc_clusters(); tpcc->SetMarkerColor(4); } catch(TEveException& exc) { printf("Exception loading ITS/TPC clusters: %s\n", exc.Data()); } TEveTrackList* cont = esd_tracks(); cont->SetLineWidth((Width_t)2); TEveElement* top = gEve->GetCurrentEvent(); proj->DestroyElements(); //AliESDEvent* esd = AliEveEventManager::AssertESD(); // geom proj->ImportElements(geom); // event proj->ImportElements(top); // top->SetRnrState(kFALSE); } <commit_msg>Modification for new Eve (Marian)<commit_after> class TEveProjectionManager; class TEveGeoShape; class TEveElement; class TEveElementList; TEveProjectionManager * proj = 0; TEveGeoShape * geom = 0; void tpc_tracks(const char *input=0) { // // // if (input){ TString ipath(input); if (ipath.Contains(".zip")){ gSystem->Exec("rm TPC*"); gSystem->Exec("rm AliESD*"); if (ipath.Contains("root:/")){ char command[1000]; sprintf(command,"xrdcp %s in.zip",input); gSystem->Exec(command); } if (ipath.Contains("alien:/")){ char command[1000]; sprintf(command,"alien_cp %s in.zip",input); gSystem->Exec(command); } gSystem->Exec("unzip in.zip"); } } TEveUtil::LoadMacro("alieve_init.C"); alieve_init(".", -1); TEveUtil::LoadMacro("geom_gentle.C"); TEveUtil::LoadMacro("primary_vertex.C"); TEveUtil::LoadMacro("esd_tracks.C"); TEveUtil::LoadMacro("its_clusters.C+"); TEveUtil::LoadMacro("tpc_clusters.C+"); TEveViewer* nv = gEve->SpawnNewViewer("NLT Projected"); TEveScene* ns = gEve->SpawnNewScene("NLT"); nv->AddScene(ns); TGLViewer* v = nv->GetGLViewer(); v->SetCurrentCamera(TGLViewer::kCameraOrthoXOY); TGLCameraMarkupStyle* mup = v->GetCameraMarkup(); if(mup) mup->SetShow(kFALSE); TEveTrackCounter* g_trkcnt = new TEveTrackCounter("Primary Counter"); gEve->AddToListTree(g_trkcnt, kFALSE); TEveProjectionManager* p = new TEveProjectionManager; proj = p; gEve->AddToListTree(p, kTRUE); gEve->AddElement(proj, ns); // geometry TEveGeoShape* gg = geom_gentle(); geom = gg; // event gAliEveEvent->AddNewEventCommand("on_new_event();"); gAliEveEvent->GotoEvent(0); gEve->Redraw3D(kTRUE); } /**************************************************************************/ void on_new_event() { try { //TEvePointSet* itsc = its_clusters(); //itsc->SetMarkerColor(5); TEvePointSet* tpcc = tpc_clusters(); tpcc->SetMarkerColor(4); } catch(TEveException& exc) { printf("Exception loading ITS/TPC clusters: %s\n", exc.Data()); } TEveTrackList* cont = esd_tracks(); cont->SetLineWidth((Width_t)2); TEveElement* top = gEve->GetCurrentEvent(); proj->DestroyElements(); //AliESDEvent* esd = AliEveEventManager::AssertESD(); // geom proj->ImportElements(geom); // event proj->ImportElements(top); // top->SetRnrState(kFALSE); } <|endoftext|>